/* Minification failed. Returning unminified contents.
MinifyJavaScript(1290,36-37): error JS1028: Expected identifier or string: }
 */
var HomeRepository = {
    DownloadContent: function (currentTab, otherCode) {
        contentRequest = {
            LogonId: BrowserStorage.getLogonId(),
            CurrentTab: currentTab,
            //BookId: 'PWR1701B',
            FeatureName: currentTab == 'wrd' ? 'Wiring Regulations' : 'Other Guidance',
            OtherCode: otherCode
            //GnRegNos: [],
            //OsgRegNos: [],
            //ChapterId: ''
        }
        var object = {
            Data: { "contentRequest": contentRequest }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'ContentManagement/ContentAccess.svc/GetContentForDownload',
            function success(data) {
                if (data.Status == ResultStatus.Successful && data.LoginStatus == ResultStatus.Successful) {
                    if (data.ResultObject != null) {

                        var XMLString = (data.ResultObject.XMLString == null) ? "" : data.ResultObject.XMLString;

                        var options = { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 };

                        var EncryptedXMLString = CryptoJS.AES.encrypt(XMLString, "aaaaaaaaaaaaaaaa", options);

                        try {
                            var expiryDate = GetExpiryDate();
                            if (currentTab == "wrd") {
                                store.set("WRDBook", { name: "WRDBook", XMLString: EncryptedXMLString.toString(), expiryDate: expiryDate });
                            } else if (currentTab == "osg") {
                                store.set("OSGBook", { name: "OSGBook", XMLString: EncryptedXMLString.toString(), expiryDate: expiryDate });
                            }
                        }
                        catch (error) {
                            if (error.message.toLowerCase().indexOf("quotaexceeded")) {

                                MessageViewModel = new MessageViewModel();
                                MessageViewModel.CreateErrorMessage("Local storage quota exceeded");
                                MessageViewModel.ShowOverLay();
                            }
                            else {
                                MessageViewModel = new MessageViewModel();
                                MessageViewModel.CreateErrorMessage(error);
                                MessageViewModel.ShowOverLay();
                            }
                            return false;
                        }
                        MessageViewModel = new MessageViewModel();
                        MessageViewModel.CreateSuccessMessage("Content has been made offline", "overlayId", "okButtonId", "");
                        MessageViewModel.ShowOverLay();
                    }
                }
                else {
                    sessionStorage.setItem("RedirectLocation", Application.Home.BaseURL);
                    location.href = "view/" + Application.Login.BaseURL;
                }
            },
            function error(data) {
            }, JSON.stringify(object.Data)
        );
    },
    getAllVideos: function (currentRouteSetting, routeProvider, routeCurrentContext, homeFilter) {

        var _this = this;
        var object = {
            Data: { "homeFilter": homeFilter }
        };
        var logonId = BrowserStorage.getLogonId();
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetVideoVideoModel',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {

                    //Bind all subscriptions to view.
                    if (data.ResultObject == null) {
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {

                        if (data.ResultObject.length != 0) {
                            $("#searchtextbox").val('');
                            $('#searchtextbox').datepicker('destroy');
                            $('#mobsearchtxtbox').datepicker('destroy');
                            $("#mobsearchtxtbox").val('');
                            $('#search_param').val('All categories');
                            $('#Search_button').html("All categories" + '<svg version="1.1" class="searchArrow" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 16.8 21" xml:space="preserve"><path id="Master_arrow_small" d="M2.2,10.4L6.8,15V0H10v15l4.6-4.6l2.2,2.2L8.4,21L0,12.6L2.2,10.4z" /></svg>');
                            $('#Mobile-btn').html("All categories" + '<svg version="1.1" class="searchArrowMob" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 16.8 21" xml:space="preserve"><path id="Master_arrow_small" d="M2.2,10.4L6.8,15V0H10v15l4.6-4.6l2.2,2.2L8.4,21L0,12.6L2.2,10.4z" /></svg>');

                            //SEO-Title
                            var keyword = ['IET TV', 'popular', 'latest', 'forthcoming', 'automobile'];
                            setMetaData("Home", "Home", keyword);
                            //SEO-Title

                            //  $("#Span1").html("All");

                            // var videos = jQuery.parseJSON(data.ResultObject.VideoList)
                            //var thumbnailurl = data.ResultObject.Player.ThumbnailUrl;
                            //var defaultimage = data.ResultObject.Player.DefaultImage;
                            var carousellist = data.ResultObject.Carousellist;


                            //RenderFeed();
                            /*Carousel Logic start */
                            var videoCarousel1 = '';
                            var videoCarousel2 = '';
                            var videoCarousel3 = '';

                            /*Carousel Logic start */
                            var mobilevideoCarousel1 = '';
                            var mobilevideoCarousel2 = '';
                            var mobilevideoCarousel3 = '';
                            var mobilevideoCarousel4 = '';
                            var mobilevideoCarousel5 = '';
                            var mobilevideoCarousel6 = '';

                            var topPosition = 0;
                            var leftPosition = 0;
                            /*Below are position constant*/
                            var topPosition0 = 0;
                            var leftPosition0 = 0
                            var topPosition260 = 260;
                            var leftPosition346 = 320;
                            var leftPosition692 = 640;
                            var leftPosition10 = 10;
                            var leftPosition399 = 399;
                            var topPosition520 = 520;

                            var count = 0;
                            var videoimage = ''
                            var mobilecount = 0;
                            //desktop logic
                            $.each(carousellist, function (index, data) {
                                data;
                                count = count + 1;
                                /*set top and left position value */
                                if (count % 6 == 1) {
                                    topPosition = topPosition0
                                    leftPosition = leftPosition0
                                }
                                else if (count % 6 == 2) {
                                    topPosition = topPosition0
                                    leftPosition = leftPosition346
                                }
                                else if (count % 6 == 3) {
                                    topPosition = topPosition0
                                    leftPosition = leftPosition692
                                }
                                else if (count % 6 == 4) {
                                    topPosition = topPosition260
                                    leftPosition = leftPosition0
                                }
                                else if (count % 6 == 5) {
                                    topPosition = topPosition260
                                    leftPosition = leftPosition346
                                }
                                else {
                                    topPosition = topPosition260
                                    leftPosition = leftPosition692
                                }
                                var time = new Date();
                                if (count <= 6) {

                                    //videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    videoCarousel1 += videoCarousel(leftPosition, topPosition, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, data.Duration, data.SubscriptionType, data.HasPromo, data.ChannelColor);
                                }
                                else if (count >= 7 && count <= 12) {
                                    //videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    videoCarousel2 += videoCarousel(leftPosition, topPosition, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, data.Duration, data.SubscriptionType, data.HasPromo, data.ChannelColor);
                                }
                                else if (count >= 12 && count <= 18) {
                                    // videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    videoCarousel3 += videoCarousel(leftPosition, topPosition, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, data.Duration, data.SubscriptionType, data.HasPromo, data.ChannelColor);
                                }
                            });


                            $(document).ready($('.full-slide-firstclass').html(videoCarousel1));
                            $(document).ready($('.full-slide-secondclass').html(videoCarousel2));
                            $(document).ready($('.full-slide-thirdclass').html(videoCarousel3));


                            RenderDesktopScriptHome();

                            //initiliazing cookie in home page so it will be displayed on everytime that we come to home
                            initializeCookie();

                            //mobile logic

                            var position = '';
                            $.each(carousellist, function (index, data) {
                                mobilecount = mobilecount + 1;
                                /*set top and left position value */
                                if (mobilecount % 3 == 1) {
                                    leftPosition = leftPosition10
                                    topPosition = topPosition0

                                }
                                else if (mobilecount % 3 == 2) {
                                    leftPosition = leftPosition10
                                    topPosition = topPosition520
                                }
                                else {
                                    leftPosition = leftPosition399
                                    topPosition = topPosition520
                                }
                                var time = new Date();

                                if (mobilecount <= 3) {
                                    if (mobilecount == 1) {
                                        position = 'top';
                                    }
                                    else {
                                        position = 'bottom';
                                    }
                                    // videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    mobilevideoCarousel1 += VideoCarouselMobile(leftPosition, topPosition, position, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, data.Duration, data.SubscriptionType, data.HasPromo, data.ChannelColor);
                                }
                                else if (mobilecount >= 4 && mobilecount <= 6) {
                                    if (mobilecount == 4) {
                                        position = 'top';
                                    }
                                    else {
                                        position = 'bottom';
                                    }
                                    //videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    mobilevideoCarousel2 += VideoCarouselMobile(leftPosition, topPosition, position, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, data.Duration, data.SubscriptionType, data.HasPromo, data.ChannelColor);
                                }
                                else if (mobilecount >= 7 && mobilecount <= 9) {
                                    if (mobilecount == 7) {
                                        position = 'top';
                                    }
                                    else {
                                        position = 'bottom';
                                    }
                                    // videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    mobilevideoCarousel3 += VideoCarouselMobile(leftPosition, topPosition, position, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, data.Duration, data.SubscriptionType, data.HasPromo, data.ChannelColor);
                                }
                                else if (mobilecount >= 10 && mobilecount <= 12) {
                                    if (mobilecount == 10) {
                                        position = 'top';
                                    }
                                    else {
                                        position = 'bottom';
                                    }
                                    //videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    mobilevideoCarousel4 += VideoCarouselMobile(leftPosition, topPosition, position, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, data.Duration, data.SubscriptionType, data.HasPromo, data.ChannelColor);
                                }

                                else if (mobilecount >= 13 && mobilecount <= 15) {
                                    if (mobilecount == 13) {
                                        position = 'top';
                                    }
                                    else {
                                        position = 'bottom';
                                    }
                                    // videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    mobilevideoCarousel5 += VideoCarouselMobile(leftPosition, topPosition, position, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, data.Duration, data.SubscriptionType, data.HasPromo, data.ChannelColor);
                                }
                                else if (mobilecount >= 16 && mobilecount <= 18) {
                                    if (mobilecount == 16) {
                                        position = 'top';
                                    }
                                    else {
                                        position = 'bottom';
                                    }
                                    //videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    mobilevideoCarousel6 += VideoCarouselMobile(leftPosition, topPosition, position, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, data.Duration, data.SubscriptionType, data.HasPromo, data.ChannelColor);
                                }
                            });

                            $(document).ready($('#firstslider').html(mobilevideoCarousel1));
                            $(document).ready($('#secondslider').html(mobilevideoCarousel2));
                            $(document).ready($('#thirdslider').html(mobilevideoCarousel3));
                            $(document).ready($('#forthslider').html(mobilevideoCarousel4));
                            $(document).ready($('#fifthslider').html(mobilevideoCarousel5));
                            $(document).ready($('#sixthslider').html(mobilevideoCarousel6));
                            $(document).ready(function () {
                            });

                            $(document).ready(function ($) { RenderMobileScriptHome(); });


                            /*Carousel Logic end */

                            //Stop the loader and open up the UI before lazy loading the other contents
                            Spinner.Stop();

                            $('.overlay').hide();

                            //_this.getPopularVideos(currentRouteSetting, routeProvider, routeCurrentContext, homeFilter);
                            //_this.getForthcomingVideos(currentRouteSetting, routeProvider, routeCurrentContext, homeFilter);
                            //_this.getLatestVideos(currentRouteSetting, routeProvider, routeCurrentContext, homeFilter);
                            //_this.getChannelMenu(currentRouteSetting, routeProvider, routeCurrentContext);


                        }
                        else {
                            $('#VideoTable').html("No records found.");
                        }
                        $('#NoRecordFound').hide();                        
                        routeProvider.bindInnerRoutes();
                        if (!WebService.DisableGA) {
                            storeurlDetailsInGA('Carousel');
                        }
                        //var IsEmergencyShown = IsNullOrEmpty(sessionStorage.getItem("IsEmergencyShown")) ? false : sessionStorage.getItem("IsEmergencyShown");
                        //var EmergencyId = IsNullOrEmpty(sessionStorage.getItem("EmergencyId")) ? 0 : sessionStorage.getItem("EmergencyId")

                        //if (IsEmergencyShown == false || EmergencyId!=0) {
                        //    var objLoginRepository = new LoginRepository();
                        //    objLoginRepository.EmergencyInformation();
                        //}
                    }
                }
            }
            ,
            function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();

            }, JSON.stringify(object.Data));




    },


    getPopularVideos: function (currentRouteSetting, routeProvider, routeCurrentContext, homeFilter) {
        var _this = this;
        var object = {
            Data: { "homeFilter": homeFilter }
        };
        var logonId = BrowserStorage.getLogonId();
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetPopularVideolist',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {

                        var popularlist = data.ResultObject.Popularlist;

                        var addtionaVideoHTML = '';

                        var viewAllHTML = ' ' +
                            '<div class="clearfix bottom-border"></div><div class="font-bold"><a >View all</a></div>';


                        addtionaVideoHTML = '<span class="font-bold fs-18 fc-black">Most Viewed</span>' +
                            '<hr>';
                        var time = new Date();
                        $.each(popularlist, function (index, data) {

                            addtionaVideoHTML += getAddtionaVideoHTML(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, false, 0, data.SubscriptionType, data.Duration);

                        });
                        var count = 0;
                        if (data.ResultObject != null) {
                            count = data.ResultObject.PopularlistCount;
                        }
                        addtionaVideoHTML += GetViewAllHTML('Popular', count);

                        $(document).ready($('#MostPopular').html(addtionaVideoHTML));
                        sessionStorage.setItem("ChannelName", "");

                        $('#LazyLoaderMostPopular').addClass('display-none');

                    }
                }
                routeProvider.bindInnerRoutes();

            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data))


    },


    getForthcomingVideos: function (currentRouteSetting, routeProvider, routeCurrentContext, homeFilter) {
        var _this = this;
        var object = {
            Data: { "homeFilter": homeFilter }
        };
        var logonId = BrowserStorage.getLogonId();
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetForthcomingVideolist',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        var forthcominglist = data.ResultObject.Forthcominglist;

                        var addtionaVideoHTML = '';


                        addtionaVideoHTML = '<span class="font-bold fs-18 fc-black">Coming up</span>' +
                            '<hr>';
                        var time = new Date();
                        $.each(forthcominglist, function (index, data) {

                            addtionaVideoHTML += getAddtionaVideoHTML(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, data.IsEvent, data.EventId, data.SubscriptionType, data.Duration);

                        });
                        if (data.ResultObject != null) {
                            count = data.ResultObject.ForthcominglistCount;
                        }
                        addtionaVideoHTML += GetViewAllHTML('Forthcoming', count);
                        sessionStorage.setItem("ChannelName", "");
                        $(document).ready($('#Forthcoming').html(addtionaVideoHTML));

                        $('#LazyLoaderForthcoming').addClass('display-none');

                    }
                }
                routeProvider.bindInnerRoutes();

            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data))


    },

    getLatestVideos: function (currentRouteSetting, routeProvider, routeCurrentContext, homeFilter) {
        var _this = this;
        var object = {
            Data: { "homeFilter": homeFilter }
        };
        var logonId = BrowserStorage.getLogonId();
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetLatestVideolist',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {

                        var LatestList = data.ResultObject.Latestlist;

                        var addtionaVideoHTML = '';


                        addtionaVideoHTML = '<span class="font-bold fs-18 fc-black">Latest</span>' +
                            '<hr>';
                        var time = new Date();
                        $.each(LatestList, function (index, data) {
                            addtionaVideoHTML += getAddtionaVideoHTML(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.IsJisc, false, 0, data.SubscriptionType, data.Duration);


                        });
                        if (data.ResultObject != null) {
                            count = data.ResultObject.LatestlistCount;
                        }
                        addtionaVideoHTML += GetViewAllHTML('Latest', count);

                        $(document).ready($('#Latest').html(addtionaVideoHTML));
                        sessionStorage.setItem("ChannelName", "");

                        $('#LazyLoaderLatest').addClass('display-none');

                    }
                }
                routeProvider.bindInnerRoutes();

            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data))


    },
    getChannelMenu: function (currentRouteSetting, routeProvider, routeCurrentContext) {

        var object = {
            Data: {
                "logonId": BrowserStorage.getLogonId()// IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")             
            }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/GetMenuChannels',
            function (data, status, headers, config) {

                if (data.Status == ResultStatus.Successful && data.ResultObject != null) {
                    if (data.ResultObject.length != 0) {
                        var strMobCategoryNames = "";
                        var strMobChannelNames = "";
                        var CntforMobile = 1;
                        var containercount = 0;
                        var categoryCount = 0;
                        $.each(data.ResultObject[0].ChannelMenuForMob.ResultObject, function (index, data) {

                            CntforMobile++;
                            var CategoryName = data.CategoryName;
                            var Maindiv = "";
                            var SecondDiv = "";
                            var channelLen = data.Channels.length;
                            var count = 1;
                            var container = "";


                            strMobCategoryNames = '<a href="#category' + CntforMobile + '" class="accordion-toggle menu-header-2 collapsed" data-toggle="collapse" data-parent=".sideMenuAccordoinChannelMenu" id="channelsTechnology">' + CategoryName + '</a>';
                            strMobCategoryNames += '<div class="panel-group sideMenuAccordoinChannelMenu">';
                            strMobCategoryNames += '<div class="panel panel-default">';

                            strMobCategoryNames += '<div class="panel-collapse collapse menu-submenu" id="category' + CntforMobile + '">'
                            strMobChannelNames = "";
                            for (k = 0; k < channelLen; k++) {
                                strMobChannelNames += '<a data-innerroutename="Channel" data-channelId=' + data.Channels[k].Id + ' data-color=' + data.Channels[k].Color + ' data-name="' + data.Channels[k].Name + '" data-hasIndex="true" class="list-group-item custom_pointer">' + data.Channels[k].Name + '</a>';
                                var container = "";
                                var cnt = 0;


                            }
                            strMobCategoryNames += strMobChannelNames + '</div></div></div>'
                            $(".divMobileChannel").append(strMobCategoryNames);

                            categoryCount++;
                        });


                        $.each(data.ResultObject, function (index, data) {
                            //if (index <= 5) {
                            //    //var CategoryNames = '<li class="channel-btn-desktop"><a href="#category_' + index + '" data-toggle="tab">' + data.CategoryName + ' &nbsp<i class="fa fa-grey fa-chevron-down"></i></a></li>';

                            //    //$('#CategoryMenu').append(CategoryNames);

                            //    //var ChannelMainDiv = "";
                            //    //ChannelMainDiv = document.createElement("div");
                            //    //ChannelMainDiv.setAttribute("class", 'tab-pane fade');
                            //    //ChannelMainDiv.setAttribute('id', 'category_' + index);
                            //    //var ChannelUnorderedList = document.createElement("ul");
                            //    //ChannelUnorderedList.setAttribute('class', 'channel-lists-details');

                            //    //for (i = 0; i < data.Channels.length; i++) {

                            //    //    var ChannelList = document.createElement("li");
                            //    //    var ChannelAnchor = document.createElement("a");
                            //    //    ChannelAnchor.setAttribute("data-innerroutename", "Channel");
                            //    //    ChannelAnchor.setAttribute("data-hasIndex", "true");
                            //    //    ChannelAnchor.setAttribute("data-ChannelId", data.Channels[i].Id);
                            //    //    ChannelAnchor.setAttribute("data-color", data.Channels[i].Color);
                            //    //    ChannelAnchor.setAttribute("data-name", data.Channels[i].Name);
                            //    //    ChannelAnchor.setAttribute('data-toggle', "tooltip");
                            //    //    ChannelAnchor.setAttribute('data-placement', "bottom");
                            //    //    ChannelAnchor.setAttribute('title', data.Channels[i].Name);

                            //    //    var currnetday = new Date();
                            //    //    var Channelimage = document.createElement("img");
                            //    //    var ChannelName = document.createElement("h3");
                            //    //    if (data.Channels[i].ChannelIconImage != "") {
                            //    //        Channelimage.setAttribute("src", data.Channels[i].ChannelIconImage + "?" + currnetday.getTime());
                            //    //    }
                            //    //    ChannelName.innerHTML = data.Channels[i].Name;


                            //    //    ChannelAnchor.appendChild(Channelimage);
                            //    //    ChannelAnchor.appendChild(ChannelName);
                            //    //    ChannelList.appendChild(ChannelAnchor);
                            //    //    ChannelUnorderedList.appendChild(ChannelList);

                            //    //}
                            //    ////ChannelUnorderedList.appendChild(ChannelList);
                            //    //ChannelMainDiv.appendChild(ChannelUnorderedList);

                            //    //$('#ChannelMenu').append(ChannelMainDiv);

                            //    //if(index <= 10)
                            //    //{
                            //    var CategoryNames = document.createElement("div");
                            //    //CategoryNames.setAttribute("class", "channel-btn-desktop");

                            //    var catName = document.createElement("div");
                            //    catName.setAttribute("class", "channel-title");

                            //    var paraCatName = document.createElement("p");
                            //    paraCatName.innerHTML = data.CategoryName;

                            //    catName.appendChild(paraCatName);
                            //    CategoryNames.appendChild(catName);
                            //    //CategoryNames.appendChild('<div class="channel-title"><p>' + data.CategoryName + '</p></div>');

                            //    $('#NewChannelDiv').append(CategoryNames);
                            //    var ChannelList = document.createElement("div");
                            //    var countChannels = 0;
                            //    var channelIndex = 0;

                            //    for (i = 0; i < data.Channels.length; i++) {

                            //        var ChannelParentDiv = document.createElement("div");
                            //        ChannelParentDiv.setAttribute("class", "channel-10");
                            //        var ChannelAnchor = document.createElement("a");
                            //        ChannelAnchor.setAttribute("data-innerroutename", "Channel");
                            //        ChannelAnchor.setAttribute("data-hasIndex", "true");
                            //        ChannelAnchor.setAttribute("data-ChannelId", data.Channels[i].Id);
                            //        ChannelAnchor.setAttribute("data-color", data.Channels[i].Color);
                            //        ChannelAnchor.setAttribute("data-name", data.Channels[i].Name);
                            //        ChannelAnchor.setAttribute('data-toggle', "tooltip");
                            //        ChannelAnchor.setAttribute('data-placement', "bottom");
                            //        ChannelAnchor.setAttribute('title', data.Channels[i].Name);

                            //        var currnetday = new Date();
                            //        var imageDiv = document.createElement("div");
                            //        imageDiv.setAttribute("class","channel-img");
                            //        var Channelimage = document.createElement("img");
                            //        imageDiv.appendChild(Channelimage);
                            //        var ChannelName = document.createElement("h4");
                            //        if (data.Channels[i].ChannelIconImage != "") {
                            //            Channelimage.setAttribute("src", data.Channels[i].ChannelIconImage + "?" + currnetday.getTime());
                            //        }

                            //        ChannelName.innerHTML = data.Channels[i].Name;
                            //        imageDiv.appendChild(Channelimage);
                            //        ChannelAnchor.appendChild(imageDiv);
                            //        ChannelAnchor.appendChild(ChannelName);
                            //        ChannelParentDiv.appendChild(ChannelAnchor);
                            //        ChannelList.appendChild(ChannelParentDiv);


                            //    }

                            //    CategoryNames.appendChild(ChannelList);
                            //    $('#NewChannelDiv').append(CategoryNames);


                            //    //}
                            //}
                            if (data.ChannelMenus != null) {
                                var ChannelCount = 0;
                                for (var i = 0; i < data.ChannelMenus.ResultObject.length; i++) {
                                    var CategoryNames = document.createElement("div");
                                    //CategoryNames.setAttribute("class", "channel-btn-desktop");

                                    var catName = document.createElement("div");

                                    if (i == 0) {
                                        catName.setAttribute("class", "channel-title");
                                        var paraCatName = document.createElement("p");
                                        paraCatName.innerHTML = data.ChannelMenus.ResultObject[i].ChannelCategory;

                                        catName.appendChild(paraCatName);
                                    }
                                    if (i != 0 && data.ChannelMenus.ResultObject[i].ChannelCategory != data.ChannelMenus.ResultObject[i - 1].ChannelCategory) {

                                        if (i == 9) {
                                            catName.setAttribute("class", "channel-title-10");
                                            var paraCatName = document.createElement("p");
                                            paraCatName.innerHTML = data.ChannelMenus.ResultObject[i].ChannelCategory;

                                            catName.appendChild(paraCatName);
                                        }
                                        else {
                                            catName.setAttribute("class", "channel-title");
                                            var paraCatName = document.createElement("p");
                                            paraCatName.innerHTML = data.ChannelMenus.ResultObject[i].ChannelCategory;

                                            catName.appendChild(paraCatName);
                                        }
                                    }


                                    CategoryNames.appendChild(catName);
                                    //CategoryNames.appendChild('<div class="channel-title"><p>' + data.CategoryName + '</p></div>');

                                    $('#NewChannelDiv').append(CategoryNames);
                                    var ChannelList = document.createElement("div");
                                    ChannelList.setAttribute("class", "channel-block");
                                    var countChannels = 0;
                                    var channelIndex = 0;

                                    var ChannelParentDiv = document.createElement("div");
                                    ChannelParentDiv.setAttribute("class", "channel-10");
                                    var ChannelAnchor = document.createElement("a");
                                    ChannelAnchor.setAttribute("data-innerroutename", "Channel");
                                    ChannelAnchor.setAttribute("data-hasIndex", "true");
                                    ChannelAnchor.setAttribute("data-ChannelId", data.ChannelMenus.ResultObject[i].Id);
                                    ChannelAnchor.setAttribute("data-color", data.ChannelMenus.ResultObject[i].Color);
                                    ChannelAnchor.setAttribute("data-name", data.ChannelMenus.ResultObject[i].Name);
                                    ChannelAnchor.setAttribute('data-toggle', "tooltip");
                                    ChannelAnchor.setAttribute('data-placement', "bottom");
                                    ChannelAnchor.setAttribute('title', data.ChannelMenus.ResultObject[i].Name);

                                    var currnetday = new Date();
                                    var imageDiv = document.createElement("div");
                                    imageDiv.setAttribute("class", "channel-img");
                                    var Channelimage = document.createElement("img");
                                    imageDiv.appendChild(Channelimage);
                                    var ChannelName = document.createElement("h4");
                                    if (data.ChannelMenus.ResultObject[i].ChannelIconImage != "") {
                                        Channelimage.setAttribute("src", data.ChannelMenus.ResultObject[i].ChannelIconImage + "?" + currnetday.getTime());
                                    }

                                    ChannelName.innerHTML = data.ChannelMenus.ResultObject[i].Name;
                                    imageDiv.appendChild(Channelimage);
                                    ChannelAnchor.appendChild(imageDiv);
                                    ChannelAnchor.appendChild(ChannelName);
                                    ChannelParentDiv.appendChild(ChannelAnchor);
                                    ChannelList.appendChild(ChannelParentDiv);

                                    CategoryNames.appendChild(ChannelList);
                                    $('#NewChannelDiv').append(CategoryNames);
                                }
                            }
                        });

                        RouteProvider.bindInnerRoutes();
                    }

                }


            }
            ,
            function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();

            }, JSON.stringify(object.Data));
    }


};

function GetViewAllHTML(searchdata, count) {
    var viewallHTML = "";
    if (count > 3) {
        viewallHTML = '<div class="clearfix bottom-border below-carousel-conent-border-bottom"></div><div class="font-bold"><a  class="custom_pointer" data-innerroutename=\"' + searchdata + '\" data-videotype=' + searchdata + ' data-hasindex="true" >View all</a></div>';
    }
    else {
        viewallHTML = '<div class="clearfix bottom-border below-carousel-conent-border-bottom"></div><div class="font-bold" style="display: none;"><a  class="custom_pointer" data-innerroutename=\"' + searchdata + '\" data-videotype=' + searchdata + ' data-hasindex="true" >View all</a></div>';
    }
    return viewallHTML;
}
/*generate thumbnail logic */
function videoCarousel(leftPosition, topPosition, videoid, videoNo, channelName, videoTitle, shortDescription, videoimage, hasLock, channelId, IsJisc, Duration, SubscriptionType, HasPromo, channelColor) {

    videoTitle = videoTitle.replace(/\"/g, "&quot;").replace(/\'/g, "&#39;");
    var accessbtn = '';
    var videoroute = '';
    var channelroute = '';
    var channelHTMLCode = '';
    if (Duration == null || HasPromo == true) {
        Duration = ' ';
    }

    if (SubscriptionType == null) {
        SubscriptionType = '';
    }

    if (hasLock == false) {
        accessbtn = '<svg xmlns = "http://www.w3.org/2000/svg" class="playBtn"  width = "37.93" height = "37.93" viewBox = "0 0 37.93 37.93" > <g id="Group_854" data-name="Group 854" transform="translate(0 0)"><g id="Group_853" data-name="Group 853"><g id="Fields_Input_Colour_White" data-name="Fields / Input / Colour White"><rect id="Fields_Input_Colour_White_background" data-name="Fields / Input / Colour White background" width="37.93" height="37.93" fill="rgba(0,0,0,0)" /><rect id="Fields_Input_Colour_White-2" data-name="Fields / Input / Colour White" width="37.93" height="37.93" fill="' + channelColor + '"/></g><path id="Polygon_1" data-name="Polygon 1" d="M6.392,0l6.392,11.25H0Z" style="transform: rotate(90deg) translate(13px, -25px)" transform="translate(24.897 12.732) rotate(90)" fill="#fff" /></g></g></svg >';
    }
    else {
        accessbtn = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="playBtn" x="0px" y="0px" viewBox="0 0 37.9 37.9" style="enable-background:new 0 0 37.9 37.9;" xml:space="preserve"><style type="text/css">.st1{fill:#FFFFFF;}</style><g id="Group_854" transform="translate(0 0)"><g id="Group_853"><g id="Fields_Input_Colour_White"><rect id="Fields_Input_Colour_White_background" y="0" width="37.9" height="37.9"/><rect id="Fields_Input_Colour_White-2" y="0" width="37.9" height="37.9" fill="' + channelColor + '"/></g></g></g><path id="Path_111" class="st1" d="M23.5,17.6h-1.1V15c-0.1-1.9-1.7-3.3-3.6-3.2c-1.7,0.1-3.1,1.5-3.2,3.2v2.6h-1.1c-0.4,0-0.7,0.3-0.7,0.7v7c0,0.4,0.3,0.7,0.7,0.7h9c0.4,0,0.7-0.3,0.7-0.7v-7C24.2,17.9,23.9,17.6,23.5,17.6L23.5,17.6z M17.1,15 L17.1,15c0.1-1,1-1.8,2-1.7c0.9,0.1,1.6,0.8,1.7,1.7l0,0v2.6h-3.7V15z M19.6,22.5v2h-1.2v-2c-0.7-0.3-1.1-1.2-0.7-2c0.3-0.7,1.2-1.1,2-0.7c0.7,0.3,1.1,1.2,0.7,2C20.2,22.1,19.9,22.3,19.6,22.5L19.6,22.5z"/></svg>';
        
    }

    if (videoid != "" && IsJisc == false) {
        videoroute = 'data-innerroutename=\"videoid\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-videoNo=\'' + videoNo + '\'   data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        channelroute = 'data-innerroutename="Channel" data-hasindex="true" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        //PS-1020: Added style attribute with color for channel title
        channelHTMLCode = '<div class="thumbnail-channel" ' + channelroute + ' ><a href="?Channel=' + channelName + '" class="carouselVideoTextColor disablehreflink" style="color:' + channelColor + '">' + channelName + '</a></div>'
    }
    else if (videoid != "" && IsJisc == true) {
        videoroute = 'data-innerroutename=\"JiscVideo\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-videoNo=\'' + videoNo + '\'  data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        channelroute = 'data-innerroutename="Channel" data-hasindex="true" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        //PS-1020: Added style attribute with color for channel title
        channelHTMLCode = '<div class="thumbnail-channel" ' + channelroute + ' ><a href="?Channel=' + channelName + '" class="carouselVideoTextColor disablehreflink" style="color:' + channelColor + '">' + channelName + '</a></div>'
    }
    var videoCarousel = '<div class="thumbnail-container-div custom_pointer" ' +
        'style="left:' + leftPosition + 'px; top:' + topPosition + 'px;" ' +
        ' >' +
        '<a href="?videoid=' + videoNo + '" class="mainwrapper disablehreflink" ' + videoroute + '>' +
        '<div class="box">' +
        '<div class="thumbnail-desktop-carousel" style="background-image:url(\'' + videoimage + '\')"></div>' +
        '<div class="caption" style="position:absolute;">' +
        ' <div class="video_caption">' + shortDescription + '</div>' +
        '<span id="timer_' + videoid + '" class="caption-timer">' + Duration + '</span>' +
        '<span id="SubscriptionType_' + videoid + '" class="caption-SubscriptionType"  style="display: none;" >' + SubscriptionType + '</span>' +

        '<span id="VideoTitle_' + videoid + '" class="caption-VideoTitle"  style="display: none;" >' + videoTitle + '</span>' +

        '</div>' +
        //  '<img src="Images/play.png" class="playBtn"/>' +
        '</div>' +
        '</a>' +
        channelHTMLCode +
        '<div class=thumbnail-caption ' + videoroute + '><a href="?videoid=' + videoNo + '" class="caption-VideoTitle carouselVideoTextColor disablehreflink">' + truncateString(videoTitle, 58) + '</a></div>' +

        //'<img src="Images/' + accessbtn + '" class="playBtn" ' + videoroute +

        //'/> '
        //'<svg xmlns="http://www.w3.org/2000/svg" class="playBtn"  width="37.93" height="37.93" viewBox="0 0 37.93 37.93"><g id="Group_854" data-name="Group 854" transform="translate(0 0)"><g id="Group_853" data-name="Group 853"><g id="Fields_Input_Colour_White" data-name="Fields / Input / Colour White"><rect id="Fields_Input_Colour_White_background" data-name="Fields / Input / Colour White background" width="37.93" height="37.93" fill="rgba(0,0,0,0)"/><rect id="Fields_Input_Colour_White-2" data-name="Fields / Input / Colour White" width="37.93" height="37.93" fill=' + channelColor + '/></g><path id="Polygon_1" data-name="Polygon 1" d="M6.392,0l6.392,11.25H0Z" transform="translate(24.897 12.732) rotate(90)" fill="#fff"/></g></g></svg>'

        accessbtn +
        '</div>';
    return videoCarousel;
}

function SetVideoImage(streamThumbnailUrl, UKStreamID, thumbnailurl, FileName, defaultimage) {
    var setthumbnail = '';
    if (streamThumbnailUrl != null) {
        setthumbnail = streamThumbnailUrl
    }
    else if (UKStreamID != null) {
        setthumbnail = thumbnailurl.replace("ENTRYID", UKStreamID)
    }
    else if (FileName != null) {
        if (FileName.FileType == "custom") {
            setthumbnail = FileName.FileNameWithUrl;
        }
        else {
            setthumbnail = defaultimage;
        }
    }
    else {
        setthumbnail = defaultimage;
    }
    return setthumbnail;
}

function RenderDesktopScriptHome() {
    var options = {
        $BulletNavigatorOptions: { //[Optional] Options to specify and enable navigator or not
            $Class: $JssorBulletNavigator$, //[Required] Class to create navigator instance
            $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
            $AutoCenter: 1, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
            $SpacingX: 2 //[Optional] Horizontal space between each item in pixel, default value is 0

        },

        $ArrowNavigatorOptions: { //[Optional] Options to specify and enable arrow navigator or not
            $Class: $JssorArrowNavigator$, //[Requried] Class to create arrow navigator instance
            $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
            $AutoCenter: 2, //[Optional] Auto center arrows in parent container, 0 No, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
            $Steps: 1 //[Optional] Steps to go for each navigation request, default value is 1
        },
        $SlideWidth: 1200,
        $SlideSpacing: 20, 					                //Space between each slide in pixels
        $DisplayPieces: 2,                                  //Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1
        $ParkingPosition: 130                                //The offset position to park slide (this options applys only when slideshow disabled).
    };



    var jssor_slider1 = new $JssorSlider$("sliderHome_Desktop", options);

    //responsive code begin
    //you can remove responsive code if you don't want the slider scales while window resizes
    function ScaleSlider() {
        var parentWidth = jssor_slider1.$Elmt.parentNode.clientWidth;
        if (parentWidth) {
            var sliderWidth = parentWidth;

            //keep the slider width no more than 1000
            sliderWidth = Math.min(sliderWidth, 1200);

            jssor_slider1.$SetScaleWidth(sliderWidth);
        } else
            window.setTimeout(ScaleSlider, 30);
    }

    ScaleSlider();

    if (!navigator.userAgent.match(/(iPhone|iPod|iPad|BlackBerry|IEMobile)/)) {
        $(window).bind('resize', ScaleSlider);
    }
    if (navigator.userAgent.match(/(iPhone|iPod|iPad)/)) {
        $(window).bind("orientationchange", ScaleSlider);
    }
}

function RenderMobileScriptHome() {
    var optionsMobile = {
        $BulletNavigatorOptions: { //[Optional] Options to specify and enable navigator or not
            $Class: $JssorBulletNavigator$, //[Required] Class to create navigator instance
            $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
            $AutoCenter: 1, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
            $SpacingX: 25 //[Optional] Horizontal space between each item in pixel, default value is 0

        }
    };



    var jssor_slider2 = new $JssorSlider$("sliderHome_Mobile", optionsMobile);

    //responsive code begin
    //you can remove responsive code if you don't want the slider scales while window resizes
    function ScaleSlider() {
        var parentWidth = jssor_slider2.$Elmt.parentNode.clientWidth;
        if (parentWidth) {
            var sliderWidth = parentWidth;

            //keep the slider width no more than 800
            sliderWidth = Math.min(sliderWidth, 768);

            jssor_slider2.$SetScaleWidth(sliderWidth);
        } else
            window.setTimeout(ScaleSlider, 30);
    }

    ScaleSlider();
    if (!navigator.userAgent.match(/(iPhone|iPod|iPad|BlackBerry|IEMobile)/)) {
        $(window).bind('resize', ScaleSlider);
    }
    if (navigator.userAgent.match(/(iPhone|iPod|iPad)/)) {
        $(window).bind("orientationchange", ScaleSlider);
    }

    //Scale slider while window load/resize/orientationchange.
    $(window).bind("load", ScaleSlider);
    $(window).bind("resize", ScaleSlider);
    $(window).bind("orientationchange", ScaleSlider);

    // debugger;
    //if (navigator.userAgent.match(/(iPhone|iPod|iPad)/)) {
    //    $(window).bind("orientationchange", ScaleSlider);
    //}
    //responsive code end   
}
/*generate thumbnail logic */
function getAddtionaVideoHTML(videoid, videoNo, channelName, videoTitle, videoimage, hasLock, channelId, IsJisc, IsEvent, eventId, SubscriptionType, Duration) {

    videoTitle = videoTitle.replace(/\"/g, "&quot;").replace(/\'/g, "&#39;");
    var accessbtn = '';
    if (hasLock == false) {
        accessbtn = '<svg xmlns = "http://www.w3.org/2000/svg" class="playBtn-small"  width = "37.93" height = "37.93" viewBox = "0 0 37.93 37.93" > <g id="Group_854" data-name="Group 854" transform="translate(0 0)"><g id="Group_853" data-name="Group 853"><g id="Fields_Input_Colour_White" data-name="Fields / Input / Colour White"><rect id="Fields_Input_Colour_White_background" data-name="Fields / Input / Colour White background" width="37.93" height="37.93" fill="rgba(0,0,0,0)" /><rect id="Fields_Input_Colour_White-2" data-name="Fields / Input / Colour White" width="37.93" height="37.93" fill="' + channelColor + '"/></g><path id="Polygon_1" data-name="Polygon 1" d="M6.392,0l6.392,11.25H0Z" transform="translate(24.897 12.732) rotate(90)" fill="#fff" /></g></g></svg >';
    }
    else {
        accessbtn = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="playBtn" x="0px" y="0px" viewBox="0 0 37.9 37.9" style="enable-background:new 0 0 37.9 37.9;" xml:space="preserve"><style type="text/css">.st1{fill:#FFFFFF;}</style><g id="Group_854" transform="translate(0 0)"><g id="Group_853"><g id="Fields_Input_Colour_White"><rect id="Fields_Input_Colour_White_background" y="0" width="37.9" height="37.9"/><rect id="Fields_Input_Colour_White-2" y="0" width="37.9" height="37.9" fill="' + channelColor + '"/></g></g></g><path id="Path_111" class="st1" d="M23.5,17.6h-1.1V15c-0.1-1.9-1.7-3.3-3.6-3.2c-1.7,0.1-3.1,1.5-3.2,3.2v2.6h-1.1c-0.4,0-0.7,0.3-0.7,0.7v7c0,0.4,0.3,0.7,0.7,0.7h9c0.4,0,0.7-0.3,0.7-0.7v-7C24.2,17.9,23.9,17.6,23.5,17.6L23.5,17.6z M17.1,15 L17.1,15c0.1-1,1-1.8,2-1.7c0.9,0.1,1.6,0.8,1.7,1.7l0,0v2.6h-3.7V15z M19.6,22.5v2h-1.2v-2c-0.7-0.3-1.1-1.2-0.7-2c0.3-0.7,1.2-1.1,2-0.7c0.7,0.3,1.1,1.2,0.7,2C20.2,22.1,19.9,22.3,19.6,22.5L19.6,22.5z"/></svg>';
    }

    if (IsEvent == true && eventId > 0) {
        var videoroute = 'data-innerroutename=\"event\" data-enablerefirect="false" data-redirectpage="View/EventLiveLanding.html" data-eventid=\"' + eventId + '\" data-videoid=\"' + videoid + '\"  data-videoNo=\"' + videoNo + '\"   data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        var channelroute = 'data-innerroutename="Channel" data-hasindex="true" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
    }
    else if (videoid != "" && IsJisc == false) {
        var videoroute = 'data-innerroutename=\"videoid\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-videoNo=\"' + videoNo + '\"  data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        var channelroute = 'data-innerroutename="Channel" data-hasindex="true" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
    }
    else if (videoid != "" && IsJisc == true) {
        var videoroute = 'data-innerroutename=\"JiscVideo\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-videoNo=\"' + videoNo + '\"  data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        var channelroute = 'data-innerroutename="Channel" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
    }


    var addtionaVideoHTML = '<div class="float-left bottom-margin-20 video-thumbnail-container" cursor="pointer">' +
        '<a href="?videoid=' + videoNo + '" class="thumbnail-background thumbnail-desktop-list disablehreflink" ' + videoroute + ' style="background-image:url(\'' + videoimage + '\')">' +
        '<img class="playBtn-small" src="Images/' + accessbtn + '">' +
        //accessbtn +
        '</a>' +
        '<div class="text-margin">' +
        '<a href="?videoid=' + videoNo + '" class="list-caption disablehreflink" ' + videoroute + ' >' + truncateString(videoTitle, 30) + '</a><br>' +
        '<a href="?Channel=' + channelName + '" class="list-channel disablehreflink" ' + channelroute + ' >' + channelName + '</a>' +
        '</div>' +
        '</div>';
    //'<div class="clearfix"></div>'

    return addtionaVideoHTML;
}

//function truncateString(str, length) {
//    return str.length > length ? jQuery.trim(str).substring(0, length)
//                          .trim(this) + "..." : str
//}

function RenderFeed() {

    var feed = new google.feeds.Feed("http://feeds.feedburner.com/tedtalks_video");

    feed.setNumEntries(3);
    feed.load(function (result) {
        if (!result.error) {
            var container = document.getElementById("Videofeed");
            //container.innerHTML = '<h3>Video feed</h3>' +
            '<hr>';
            var count = result.feed.entries.length;
            for (var i = 0; i < result.feed.entries.length; i++) {
                var addtionaVideoHTML = ''
                var entry = result.feed.entries[i];

                //var entry = result.feed.entries[i];
                var bmfx = entry.mediaGroups[0].contents[0].thumbnails[0].url;
                //var li = document.createElement("div");
                //li.innerHTML = '<h3><a href="' + entry.link + '">' + entry.title + '</a> <cite>by ' + entry.mediaGroup + '</cite></h3>';
                addtionaVideoHTML = '<a class="float-left bottom-margin-20 video-thumbnail-container" target="_blank"  href="' + entry.link + '">' +
                    '<div class="thumbnail-background thumbnail-desktop-list" style="background-image:url(\'' + bmfx + '\')">' +
                    '<img class="playBtn-small" src="Images/play.png">' +
                    '</div>' +
                    '<div class="text-margin">' +
                    '<div class="list-caption">' + truncateString(entry.title, 25) + '</div><br>' +
                    '<div class="list-channel" >' + entry.author + " : " + entry.categories[0] + '</div>' +
                    '</div>' +
                    '</a>';


                //var channelName = entry.author + " : " + entry.categories[0];
                //addtionaVideoHTML = getAddtionaVideoHTML(entry.link, channelName, truncateString(entry.title, 30), "", bmfx);
                //container.innerHTML += addtionaVideoHTML;


            }
            var viewAllHTML = ' ' +
                '<div class="clearfix bottom-border below-carousel-conent-border-bottom"></div>';//<div class="font-bold"><a href="#">View all</a></div>';
            //container.innerHTML += viewAllHTML;
        }
    });
}


function VideoCarouselMobile(leftPosition, topPosition, position, videoid, videoNo, channelName, videoTitle, shortDescription, videoimage, hasLock, channelId, IsJisc, Duration, SubscriptionType, HasPromo, channelColor) {
    videoTitle = videoTitle.replace(/\"/g, "&quot;").replace(/\'/g, "&#39;");
    var accessbtn = '';
    var videoroute = '';
    var channelroute = '';
    var channelHTMLCode = '';
    if (Duration == null || HasPromo == true) {
        Duration = ' ';
    }
    if (hasLock == false) {
        accessbtn = '<svg xmlns = "http://www.w3.org/2000/svg" class="playBtn-mobile-' + position + '"  width = "37.93" height = "37.93" viewBox = "0 0 37.93 37.93" > <g id="Group_854" data-name="Group 854" transform="translate(0 0)"><g id="Group_853" data-name="Group 853"><g id="Fields_Input_Colour_White" data-name="Fields / Input / Colour White"><rect id="Fields_Input_Colour_White_background" data-name="Fields / Input / Colour White background" width="37.93" height="37.93" fill="rgba(0,0,0,0)" /><rect id="Fields_Input_Colour_White-2" data-name="Fields / Input / Colour White" width="37.93" height="37.93" fill="' + channelColor + '"/></g><path id="Polygon_1" data-name="Polygon 1" d="M6.392,0l6.392,11.25H0Z" style="transform: rotate(90deg) translate(13px, -25px)" transform="translate(24.897 12.732) rotate(90)" fill="#fff" /></g></g></svg >';
    }
    else {
        accessbtn = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="playBtn-mobile-' + position + '" x="0px" y="0px" viewBox="0 0 37.9 37.9" style="enable-background:new 0 0 37.9 37.9;" xml:space="preserve"><style type="text/css">.st1{fill:#FFFFFF;}</style><g id="Group_854" transform="translate(0 0)"><g id="Group_853"><g id="Fields_Input_Colour_White"><rect id="Fields_Input_Colour_White_background" y="0" width="37.9" height="37.9"/><rect id="Fields_Input_Colour_White-2" y="0" width="37.9" height="37.9" fill="' + channelColor + '"/></g></g></g><path id="Path_111" class="st1" d="M23.5,17.6h-1.1V15c-0.1-1.9-1.7-3.3-3.6-3.2c-1.7,0.1-3.1,1.5-3.2,3.2v2.6h-1.1c-0.4,0-0.7,0.3-0.7,0.7v7c0,0.4,0.3,0.7,0.7,0.7h9c0.4,0,0.7-0.3,0.7-0.7v-7C24.2,17.9,23.9,17.6,23.5,17.6L23.5,17.6z M17.1,15 L17.1,15c0.1-1,1-1.8,2-1.7c0.9,0.1,1.6,0.8,1.7,1.7l0,0v2.6h-3.7V15z M19.6,22.5v2h-1.2v-2c-0.7-0.3-1.1-1.2-0.7-2c0.3-0.7,1.2-1.1,2-0.7c0.7,0.3,1.1,1.2,0.7,2C20.2,22.1,19.9,22.3,19.6,22.5L19.6,22.5z"/></svg>';
    }

    if (videoid != "" && IsJisc == false) {
        videoroute = 'data-innerroutename=\"videoid\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-videoNo=\'' + videoNo + '\'  data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        channelroute = 'data-innerroutename="Channel" data-hasindex="true" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        //PS-1020: Added style attribute with color for channel title
        channelHTMLCode = '<div class="thumbnail-channel" ' + channelroute + ' ><a href="?Channel=' + channelName + '" class="carouselVideoTextColor disablehreflink" style="color:' + channelColor + '">' + channelName + '</a></div>'
    }
    else if (videoid != "" && IsJisc == true) {
        videoroute = 'data-innerroutename=\"JiscVideo\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-videoNo=\'' + videoNo + '\'  data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        channelroute = 'data-innerroutename="Channel" data-hasindex="true" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        //PS-1020: Added style attribute with color for channel title
        channelHTMLCode = '<div class="thumbnail-channel" ' + channelroute + ' ><a href="?Channel=' + channelName + '" class="carouselVideoTextColor disablehreflink" style="color:' + channelColor + '">' + channelName + '</a></div>'
    }
    if (position == "bottom") {
        var MobileCarousel = '<div class="thumbnail-container-div-mobile-' + position + '"   style="left: ' + leftPosition + 'px; top: ' + topPosition + 'px;" href="#" >' +
            '<a href="?videoid=' + videoNo + '" class="mainwrapper disablehreflink" ' + videoroute + '>' +
            '<div class="box">' +
            '<div class="thumbnail-mobile-carousel-' + position + '" style="background-image:url(\'' + videoimage + '\')"></div>' +
            '</div>' +
            '</a>' +
            channelHTMLCode +
            '<div class=thumbnail-caption-mobile ' + videoroute + '><a href="?videoid=' + videoNo + '" class="carouselVideoTextColor disablehreflink">' + truncateString(videoTitle, 30) + '</a></div>' +

            
            accessbtn +
            '</div>';
    }
    else {
        var MobileCarousel = '<div class="thumbnail-container-div-mobile-' + position + '"   style="left: ' + leftPosition + 'px; top: ' + topPosition + 'px;" href="#" >' +
            '<a href="?videoid=' + videoNo + '"  class="mainwrapper disablehreflink" ' + videoroute + '>' +
            '<div class="box">' +
            '<div class="thumbnail-mobile-carousel-' + position + '" style="background-image:url(\'' + videoimage + '\')"></div>' +
            '<div class="caption">' +
            '<div class="video_caption new">' + shortDescription + '</div>' +

            '<span class="caption-timer">' + Duration + '</span>' +
            '<span id="SubscriptionType" class="caption-SubscriptionType"  style="display: none;" >' + SubscriptionType + '</span>' +

            '<span id="VideoTitle" class="caption-VideoTitle"  style="display: none;" >' + videoTitle + '</span>' +
            '</div>' +
            '</div>' +
            '</a>' +
            channelHTMLCode +
            '<div class=thumbnail-caption-mobile ' + videoroute + '><a href="?videoid=' + videoNo + '"  class="carouselVideoTextColor disablehreflink">' + truncateString(videoTitle, 30) + '</a></div>' +

            accessbtn +
            '</div>';
    }
    return MobileCarousel;
}


var CMSRepository = function () {
    var NewsSectionId = 1;
    var ServicesSectionId = 2;

    var IETTVHelpSubSection = 1;
    var AccountTypesSubSection = 2;

    var _this = this;

    this.MessageViewModel = new MessageViewModel();

    this.HelpWindowFunction = function (topic) {



        //window.open('titlepage.html', 'newwindow', config = 'height=100,width=400, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, directories=no, status=no')
    }

    this.GetCMSHelpList = function () {

        var object = {
            Data: {

            }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'Cms/CmsInformation.svc/GetCMSHelpList',
           function (data, status, headers, config) {
               if (ResultStatus.Successful == data.Status && data.ResultObject) {
                   //Bind all subscriptions to view.
                   if (data.ResultObject == null) {
                       //$('#NoRecordFound').html(data.Message);                       
                   }
                   else {

                       if (data.ResultObject.length != 0) {
                           var HelpDivFormat = '<div class="col-md-12 no-padding">';
                           HelpDivFormat += '<a  data-innerroutename="help" data-pageid="{1}" data-pagename="{2}" data-hasindex="true" class="custom_pointer">{0}</a>';
                           HelpDivFormat += '</div>';

                           var ServicesLIFormat = '<li><a data-innerroutename="services" data-pageid="{1}" data-pagename="{2}" data-hasindex="true" class="custom_pointer">{0}</a></li>';

                           var HelpAnchorFormatDeviceView = '<a data-innerroutename="help" data-pageid="{1}" data-pagename="{2}" data-hasindex="true" class="custom_pointer">{0}</a>';

                           var ServiceAnchorFormatDeviceView = '<a data-innerroutename="help" data-pageid="{1}" data-pagename="{2}" data-hasindex="true" class="custom_pointer">{0}</a>';

                           var ServicesLIIndexFooter = '<li><a data-innerroutename="help" data-pageid="{1}" data-pagename="{2}" data-hasindex="true" class="custom_pointer">{0}</a></li>';
                           
                           var ServicesLIFooter = '<li><a class="link-green custom_pointer" id="ancCMSPage" onClick="OpenCMSPage(\'{1}\')">{0}</a></li>';                           

                           for (i = 0; i < data.ResultObject.length; i++) {
                               var CMSSectionId = data.ResultObject[i].CMSSectionId;
                               var CMSSubSectionId = data.ResultObject[i].CMSSubSectionId;
                               var CMSPageId = data.ResultObject[i].CMSPageId;
                               var CMSPageName = data.ResultObject[i].CMSPageName;
                               var CMSViewName = data.ResultObject[i].CMSViewName;

                               if (CMSSectionId == NewsSectionId) {
                                   if (CMSSubSectionId == IETTVHelpSubSection) {
                                       $('#helpItemsContianer').append(HelpDivFormat.format(CMSPageName, CMSPageId, CMSViewName));
                                       $('#Helpcategory1').append(HelpAnchorFormatDeviceView.format(CMSPageName, CMSPageId, CMSViewName));
                                       $('.helpItemsContianerIndexFooter').append(ServicesLIIndexFooter.format(CMSPageName, CMSPageId, CMSViewName));
                                       $('.helpItemsContianerFooter').append(ServicesLIFooter.format(CMSPageName, CMSViewName));
                                   }
                                   else if (CMSSubSectionId == AccountTypesSubSection) {
                                       //alert($('.AccountItemsContianerFooter').html());
                                       $('#helpAccountItemsContainer').append(HelpDivFormat.format(CMSPageName, CMSPageId, CMSViewName));
                                       $('#Helpcategory2').append(HelpAnchorFormatDeviceView.format(CMSPageName, CMSPageId, CMSViewName));
                                       $('.AccountItemsContianerIndexFooter').append(ServicesLIIndexFooter.format(CMSPageName, CMSPageId, CMSViewName));
                                       $('.AccountItemsContianerFooter').append(ServicesLIFooter.format(CMSPageName, CMSViewName));
                                   }
                               }
                               else if (CMSSectionId == ServicesSectionId) {
                                   $("#ServiceUL").append(ServicesLIFormat.format(CMSPageName, CMSPageId, CMSViewName));
                                   $("#divMobile-Services").append(ServiceAnchorFormatDeviceView.format(CMSPageName, CMSPageId, CMSViewName));
                               }
                           }

                           RouteProvider.bindInnerRoutes();
                            }
                   }
               }
           },
        function (data, status, headers, config) {
            //console.log(data);

        }, JSON.stringify(object.Data));

    }

    //this.GetViewInformation = function (CMSPageId, CMSPageName, isDeviceView) {
    this.GetViewInformation = function (CMSPageName) {
        
        $('#imageContainerAnchor2').addClass('display-none');
        $('#videoPlayer2').addClass('display-none');
        $('#imageContainerAnchor1').addClass('display-none');
        $('#videoPlayer1').addClass('display-none');

        clearImage('1');
        clearVideo('1');

        clearImage('2');
        clearVideo('2');

        clearImageDiv('1');
        clearVideoDiv('1');
        clearImageDiv('2');
        clearVideoDiv('2');

        //$('#hiddenPageId').val(CMSPageId);

        var object = {
            Data: {
                //CMS_Page_Id: CMSPageId,
                CMS_Page_Name: CMSPageName
            }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'Cms/CmsInformation.svc/GetViewInformation',
           function (data, status, headers, config) {
               if (ResultStatus.Successful == data.Status && data.ResultObject) {
                   //Bind all subscriptions to view.
                   if (data.ResultObject == null) {
                       //$('#NoRecordFound').html(data.Message);                       
                   }
                   else {

                       if (data.ResultObject.length != 0) {                           
                           //$('#PageName').html(data.ResultObject.PageName);
                           $('#title1').html(data.ResultObject.PageName);
                           $('#title2').html(data.ResultObject.Title);
                           var test = window.location.href;
                           if (test.indexOf("services") != -1) {
                               $("#PageName,#cmsTitle").addClass("services-title");
                           }
                           else {
                               $("#PageName,#cmsTitle").addClass("help-title");
                           }
                           //$('#titleDiv').html(data.ResultObject.Title);                           
                           $('#contentDiv').html(data.ResultObject.HTMLMarkup1);


                           if (!IsNullOrEmpty(data.ResultObject.Image1_Id) && data.ResultObject.Image1_Id > 0) {
                               var imageElem = $('.imageContainerAnchor1');

                               imageElem.attr('href', data.ResultObject.Redirect_Link1);

                               imageElem.find('img').attr('alt', data.ResultObject.Alt_Text1);

                               imageElem.find('img').attr('src', WebService.CMSSharePath + data.ResultObject.Image_Path1);

                               $('#imageContainerAnchor1').removeClass('display-none');

                           }
                           else if (!IsNullOrEmpty(data.ResultObject.Video1_Id) && data.ResultObject.Video1_Id > 0) {
                               $('#videoPlayer1').html(data.ResultObject.Video1);
                               $('#videoPlayer1').removeClass('display-none');
                           }

                           if (!IsNullOrEmpty(data.ResultObject.Image2_Id) && data.ResultObject.Image2_Id > 0) {
                               var imageElem = $('.imageContainerAnchor2');

                               imageElem.attr('href', data.ResultObject.Redirect_Link2);

                               imageElem.find('img').attr('alt', data.ResultObject.Alt_Text2);

                               imageElem.find('img').attr('src', WebService.CMSSharePath + data.ResultObject.Image_Path2);

                               //$('#btnRemoveImage2').removeClass('display-none');

                               $('#imageContainerAnchor2').removeClass('display-none');

                           }
                           else if (!IsNullOrEmpty(data.ResultObject.Video2_Id) && data.ResultObject.Video2_Id > 0) {
                               $('#videoPlayer2').html(data.ResultObject.Video2);
                               $('#videoPlayer2').removeClass('display-none');
                           }
                           //Testing if no media present then  make video panel display none and display full width
                           if ($('#videoPlayer2').hasClass('display-none') && $('#imageContainerAnchor2').hasClass('display-none') && $('#videoPlayer1').hasClass('display-none') && $('#imageContainerAnchor1').hasClass('display-none')) {
                               $('.leftContainer').addClass('display-none');
                               $('.rightContainer').removeClass('col-md-8').addClass('col-md-12');
                           }
                           $('#titleDiv').removeClass('display-none');
                           $('#contentDiv').removeClass('display-none');

                            //PS - 1196: Changing CMS pages question / answer style to expandable / collapsible panel-start
                               var lastAnswer;
                               $('.container-fluid .question').each(function (index) {
                                   $(this).attr({
                                       "data-toggle": "collapse",
                                       "data-value": "#question" + index,
                                   });
                                   $(this).append('<svg version="1.1" id="faqArrow" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 16.8 21" xml:space="preserve"> <path id = "Master_arrow_small" d = "M2.2,10.4L6.8,15V0H10v15l4.6-4.6l2.2,2.2L8.4,21L0,12.6L2.2,10.4z" ></path ></svg >');
                               });
                           
                               $('.container-fluid .answer').each(function (index) {
                                   $(this).attr({
                                       "id": "question" + index
                                       //"class": "collapse"

                                   }).addClass("collapse");
                                   lastAnswer = index;
                               });
                           var addingBorder = $(document).find('#question' + lastAnswer);
                           $("<span class='lastanswer_block'></span>").insertAfter(addingBorder); 
                               //$(document).find('#question' + lastAnswer).closest('p').addClass('lastanswer_block');
                                //PS - 1196: Changing CMS pages question / answer style to expandable / collapsible panel-end
                           $(window).scrollTop($('#cmsTitle').offset().top);
                       }
                   }
               }
               if (!WebService.DisableGA) {
                   
                   storeurlDetailsInGA("CMSHelp Page Name - " + CMSPageName);
               }

               CloseMobileMenu();               
           },
        function (data, status, headers, config) {
            //console.log(data);

        }, JSON.stringify(object.Data));

    }   
}



function showUploadError(sender, args) {
    if (args.response.indexOf("already exist") > -1) {
        alert("The file with this name already exists\nPlease upload the file with some other name.");
    }
    else {
        alert("An error has occured while uploading the file.");
    }
}

function UploadComplete(sender, args) {
    var filesize = args.get_fileSize();
    // var fileId = args.get_fileId();
    var fileName = args._fileName;

    var postedUrlInfo = Sys.Serialization.JavaScriptSerializer.deserialize(args.get_postedUrl());

    if (postedUrlInfo.error != "" && postedUrlInfo.error != "undefined" && postedUrlInfo.error != null) {
        if (postedUrlInfo.error.indexOf("duplicateImage") > -1) {

            alert("The file with this name already exists\nPlease upload the file with some other name.");

            $('#ContentPlaceHolder1_AjaxFileUpload1_QueueContainer').empty();
            //sender._filesInQueue.length = 0;

        }
    }
    else {
        var imageElem = $('.imageContainerAnchor1');

        imageElem.find('img').attr('src', WebService.CMSSharePath + fileName);

        $('#embedCode1').val('');

        $('#imageContainerAnchor1').removeClass('display-none');

        $('#videoPlayer1').hide();
    }
}


function UploadComplete2(sender, args) {
    var filesize = args.get_fileSize();
    // var fileId = args.get_fileId();
    var fileName = args._fileName;

    var postedUrlInfo = Sys.Serialization.JavaScriptSerializer.deserialize(args.get_postedUrl());

    if (postedUrlInfo.error != "" && postedUrlInfo.error != "undefined" && postedUrlInfo.error != null) {
        if (postedUrlInfo.error.indexOf("duplicateImage") > -1) {

            alert("The file with this name already exists\nPlease upload the file with some other name.");

            $('#ContentPlaceHolder1_AjaxFileUpload1_QueueContainer').empty();
            //sender._filesInQueue.length = 0;

        }
    }
    else {
        var imageElem = $('.imageContainerAnchor2');

        imageElem.find('img').attr('src', WebService.CMSSharePath + fileName);

        $('#embedCode2').val('');

        $('#imageContainerAnchor2').removeClass('display-none');

        $('#videoPlayer2').hide();
    }
}

function OpenCMSPage(cmsPageName) {
    //window.open('', 'new').location.href = "CMSHelpFullView.html?PageId=" + cmsPageId + "&PageName=" + cmsPageName;
    var finalUrl = GetURLWithoutHash();

    var currentPageUrl = '';

    if (finalUrl.indexOf('?') > -1) {
        currentPageUrl = finalUrl.split('?')[0];
    }
    else {
        currentPageUrl = finalUrl;
    }

    var newUrl = '';

    if (currentPageUrl.toLowerCase().indexOf('/view') > -1) {
        newUrl = currentPageUrl.toLowerCase().split('/view')[0];        
    }

    //var helpPageURL = currentPageUrl
    cmsPageName = cmsPageName.toLowerCase().replace(/\ /g, '-');
    location.href = newUrl + "/?help=" + cmsPageName, "newwin", "toolbar=yes, scrollbars=yes, resizable=yes, top=100, left=500, width=600, height=500";
}
var NotificationRepository = {
    MessageViewModel: new MessageViewModel(),
    CheckNotificationForUser: function () {
        var _this = this;
        var object = {
            Data: {
                "user": {
                    "LogonId": sessionStorage.getItem("LogonId")
                }
            }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/CheckNotificationForUser',

            function (data, status, headers, config) {
                if (data.LoginStatus == ResultStatus.Successful)
                {
                    if (data.Status == ResultStatus.Successful) 
                    {
                        if (data.ResultObject != null)
                        {
                            sessionStorage.setItem("NotificationFlag", parseBool(data.ResultObject.NotificationResult));
                            if (parseBool(data.ResultObject.NotificationResult) == true) {
                                $("#NotificationDiv").show();
                                $("#spnNotificationTxt").text(data.ResultObject.NotificationContent);
                                $('#btnSubsRenew').val(data.ResultObject.ProductCode);
                                if (parseBool(localStorage.getItem("IsIndividualUser")) == true) {
                                    $("#btnSubsRenew").show();
                                }
                                else {
                                    $("#NotificationDiv").addClass('alert_notifiction_indi');
                                    $("#btnSubsRenew").hide();
                                }
                            }
                            else
                            {
                                CloseNotification();
                            }
                        }
                    }                    
                    else
                    {
                        _this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                        _this.MessageViewModel.ShowOverLay();
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data.Message);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    }
};
function SendNotificationDetails() {
    var _this = this;
    var object = {
        Data: {
            "user": {
                "LogonId": sessionStorage.getItem("LogonId")
            }
        }
    };

    Repository.LoadDataJSON(WebService.BaseURL + 'Subscriptions/SubscriptionService.svc/SendNotificationDetails',

        function (data, status, headers, config) {

            if (data.LoginStatus == ResultStatus.Successful)
            {
                var messageViewModel = new MessageViewModel();
                if (data.Status == ResultStatus.Successful && data.ResultObject != null) {
                    if (parseBool(data.ResultObject["IsMailSend"]) == true) {
                        messageViewModel.CreateInfoMessage("Mail send successfully.");
                        messageViewModel.ShowOverLay();
                    }
                    else
                    {
                        messageViewModel.CreateInfoMessage("System failed to send mail.");
                        messageViewModel.ShowOverLay();
                    }
                }
                else
                {
                    messageViewModel.CreateInfoMessage("System failed to send mail.");
                    messageViewModel.ShowOverLay();
                }
            }
        },
        function (data, status, headers, config) {
            var messageViewModel = new MessageViewModel();
            messageViewModel.CreateErrorMessage(data.Message);
            messageViewModel.ShowOverLay();
        }, JSON.stringify(object.Data));
}
function CloseNotification() {
    sessionStorage.setItem("NotificationFlag", false);
    $("#NotificationDiv").hide();
}

function RenewSubscription() {
    if ($.trim($('#btnSubsRenew').val()) != "")
    {
        sessionStorage.setItem("SelectedProductId", $.trim($('#btnSubsRenew').val()));
    }
    location.href = "?" + Application.buySubscription.BaseURL;
}
function UpdateSubscriptionNotification() {
    var checked = $('.mysubscriptionNotification').is(':checked');
    var object =
    {
        Data: {
            Ischecked: checked,
            LogonId: IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")
        }
    };
    Repository.LoadDataJSON(WebService.BaseURL + 'Subscriptions/SubscriptionService.svc/UpdateSubscriptionNotification',
    function (data) {
        if (ResultStatus.Successful == data.LoginStatus) {
            if (data.ResultObject != null) {
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateInfoMessage(data.Message);
                messageViewModel.ShowOverLay();
            }
        }
        else {
            sessionStorage.setItem("RedirectLocation", Application.MySubscription.BaseURL);
            sessionStorage.setItem("RedirectFrom", Application.SearchResult.BaseURL);
            location.href = "view/" + Application.Login.BaseURL;
        }
    },
    function (data) {
        var messageViewModel = new MessageViewModel();
        messageViewModel.CreateErrorMessage(data);
        messageViewModel.ShowOverLay();
    }, JSON.stringify(object.Data));

}
var LoginRepository = function () {
	this.MessageViewModel = new MessageViewModel();
	this.CurrentLoginDetails = {};
	//For Desktop
	this.MenuMessageId = 'message';
	this.MenuLoginId = 'login';
	this.MenuLogoutId = "logout";
	this.MenuAccountId = 'accountLi';
	this.MenuAccountSubMenuMySubscriptionId = 'MySubscription';
	this.MenuAccountSubMenuUserManagememtId = 'UserManagememt';
	this.MenuBuySubscription = 'BuySubscription';
	this.MenuChangePassword = 'ChangePassword';
	this.MenuUserGeneratedContentId = "UserGeneratedContent";

	this.MenuLoggedInAsDifferentUserId = 'loggedInAsDifferentUser';
	this.helpPage = "btn_help";
	this.myIETTvPage = "btn_access_details";
	this.userLogo = "user_logo"
	this.AdditionalLogin = "IPLoginUser";

	//For Mobile
	this.MenuMessageMobileId = 'message_mobile';
	this.Menumessage_mobileOffLine = 'message_mobileOffLine';
	this.MenuLoginMobileId = 'login_mobile';
	this.MenuLogoutMobileId = "logout_mobile";
	this.MenuAccountMobileId = 'accountLi_mobile';
	this.MenuAccountSubMenuMySubscriptionMobileId = 'MySubscription_mobile';
	this.MenuChangePasswordMobileId = 'ChangePassword_mobile';//NN
	this.MenuUserManagementMobileId = 'UserManagement_mobile';
	this.UserGeneratedContentMobileId = 'UserGeneratedContent_mobile';
	this.MobileMenuBuySubscription = 'BuyChannels_mobile';
	this.MenuLoggedInAsDifferentUserMobileId = 'loggedInAsDifferentUser_mobile';
	this.MenuAccountSubMenuSystemUsageReportId = "CorpReport";
	this.MenuMarcRecordDownloadId = "DownloadMARCRecord";
	this.redirectBtn = "btnRedirect";
	this.redirecthref = "redirectLink";
	this.restrictedHref = "Restrictedlink";
	this.btnLoginMessageHelp = "btn_help";
	this.btnShibbolethLogin = ".btnExternalLogin";//btnExternalLogin
	this.IsWelcomeMessageShown = 0;

	this.validateConcurrencyUser = function (jsonData) {
		//var _this = this;
		var object = {
			Data: { "concurrencyUser": jsonData }
		};

		Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/ConcurrencyLogon',
			function (data, status, headers, config) {
				if (data.Status == ResultStatus.Successful) {
					data = data.ResultObject;
					localStorage.setItem("UserName", data.UserName);
					//sessionStorage.setItem("LogonId", data.LogonId);
					BrowserStorage.setLogonId(data.LogonId);
					localStorage.setItem("AccountId", data.AccountId);
					localStorage.setItem("IsTermsAndConditionsAccepted", data.IsTermsAndConditionsAccepted);
					localStorage.setItem("AdditionalLogin_AccountId", data.AccountId);
					localStorage.setItem("Welcome", data.Welcome);
					localStorage.setItem("IsIndividualUser", data.IsIndividualUser);
					sessionStorage.setItem("IsPasswordReset", data.IsPasswordReset);
					localStorage.setItem("AccountType", data.AccountType);
					localStorage.setItem("CorporateUserType", data.CorporateUserType);
					sessionStorage.setItem("IsIPLogin", false);
					SetAccessCodeDetailsinSession();
					//localStorage.setItem("DisplayBuySubscriptionSubMenu", false);
					// sessionStorage.setItem("RedirectLocation", "inlineReaderWRDSearch");
					//if (sessionStorage.getItem("RedirectLocation") == Application.Address.BaseURL) {
					//    sessionStorage.setItem("RedirectLocation", Application.Home.BaseURL);
					//}

					//if ((sessionStorage.getItem("RedirectFrom") != Application.SearchResult.BaseURL)
					//    && (sessionStorage.getItem("RedirectFrom") != Application.TaxonomyLandingPage.BaseURL)) {
					//    sessionStorage.setItem("RedirectLocation", "Login");
					//}
					//if ((sessionStorage.getItem("RedirectFrom") != Application.SearchResult.BaseURL)) {
					//    sessionStorage.setItem("RedirectLocation", "Login");
					//}

					if (!parseBool(data.IsTermsAndConditionsAccepted)) {
						location.href = Application.TermsandConditions.BaseURL;
					}
					else {
						if (sessionStorage.getItem("IsPasswordReset") == "true") {
							location.href = '../' + Application.ChangePassword.BaseURL;
						}
						else {
							if (sessionStorage.getItem("RedirectFromBeforeSSO") !== null && sessionStorage.getItem("RedirectFromBeforeSSO") !== "") {
								location.href = sessionStorage.getItem("RedirectFromBeforeSSO");
							}
							else {
								location.href = '../?' + BrowserStorage.getRedireceLocationwithIndex();
							}
						}

						//location.href = '../?' + BrowserStorage.getRedireceLocationwithIndex();

						//if ((sessionStorage.getItem("RedirectFrom") == Application.SearchResult.BaseURL)
						//   && !IsNullOrEmpty(sessionStorage.getItem("RedirectLocation"))) {
						//    //sessionStorage.setItem("RedirectFrom", "");
						//    location.href = '../?' + sessionStorage.getItem("RedirectLocation");
						//}
						//if ((sessionStorage.getItem("RedirectFrom") == Application.SearchResult.BaseURL
						//    || sessionStorage.getItem("RedirectFrom") == Application.TaxonomyLandingPage.BaseURL)
						//    && !IsNullOrEmpty(sessionStorage.getItem("RedirectLocation"))) {
						//    //sessionStorage.setItem("RedirectFrom", "");
						//    location.href = '../?' + sessionStorage.getItem("RedirectLocation");
						//}
						//else {
						//    location.href = '../';
						//}
					}
					//_this.loginMessage();
				}
				else {
					_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
					_this.MessageViewModel.ShowOverLay();
				}
			},
			function (data, status, headers, config) {
				_this.MessageViewModel.CreateErrorMessage(data);
				_this.MessageViewModel.ShowOverLay();
			}, JSON.stringify(object.Data));
	},

		//this.getChannelMenu = function (currentRouteSetting, routeProvider, routeCurrentContext) {
		//    var object = {
		//        Data: {
		//            "logonId": BrowserStorage.getLogonId()// IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")
		//        }
		//    };
		//    Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/GetMenuChannels',
		//          function (data, status, headers, config) {
		//              if (data.Status == ResultStatus.Successful && data.ResultObject != null) {
		//                  if (data.ResultObject.length != 0) {
		//                      var strMobCategoryNames = "";
		//                      var strMobChannelNames = "";
		//                      var CntforMobile = 1;
		//                      var containercount = 0;
		//                      var categoryCount = 0;
		//                      $.each(data.ResultObject, function (index, data) {
		//                          CntforMobile++;
		//                          var CategoryName = data.CategoryName;
		//                          var Maindiv = "";
		//                          var SecondDiv = "";
		//                          var channelLen = data.Channels.length;
		//                          var count = 1;
		//                          var container = "";

		//                          strMobCategoryNames = '<a href="#category' + CntforMobile + '" class="accordion-toggle menu-header-2 collapsed" data-toggle="collapse" data-parent=".sideMenuAccordoinChannelMenu" id="channelsTechnology">' + CategoryName + '</a>';
		//                          strMobCategoryNames += '<div class="panel-group sideMenuAccordoinChannelMenu">';
		//                          strMobCategoryNames += '<div class="panel panel-default">';

		//                          strMobCategoryNames += '<div class="panel-collapse collapse menu-submenu" id="category' + CntforMobile + '">'
		//                          strMobChannelNames = "";
		//                          for (k = 0; k < channelLen; k++) {
		//                              strMobChannelNames += '<a data-innerroutename="Channel" data-channelId=' + data.Channels[k].Id + ' data-color=' + data.Channels[k].Color + ' data-name="' + data.Channels[k].Name + '" data-hasIndex="true" class="list-group-item custom_pointer">' + data.Channels[k].Name + '</a>';
		//                              var container = "";
		//                              var cnt = 0;

		//                          }
		//                          strMobCategoryNames += strMobChannelNames + '</div></div></div>'
		//                          $(".divMobileChannel").append(strMobCategoryNames);

		//                          categoryCount++;
		//                      });

        //                        $.each(data.ResultObject, function (index, data) {
        //                              if (index <= 5) {
        //                                  //var CategoryNames = '<li class="channel-btn-desktop"><a href="#category_' + index + '" data-toggle="tab">' + data.CategoryName + ' &nbsp<i class="fa fa-grey fa-chevron-down"></i></a></li>';

        //                                  //$('#CategoryMenu').append(CategoryNames);

        //                                  //var ChannelMainDiv = "";
        //                                  //ChannelMainDiv = document.createElement("div");
        //                                  //ChannelMainDiv.setAttribute("class", 'tab-pane fade');
        //                                  //ChannelMainDiv.setAttribute('id', 'category_' + index);
        //                                  //var ChannelUnorderedList = document.createElement("ul");
        //                                  //ChannelUnorderedList.setAttribute('class', 'channel-lists-details');

        //                                  //for (i = 0; i < data.Channels.length; i++) {
        //                                  //    var ChannelList = document.createElement("li");
        //                                  //    var ChannelAnchor = document.createElement("a");
        //                                  //    ChannelAnchor.setAttribute("data-innerroutename", "Channel");
        //                                  //    ChannelAnchor.setAttribute("data-hasIndex", "true");
        //                                  //    ChannelAnchor.setAttribute("data-ChannelId", data.Channels[i].Id);
        //                                  //    ChannelAnchor.setAttribute("data-color", data.Channels[i].Color);
        //                                  //    ChannelAnchor.setAttribute("data-name", data.Channels[i].Name);
        //                                  //    ChannelAnchor.setAttribute('data-toggle', "tooltip");
        //                                  //    ChannelAnchor.setAttribute('data-placement', "bottom");
        //                                  //    ChannelAnchor.setAttribute('title', data.Channels[i].Name);

        //                                  //    var currnetday = new Date();
        //                                  //    var Channelimage = document.createElement("img");
        //                                  //    var ChannelName = document.createElement("h3");
        //                                  //    if (data.Channels[i].ChannelIconImage != "") {
        //                                  //        Channelimage.setAttribute("src", data.Channels[i].ChannelIconImage + "?" + currnetday.getTime());
        //                                  //    }
        //                                  //    ChannelName.innerHTML = data.Channels[i].Name;

        //                                  //    ChannelAnchor.appendChild(Channelimage);
        //                                  //    ChannelAnchor.appendChild(ChannelName);
        //                                  //    ChannelList.appendChild(ChannelAnchor);
        //                                  //    ChannelUnorderedList.appendChild(ChannelList);

        //                                  //}
        //                                  ////ChannelUnorderedList.appendChild(ChannelList);
        //                                  //ChannelMainDiv.appendChild(ChannelUnorderedList);

        //                                  //$('#ChannelMenu').append(ChannelMainDiv);

        //                                  //if(index <= 10)
        //                                  //{
        //                                  var CategoryNames = document.createElement("div");
        //                                  //CategoryNames.setAttribute("class", "channel-btn-desktop");

        //                                  var catName = document.createElement("div");
        //                                  catName.setAttribute("class", "channel-title");

        //                                  var paraCatName = document.createElement("p");
        //                                  paraCatName.innerHTML = data.CategoryName;

        //                                  catName.appendChild(paraCatName);
        //                                  CategoryNames.appendChild(catName);
        //                                  //CategoryNames.appendChild('<div class="channel-title"><p>' + data.CategoryName + '</p></div>');

        //                                  $('#NewChannelDiv').append(CategoryNames);
        //                                  var ChannelList = document.createElement("div");
        //                                  var countChannels = 0;
        //                                  var channelIndex = 0;

        //                                for (i = 0; i < data.Channels.length; i++) {
        //                                    var ChannelParentDiv = document.createElement("div");
        //                                    ChannelParentDiv.setAttribute("class", "channel-10");
        //                                    var ChannelAnchor = document.createElement("a");
        //                                    ChannelAnchor.setAttribute("data-innerroutename", "Channel");
        //                                    ChannelAnchor.setAttribute("data-hasIndex", "true");
        //                                    ChannelAnchor.setAttribute("data-ChannelId", data.Channels[i].Id);
        //                                    ChannelAnchor.setAttribute("data-color", data.Channels[i].Color);
        //                                    ChannelAnchor.setAttribute("data-name", data.Channels[i].Name);
        //                                    ChannelAnchor.setAttribute('data-toggle', "tooltip");
        //                                    ChannelAnchor.setAttribute('data-placement', "bottom");
        //                                    ChannelAnchor.setAttribute('title', data.Channels[i].Name);

        //                                    var currnetday = new Date();
        //                                    var imageDiv = document.createElement("div");
        //                                    imageDiv.setAttribute("class","channel-img");
        //                                    var Channelimage = document.createElement("img");
        //                                    imageDiv.appendChild(Channelimage);
        //                                    var ChannelName = document.createElement("h4");
        //                                    if (data.Channels[i].ChannelIconImage != "") {
        //                                        Channelimage.setAttribute("src", data.Channels[i].ChannelIconImage + "?" + currnetday.getTime());
        //                                    }

        //                                    ChannelName.innerHTML = data.Channels[i].Name;
        //                                    imageDiv.appendChild(Channelimage);
        //                                    ChannelAnchor.appendChild(imageDiv);
        //                                    ChannelAnchor.appendChild(ChannelName);
        //                                    ChannelParentDiv.appendChild(ChannelAnchor);
        //                                    ChannelList.appendChild(ChannelParentDiv);

        //                                }

        //                                  CategoryNames.appendChild(ChannelList);
        //                                  $('#NewChannelDiv').append(CategoryNames);

        //                                  //}
        //                              }
        //                          });

        //                      RouteProvider.bindInnerRoutes();
        //                  }

		//              }
		//          }
		//          ,
		//          function (data, status, headers, config) {
		//              Spinner.Stop();
		//              var messageViewModel = new MessageViewModel();
		//              messageViewModel.CreateErrorMessage(data);
		//              messageViewModel.ShowOverLay();

		//          }, JSON.stringify(object.Data));
		//},

		this.getChannelMenu = function (currentRouteSetting, routeProvider, routeCurrentContext) {
			//Rakesh: To show Loader on Channels
			$('#divChanneloverlaySpinner').show();

			var object = {
				Data: {
					"logonId": BrowserStorage.getLogonId()// IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")
				}
			};
			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/GetMenuChannels',
				function (data, status, headers, config) {
					if (data.Status == ResultStatus.Successful && data.ResultObject != null) {
						if (data.ResultObject.length != 0) {
							var strMobCategoryNames = "";
							var strMobChannelNames = "";
							var CntforMobile = 1;
							var containercount = 0;
							var categoryCount = 0;
							$.each(data.ResultObject[0].ChannelMenuForMob.ResultObject, function (index, data) {
								CntforMobile++;
								var CategoryName = data.CategoryName;
								var Maindiv = "";
								var SecondDiv = "";
								var channelLen = data.Channels.length;
								var count = 1;
								var container = "";

								strMobCategoryNames = '<a href="#category' + CntforMobile + '" class="accordion-toggle menu-header-2 collapsed" data-toggle="collapse" data-parent=".sideMenuAccordoinChannelMenu" id="channelsTechnology">' + CategoryName + '</a>';
								strMobCategoryNames += '<div class="panel-group sideMenuAccordoinChannelMenu">';
								strMobCategoryNames += '<div class="panel panel-default">';

								strMobCategoryNames += '<div class="panel-collapse collapse menu-submenu" id="category' + CntforMobile + '">'
								strMobChannelNames = "";
								for (k = 0; k < channelLen; k++) {
									strMobChannelNames += '<a data-innerroutename="Channel" data-channelId=' + data.Channels[k].Id + ' data-color=' + data.Channels[k].Color + ' data-name="' + data.Channels[k].Name + '" data-hasIndex="true" class="list-group-item custom_pointer">' + data.Channels[k].Name + '</a>';
									var container = "";
									var cnt = 0;
								}
								strMobCategoryNames += strMobChannelNames + '</div></div></div>'
								$(".divMobileChannel").append(strMobCategoryNames);

								categoryCount++;
							});

                            $.each(data.ResultObject, function (index, data) {
                                if (data.ChannelMenus != null) {
                                    var ChannelCount = 0;
                                    for (var i = 0; i < data.ChannelMenus.ResultObject.length; i++) {
                                        var CategoryNames = document.createElement("div");
                                        //CategoryNames.setAttribute("class", "channel-btn-desktop");

                                        var catName = document.createElement("div");

                                        if (i == 0) {
                                            //catName.setAttribute("class", "channel-title");
                                            //add class for channel title appended with first 2 characters of category
                                            catName.setAttribute("class", 'channel-title channel-title-' + data.ChannelMenus.ResultObject[i].ChannelCategory.substring(0, 2) + '');
                                            var paraCatName = document.createElement("p");
                                            paraCatName.innerHTML = data.ChannelMenus.ResultObject[i].ChannelCategory;

                                            catName.appendChild(paraCatName);
                                        }
                                        if (i != 0 && data.ChannelMenus.ResultObject[i].ChannelCategory != data.ChannelMenus.ResultObject[i - 1].ChannelCategory) {
                                            if (i == 9) {
                                                //catName.setAttribute("class", "channel-title-10");
                                                //add class for channel title appended with first 2 characters of category
                                                catName.setAttribute("class", 'channel-title-10 channel-title-10-' + data.ChannelMenus.ResultObject[i].ChannelCategory.substring(0, 2) + '');
                                                var paraCatName = document.createElement("p");
                                                paraCatName.innerHTML = data.ChannelMenus.ResultObject[i].ChannelCategory;

                                                catName.appendChild(paraCatName);
                                            }
                                            else {
                                                //catName.setAttribute("class", "channel-title");
                                                //add class for channel title appended with first 2 characters of category
                                                catName.setAttribute("class", 'channel-title channel-title-' + data.ChannelMenus.ResultObject[i].ChannelCategory.substring(0, 2) + '');
                                                var paraCatName = document.createElement("p");
                                                paraCatName.innerHTML = data.ChannelMenus.ResultObject[i].ChannelCategory;

                                                catName.appendChild(paraCatName);
                                            }
                                        }

                                        CategoryNames.appendChild(catName);
                                        //CategoryNames.appendChild('<div class="channel-title"><p>' + data.CategoryName + '</p></div>');

                                        $('#NewChannelDiv').append(CategoryNames);
                                        var ChannelList = document.createElement("div");
                                        ChannelList.setAttribute("class", "channel-block");
                                        var countChannels = 0;
                                        var channelIndex = 0;

                                        var ChannelParentDiv = document.createElement("div");
                                        //ChannelParentDiv.setAttribute("class", "channel-10");
                                        //add class for channel name appended with first 2 characters of category
                                        ChannelParentDiv.setAttribute("class", 'channel-10 channel-10-' + data.ChannelMenus.ResultObject[i].ChannelCategory.substring(0, 2) + '');
                                        var ChannelAnchor = document.createElement("a");
                                        ChannelAnchor.setAttribute("data-innerroutename", "Channel");
                                        ChannelAnchor.setAttribute("data-hasIndex", "true");
                                        ChannelAnchor.setAttribute("data-ChannelId", data.ChannelMenus.ResultObject[i].Id);
                                        ChannelAnchor.setAttribute("data-color", data.ChannelMenus.ResultObject[i].Color);
                                        ChannelAnchor.setAttribute("data-name", data.ChannelMenus.ResultObject[i].Name);
                                        ChannelAnchor.setAttribute('data-toggle', "tooltip");
                                        ChannelAnchor.setAttribute('data-placement', "bottom");
                                        ChannelAnchor.setAttribute('title', data.ChannelMenus.ResultObject[i].Name);

                                        var currnetday = new Date();
                                        var imageDiv = document.createElement("div");
                                        imageDiv.setAttribute("class", "channel-img");
                                        var Channelimage = document.createElement("img");
                                        imageDiv.appendChild(Channelimage);
                                        var ChannelName = document.createElement("h4");
                                        //Ps-1020:set background-color and text-color of channel name as per channel color
                                        // ChannelName.setAttribute("style", 'background-color:' + data.ChannelMenus.ResultObject[i].Color + ';color:' + data.ChannelMenus.ResultObject[i].ForegroundColor + '');
                                        //Ps-1020:set background-color and text-color of channel name as per channel color
                                        ChannelName.setAttribute("style", 'background-color:' + data.ChannelMenus.ResultObject[i].Color + ';color:' + data.ChannelMenus.ResultObject[i].ForegroundColor + '');

                                        if (data.ChannelMenus.ResultObject[i].ChannelIconImage != "") {
                                            Channelimage.setAttribute("src", $.url().data.attr.source.split("?")[0] + data.ChannelMenus.ResultObject[i].ChannelIconImage.replace(/\\/g, "/") + "?" + currnetday.getTime());
                                        }
                                        ChannelName.innerHTML = data.ChannelMenus.ResultObject[i].Name;
                                        imageDiv.appendChild(Channelimage);
                                        ChannelAnchor.appendChild(imageDiv);
                                        ChannelAnchor.appendChild(ChannelName);
                                        ChannelParentDiv.appendChild(ChannelAnchor);
                                        ChannelList.appendChild(ChannelParentDiv);
                                        //Ps-1020:set color of category title as per category color
                                        // $('.channel-title-' + data.ChannelMenus.ResultObject[i].ChannelCategory.substring(0, 2) + '').css("color", data.ChannelMenus.ResultObject[i].ButtonColor);
                                        // $('.channel-title-10-' + data.ChannelMenus.ResultObject[i].ChannelCategory.substring(0, 2) + '').css("color", data.ChannelMenus.ResultObject[i].ButtonColor);
                                        //Ps-1020:set color of category title as per category color
                                        $('.channel-title-' + data.ChannelMenus.ResultObject[i].ChannelCategory.substring(0, 2) + '').css("color", data.ChannelMenus.ResultObject[i].ButtonColor);
                                        $('.channel-title-10-' + data.ChannelMenus.ResultObject[i].ChannelCategory.substring(0, 2) + '').css("color", data.ChannelMenus.ResultObject[i].ButtonColor);

                                        CategoryNames.appendChild(ChannelList);
                                        $('#NewChannelDiv').append(CategoryNames);
                                    }
                                }
                            });

                            RouteProvider.bindInnerRoutes();
                        }
                    }
                    $('#divChanneloverlaySpinner').hide();
                }
                ,
                function (data, status, headers, config) {
                    Spinner.Stop();
                    var messageViewModel = new MessageViewModel();
                    messageViewModel.CreateErrorMessage(data);
                    messageViewModel.ShowOverLay();
                }, JSON.stringify(object.Data));
        },

		this.getServicesMenu = function (currentRouteSetting, routeProvider, routeCurrentContext) {
			Repository.LoadDataWithGet(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetServicesMenu',
				function (data, status, headers, config) {
					if (data.Status == ResultStatus.Successful && data.ResultObject != null) {
						if (data.ResultObject.length != 0) {
							var CntforMobile = 0;
							var strMobServiceCategoryNames = "";
							var strMobServiceVCatNames = "";

							$.each(data.ResultObject, function (index, data) {
								var CategoryName = data.CategoryName;
								CntforMobile++;

								strMobServiceCategoryNames = '<a href="#Servicecategory' + CntforMobile + '" class="accordion-toggle menu-header-2 collapsed" data-toggle="collapse" data-parent=".sideMenuAccordoinChannelMenu" id="channelsTechnology">' + CategoryName + '</a>';
								strMobServiceCategoryNames += '<div class="panel-group sideMenuAccordoinChannelMenu">';
								strMobServiceCategoryNames += '<div class="panel panel-default">';

								strMobServiceCategoryNames += '<div class="panel-collapse collapse menu-submenu" id="Servicecategory' + CntforMobile + '">'
								strMobServiceNames = "";

								var CategoryName = data.CategoryName;
								var Maindiv = "";
								var SecondDiv = "";
								var channelLen = data.Services.length;
								var count = 1;

								for (k = 0; k < channelLen; k++) {
									strMobServiceNames += "<a href='javascript:void(0);'  onclick=CallServiceURL('" + data.Services[k].ServiceURL + "')    class='list-group-item'>" + data.Services[k].Name + "</a>";

									//make block of 4 channels
									if ((count % 4) === 0 || count == 1) {
										Maindiv = document.createElement("div");
										Maindiv.setAttribute('class', 'col-sm-2 itemheight checkcntforrow menu-dropdown-padding');//removed no-padding
										SecondDiv = document.createElement("div");

										//check column on specific row.if greater than 6 then append div with class=clearfix
										var len = $('.divserviceMenu').find('.checkcntforrow').length;
										if ((len % 6) == 0) {
											container = document.createElement("div");
											container.setAttribute('class', 'clearfix');
											$(".divserviceMenu").append(container);
										}

										if (count == 1) {
											Maindiv.innerHTML = "<h5> " + CategoryName + ":</h5>";
											SecondDiv.setAttribute('class', 'col-sm-12 no-padding');
										}
										else {
											//assign top margin if <h5> is blank
											Maindiv.innerHTML = "<h5></h5>";
											SecondDiv.setAttribute('class', 'top-margin-40');
										}
										Maindiv.appendChild(SecondDiv);
									}
									count = count + 1;
									var anchor = document.createElement("a");
									anchor.innerHTML += " " + data.Services[k].Name;
									anchor.innerHTML += "<br/>"
									//  anchor.setAttribute('class', 'channel-img-bottom-padding');
									anchor.setAttribute('href', "javascript:void(0);");
									anchor.setAttribute('onclick', "CallServiceURL('" + data.Services[k].ServiceURL + "')");
									SecondDiv.appendChild(anchor);
									$(".divserviceMenu").append(Maindiv);
								}
								strMobServiceCategoryNames += strMobServiceNames + '</div></div></div>'
								$(".divMobileServices").append(strMobServiceCategoryNames);
							});
							RouteProvider.bindInnerRoutes();
						}
					}
				}
				,
				function (data, status, headers, config) {
					Spinner.Stop();
					var messageViewModel = new MessageViewModel();
					messageViewModel.CreateErrorMessage(data);
					messageViewModel.ShowOverLay();
				});
		},

		this.EmergencyInformation = function () {
			var object = {
				Data: {
					"logonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
					"IsEmergencyShown": IsNullOrEmpty(sessionStorage.getItem("IsEmergencyShown")) ? false : sessionStorage.getItem("IsEmergencyShown"),
					"Id": IsNullOrEmpty(sessionStorage.getItem("EmergencyId")) ? 0 : sessionStorage.getItem("EmergencyId")
				}
			};
			$(".emergencyLogo").hide();
			$(".promotionalModelImage").hide();
			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/GetEmergencyInformation',
				function (data, status, headers, config) {
					if (data.Status == ResultStatus.Successful && data.ResultObject != null) {
						if (data.ResultObject.Type == "Emergency") {
							//  if (data.ResultObject.IsEmergencyShown && data.ResultObject.IsUpdated) {
							if (data.ResultObject.Title != null) {
								if (_this.IsWelcomeMessageShown == 0) {
									$("#div_emergency").modal('show');
								}
								$(".spn_emergencytext").html(data.ResultObject.EmergencyMessage);
								$(".div_emergencytitle").text(data.ResultObject.Title);
								if (data.ResultObject.ImagePath != "") {
									$(".emergencyLogo").attr("src", data.ResultObject.ImagePath);
									$(".emergencyLogo").show();
								}

								sessionStorage.setItem("IsEmergencyShown", true);
								sessionStorage.setItem("EmergencyId", data.ResultObject.Id);
							}
							//  }
						}
						else {
							// if (data.ResultObject.IsEmergencyShown && data.ResultObject.IsUpdated) {
							if (data.ResultObject.Title != null) {
								if (_this.IsWelcomeMessageShown == 0) {
									$("#div_Promotional").modal('show');
								}
								$(".div_promotionaltitle").text(data.ResultObject.Title);
								if (data.ResultObject.ImagePath != "") {
									$(".promotionalModelImage").attr("src", data.ResultObject.ImagePath);
									$(".promotionalModelImage").show();
								}
								$("#promotionalLink").attr("href", data.ResultObject.URL);
								sessionStorage.setItem("IsEmergencyShown", true);
								sessionStorage.setItem("EmergencyId", data.ResultObject.Id);

								//  }
							}
						}
					}
				},
				function (data, status, headers, config) {
					Spinner.Stop();
					var messageViewModel = new MessageViewModel();
					messageViewModel.CreateErrorMessage(data.Message);
					messageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		}

	this.validateIndividualUser = function () {
		//var _this = this;
		var individualUser = {
			LoginName: localStorage.getItem("UserName")
		};
		localStorage.setItem("UserName", "");
		var object = {
			Data: { "individualUser": individualUser }
		};

		Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/IndividualLogon',
			function (data, status, headers, config) {
				if (data.Status == ResultStatus.Successful) {
					//data = JSON.parse(data.ResultObject);
					data = data.ResultObject;
					localStorage.setItem("UserName", data.UserName);
					sessionStorage.setItem("LogonId", data.LogonId);
					localStorage.setItem("AccountId", data.AccountId);
					localStorage.setItem("IsTermsAndConditionsAccepted", data.IsTermsAndConditionsAccepted);
					localStorage.setItem("Welcome", data.Welcome);
					localStorage.setItem("IsIndividualUser", data.IsIndividualUser);
					localStorage.setItem("AccountType", data.AccountType);
					localStorage.setItem("CorporateUserType", data.CorporateUserType);
					//localStorage.setItem("DisplayBuySubscriptionSubMenu", true);
					//localStorage.setItem("IsIPLogin", false);
					sessionStorage.setItem("IsIPLogin", false);
					SetAccessCodeDetailsinSession();
					//sessionStorage.setItem("RedirectLocation", "Login");
					//if (!parseBool(data.IsTermsAndConditionsAccepted)) {
					//    location.href = Application.TermsandConditions.BaseURL;
					//}
					//else {
					//    location.href = '../?' + Application.Home.BaseURL;
					//}

					//if ((sessionStorage.getItem("RedirectFrom") != Application.SearchResult.BaseURL)) {
					//    sessionStorage.setItem("RedirectLocation", "Login");
					//}
					//if ((sessionStorage.getItem("RedirectFrom") != Application.SearchResult.BaseURL)
					//     && (sessionStorage.getItem("RedirectFrom") != Application.TaxonomyLandingPage.BaseURL)) {
					//    sessionStorage.setItem("RedirectLocation", "Login");
					//}
					if (!parseBool(data.IsTermsAndConditionsAccepted)) {
						location.href = Application.TermsandConditions.BaseURL;
					}
					else {
						location.href = '../?' + BrowserStorage.getRedireceLocationwithIndex();

						//if ((sessionStorage.getItem("RedirectFrom") == Application.SearchResult.BaseURL
						//    || sessionStorage.getItem("RedirectFrom") == Application.TaxonomyLandingPage.BaseURL)
						//    && !IsNullOrEmpty(sessionStorage.getItem("RedirectLocation"))) {
						//    //sessionStorage.setItem("RedirectFrom", "");
						//    location.href = '../?' + sessionStorage.getItem("RedirectLocation");
						//}
						//if ((sessionStorage.getItem("RedirectFrom") == Application.SearchResult.BaseURL)
						//    && !IsNullOrEmpty(sessionStorage.getItem("RedirectLocation"))) {
						//    //sessionStorage.setItem("RedirectFrom", "");
						//    location.href = '../?' + sessionStorage.getItem("RedirectLocation");
						//}
						//else {
						//    location.href = '../';
						//}
					}
					_this.loginMessage();
				}
				else {
					if (!IsNullOrEmpty(data.Message.trim())) {
						_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
							$("#okButtonId").unbind();
							$("#okButtonId").bind("click", function (e) {
								checkLoginStatus(data);
							});
						});
						_this.MessageViewModel.ShowOverLay();
					}
					else {
						sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);
						location.href = "LoginNew.html";
					}
				}
			},
			function (data, status, headers, config) {
				_this.MessageViewModel.CreateWarningMessage(data, "overlayId", "okButtonId", function () {
					$("#okButtonId").unbind();
					$("#okButtonId").bind("click", function (e) {
						checkLoginStatus(data);
					});
				});
				_this.MessageViewModel.ShowOverLay();
			}, JSON.stringify(object.Data));
	},

		this.validateIndividualUserSSO = function () {
			//var _this = this;
			var individualUser = {
				LoginName: sessionStorage.getItem("token_email"),
				IETMemberId: sessionStorage.getItem("token_MembershipNumber")
			};
			localStorage.setItem("UserName", "");
			var object = {
				Data: { "individualUser": individualUser }
			};
			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/IndividualLogonSSO',
				function (data, status, headers, config) {
					if (data.Status == ResultStatus.Successful) {
						//data = JSON.parse(data.ResultObject);
						data = data.ResultObject;
						localStorage.setItem("UserName", data.UserName);
						sessionStorage.setItem("LogonId", data.LogonId);
						localStorage.setItem("AccountId", data.AccountId);
						localStorage.setItem("IsTermsAndConditionsAccepted", data.IsTermsAndConditionsAccepted);
						localStorage.setItem("Welcome", data.Welcome);
						localStorage.setItem("IsIndividualUser", data.IsIndividualUser);
						localStorage.setItem("AccountType", data.AccountType);
						localStorage.setItem("CorporateUserType", data.CorporateUserType);
						//localStorage.setItem("DisplayBuySubscriptionSubMenu", true);
						//localStorage.setItem("IsIPLogin", false);
						sessionStorage.setItem("IsIPLogin", false);
						SetAccessCodeDetailsinSession();
						//sessionStorage.setItem("RedirectLocation", "Login");
						//if (!parseBool(data.IsTermsAndConditionsAccepted)) {
						//    location.href = Application.TermsandConditions.BaseURL;
						//}
						//else {
						//    location.href = '../?' + Application.Home.BaseURL;
						//}

						//if ((sessionStorage.getItem("RedirectFrom") != Application.SearchResult.BaseURL)) {
						//    sessionStorage.setItem("RedirectLocation", "Login");
						//}
						//if ((sessionStorage.getItem("RedirectFrom") != Application.SearchResult.BaseURL)
						//     && (sessionStorage.getItem("RedirectFrom") != Application.TaxonomyLandingPage.BaseURL)) {
						//    sessionStorage.setItem("RedirectLocation", "Login");
						//}
						if (!parseBool(data.IsTermsAndConditionsAccepted)) {
							location.href = Application.TermsandConditions.BaseURL;
						}
						else {
							if (sessionStorage.getItem("RedirectFromBeforeSSO") !== null && sessionStorage.getItem("RedirectFromBeforeSSO") !== "")
								location.href = sessionStorage.getItem("RedirectFromBeforeSSO");
							else {
								if (BrowserStorage.getRedireceLocationwithIndex() != null) {
									location.href = '../?' + BrowserStorage.getRedireceLocationwithIndex();
								}
								else {
									location.href = '../?' + Application.Root.BaseURL;
                                }
							}
						}
						_this.loginMessage();
					}
					else {
						if (!IsNullOrEmpty(data.Message.trim())) {
							_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
								$("#okButtonId").unbind();
								$("#okButtonId").bind("click", function (e) {
									checkLoginStatus(data);
								});
							});
							_this.MessageViewModel.ShowOverLay();
						}
						else {
							location.href = "LoginNew.html";
						}
					}
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateWarningMessage(data, "overlayId", "okButtonId", function () {
						$("#okButtonId").unbind();
						$("#okButtonId").bind("click", function (e) {
							checkLoginStatus(data);
						});
					});
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		},

		this.registerUser = function (jsonData) {
			//var _this = this;
			var object = {
				Data: { "user": jsonData }
			};
			Repository.LoadData(WebService.BaseURL + 'LogonService.svc/Register',
				function (data, status, headers, config) {
					if (data.Status == ResultStatus.Successful) {
						//data = JSON.parse(data.ResultObject);
						data = data.ResultObject;
						localStorage.setItem("UserName", data.UserName);
						sessionStorage.setItem("LogonId", data.LogonId);
						localStorage.setItem("AccountId", data.AccountId);
						localStorage.setItem("IsTermsAndConditionsAccepted", data.IsTermsAndConditionsAccepted);
						localStorage.setItem("Welcome", data.Welcome);
						localStorage.setItem("IsIndividualUser", data.IsIndividualUser);
						localStorage.setItem("AccountType", data.AccountType);
						localStorage.setItem("CorporateUserType", data.CorporateUserType);
						sessionStorage.setItem("IsIPLogin", false);
						SetAccessCodeDetailsinSession();

						location.href = Application.BaseURL + "TermsandConditions.html";
					}
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateWarningMessage(data, "overlayId", "okButtonId", function () {
						$("#okButtonId").unbind();
						$("#okButtonId").bind("click", function (e) {
							checkLoginStatus(data);
						});
					});
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		},

		//New Login message code
		this.loginMessage = function (jsonData) {
			var object = {
				Data: { "logonId": BrowserStorage.getLogonId() }
			};
			var enablePopup = BrowserStorage.getLoginPopup();
			if (localStorage.getItem("IsTermsAndConditionsAccepted") != true && (sessionStorage.getItem("IsIPLogin") == "true")) {
				object.Data = { "logonId": sessionStorage.getItem("LogonId") };
			}
			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/CorporateInstitutionLogo',
				function (data, status, headers, config) {
					if (data.Status == ResultStatus.Successful && data.LoginStatus == ResultStatus.Successful && data.ResultObject != null) {
						var logindetails = data.ResultObject;
						this.CurrentLoginDetails = {
							EmailAddress: logindetails.EmailAddress,
							filepath: logindetails.filepath,
							AccountName: logindetails.AccountName,
							welcomeNotification: logindetails.welcomeNotification,
							FirstName: logindetails.FirstName,
							LastName: logindetails.LastName,
							SubscriptionCount: logindetails.SubscriptionCount,
							IsIETMember: logindetails.IsIETMember,
							AccountTypeId: logindetails.AccountTypeId
						};

						if (localStorage.getItem("AccountType") == "Corporate" || localStorage.getItem("AccountType") == "Institution") {
							if (sessionStorage.getItem("IsIPLogin") == "false" || sessionStorage.getItem("IsIPLogin") == null) {
								if (localStorage.getItem("CorporateUserType") == 0 || localStorage.getItem("CorporateUserType") == 2) {
									_this.getwelcomeTextAndLogo(CurrentLoginDetails.filepath, CurrentLoginDetails.EmailAddress);
									_this.welcomeNotification(CurrentLoginDetails.welcomeNotification);
									$('#btn_access_details').hide();
									if (!enablePopup || enablePopup == false || typeof enablePopup === 'undefined') {
										_this.showLoginPopUp(CurrentLoginDetails.EmailAddress);
									}
								}//end of corporate/inst non admin

								//for admin user
								else if (localStorage.getItem("CorporateUserType") == 1) {
									_this.getwelcomeTextAndLogo(CurrentLoginDetails.filepath, CurrentLoginDetails.EmailAddress);
									_this.welcomeNotification(CurrentLoginDetails.welcomeNotification);
									_this.accessDetailButton(CurrentLoginDetails.SubscriptionCount);
									if (!enablePopup || enablePopup == false || typeof enablePopup === 'undefined') {
										_this.showLoginPopUp(CurrentLoginDetails.EmailAddress);
									}
								}//end of admin
							}//end of non ip

							//for ip
							else if (sessionStorage.getItem("IsIPLogin") == "true") {
								_this.getwelcomeTextAndLogo(CurrentLoginDetails.filepath, localStorage.getItem("Welcome"));
								_this.welcomeNotification(CurrentLoginDetails.welcomeNotification);
								$('#btn_access_details').hide();
								if (!enablePopup || enablePopup == false || typeof enablePopup === 'undefined') {
									_this.showLoginPopUp(localStorage.getItem("Welcome"));
								}
							}//end of ip
						}//end of corporate/institution

						//for individual
						else if (localStorage.getItem("IsIndividualUser") == "true") {
							$('#message_head').text('You have logged in as: ' + CurrentLoginDetails.FirstName + " " + CurrentLoginDetails.LastName);
							$('#user_logo').hide();
							_this.welcomeNotification(CurrentLoginDetails.welcomeNotification);
							_this.accessDetailButton(CurrentLoginDetails.SubscriptionCount);
							if (!enablePopup || enablePopup == false || typeof enablePopup === 'undefined') {
								_this.showLoginPopUp(CurrentLoginDetails.FirstName + " " + CurrentLoginDetails.LastName);
							}
						}//end of individual

						_this.BindHelpPageClick();
					}
				},
				function (data, status, headers, config) {
				}, JSON.stringify(object.Data));
		},

		this.getwelcomeTextAndLogo = function (logo, username) {
			$('#message_head').text('You have logged in as: ' + username);
			if (!IsNullOrEmpty(CurrentLoginDetails.filepath)) {
				$('#user_logo').attr("src", logo);
				$('#user_logo').show();
				$('.access-provided-container').removeClass("display-none");
				$('.access-provided-container-mobile').removeClass("display-none");
				$('#institutionLogoDesktop').attr("src", CurrentLoginDetails.filepath);
				$('#institutionLogoMobile').attr("src", CurrentLoginDetails.filepath);
				$('#institutionLogoDesktop').removeClass("display-none");
				$('#institutionLogoMobile').removeClass("display-none");
				$('#access-provided-by-desktop').removeClass("display-none");
				$('#access-provided-by-mobile').removeClass("display-none");
				$('#account-name-desktop').addClass("display-none");
				$('#account-name-mobile').addClass("display-none");
			}
			else {
				$('#user_logo').hide();
				$('.access-provided-container').removeClass("display-none");
				$('.access-provided-container-mobile').removeClass("display-none");
				if (!IsNullOrEmpty(CurrentLoginDetails.AccountName)) {
					$('#account-name-desktop').text(CurrentLoginDetails.AccountName);
					$('#account-name-mobile').text(CurrentLoginDetails.AccountName);
				}
				$('#institutionLogoDesktop').addClass("display-none");
				$('#institutionLogoMobile').addClass("display-none");
				$('#access-provided-by-desktop').removeClass("display-none");
				$('#access-provided-by-mobile').removeClass("display-none");
				$('#account-name-desktop').removeClass("display-none");
				$('#account-name-mobile').removeClass("display-none");
			}
		};

	this.welcomeNotification = function (welcomemessage) {
		if (!IsNullOrEmpty(CurrentLoginDetails.welcomeNotification)) {
			$('#brk').show();
			$('#welcome_notification').text(CurrentLoginDetails.welcomeNotification);
			$('#welcome_notification').show();
		} else {
			$('#brk').hide();
			$('#welcome_notification').hide();
		}
	};

	this.accessDetailButton = function (accessdetail) {
		if (CurrentLoginDetails.SubscriptionCount == true) {
			$('#btn_access_details').show();
		} else {
			$('#btn_access_details').hide();
		}
	};

	this.showLoginPopUp = function (username) {
		_this.IsWelcomeMessageShown = 1;
		//_this.EmergencyInformation();
		BrowserStorage.setLoginPopup(true);
		if (!IsNullOrEmpty(username)) {
			$("#loginWelcomeMessage").modal({
				backdrop: 'static',
				keyboard: false
			});
			$("#loginWelcomeMessage").modal('show');
		}
	};

	this.OnClickHelp = function () {
		var userType = "";
		if (localStorage.getItem("AccountType") == "Corporate") {
			userType = "ACorporate";
		} else if (localStorage.getItem("AccountType") == "Institution") {
			userType = "AInstitution";
		} else if (localStorage.getItem("IsIndividualUser") == "true") {
			if (CurrentLoginDetails.IsIETMember == true) {
				userType = "Member";
			}
			else if (CurrentLoginDetails.AccountTypeId == IndividualAccountTypeId) {
				userType = "Individual";
			}
			else {
				userType = "Visitor";
			}
		}

		//OpenHelpWindow(userType);
		//window.open('', 'new').location.href = "View/CMSHelpFullView.html?PageId=" + CMSPageMapping[userType] + "&PageName=" + userType;
		//window.open("View/CMSHelpFullView.html?PageId=" + CMSPageMapping[userType] + "&PageName=" + userType, "newwin", "toolbar=yes, scrollbars=yes, resizable=yes, top=100, left=500, width=600, height=500");
		//location.href = "View/CMSHelpFullView.html?PageId=" + CMSPageMapping[userType] + "&PageName=" + userType;

		var path = "?help=" + userType;
		location.href = path;
	};

	this.UnbindHelpPageClick = function () {
		$("#" + _this.btnLoginMessageHelp).unbind('click');
	}

	this.BindHelpPageClick = function () {
		_this.UnbindHelpPageClick();
		$("#" + _this.btnLoginMessageHelp).bind('click', _this.OnClickHelp);
	}

	this.setLoginDetail = function (jsonData) {
		if (jsonData.RememberMe) {
			$.cookie("username", jsonData.LoginName, { expires: 3650 }); //SETS IN DAYS (10 YEARS)
			$.cookie("password", jsonData.Password, { expires: 3650 });
			$.cookie("rememberme", jsonData.RememberMe, { expires: 3650 });
		}
		else {
			$.cookie("username", jsonData.LoginName, { expires: 0 });
			$.cookie("password", jsonData.Password, { expires: 0 });
			$.cookie("rememberme", jsonData.Password, { expires: 0 });
		}
	},

		this.getLoginDetail = function (jsonData) {
			if ($.cookie("username") && $.cookie("password") && $.cookie("rememberme")) {
				jsonData.LoginName = $.cookie("username");
				jsonData.Password = $.cookie("password");
				jsonData.RememberMe = parseBool($.cookie("rememberme"));
			}
		},

		this.checkUser = function (jsonData) {
			//var _this = this;
			ajaxAngularService.getDataByParam(
				{
					url: WebService.BaseURL + 'LogonService.svc/CheckUser',
					method: Method.POST,
					data: JSON.stringify(jsonData),
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					processData: true
				}).
				then(
					function (data, status, headers, config) {
						_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
							$("#okButtonId").unbind();
							$("#okButtonId").bind("click", function (e) {
								checkLoginStatus(data);
							});
						});
						_this.MessageViewModel.ShowOverLay();
					},
					function (data, status, headers, config) {
						_this.MessageViewModel.CreateWarningMessage(data, "overlayId", "okButtonId", function () {
							$("#okButtonId").unbind();
							$("#okButtonId").bind("click", function (e) {
								checkLoginStatus(data);
							});
						});
						_this.MessageViewModel.ShowOverLay();
					});
		},

		this.validateCorporateAdmin = function (jsonData) {
			//var _this = this;

			var object = {
				Data: { "corporateUser": jsonData }
			};

			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/AuthorizeCorporateAdmin',
				function (data, status, headers, config) {
					if (data.Status == ResultStatus.Successful && data.LoginStatus == ResultStatus.Successful) {
						data = data.ResultObject;
						localStorage.setItem("UserName", jsonData.LoginName);
						localStorage.setItem("AccountId", data.Id);
						localStorage.setItem("IsTermsAndConditionsAccepted", data.AccountConcurrentUsers[0].IsTermsAndConditionsAccepted);
						localStorage.setItem("Welcome", data.DisplayName);
						localStorage.setItem("IsIndividualUser", '');
						localStorage.setItem("AccountType", '');
						SetAccessCodeDetailsinSession();
						localStorage.setItem("CorporateUserType", data.AccountConcurrentUsers[0].CorporateUserType);
						if (!parseBool(data.AccountConcurrentUsers[0].IsTermsAndConditionsAccepted)) {
							location.href = Application.TermsandConditions.BaseURL;
						}
						else {
							//location.href = '../' + Application.MySubscription.BaseURL;
							if (sessionStorage.getItem("RedirectFromBeforeSSO") !== null && sessionStorage.getItem("RedirectFromBeforeSSO") !== "")
								location.href = sessionStorage.getItem("RedirectFromBeforeSSO");
							else {
								location.href = '../' + Application.MySubscription.BaseURL;
							}
						}
					}
					else {
						_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
						_this.MessageViewModel.ShowOverLay();
					}
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		},

		this.validateAllUsers = function (userCredential) {
			var isValidEmail = validateEmail(userCredential.LoginName);

			if (isValidEmail) {
				this.validateConcurrencyUser(userCredential);
			}
			else if (userCredential.LoginName.indexOf("@") < 0) {
				$('form[name=login]').attr('action', WebService.LogInRedirectURL).attr('method', Method.POST).submit();
				localStorage.setItem("UserName", userCredential.LoginName);
			}
			var login = {
				UserName: userCredential.LoginName,
				Password: userCredential.Password
			};
			this.setLoginDetail(login);
		},

		this.checkCorporateUserAlreadyLoggedIn = function (jsonData) {
			//var _this = this;

			var object = {
				Data: { "corporateUserCredential": jsonData }
			};

			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/CheckCorporateUserAlreadyLoggedIn',
				function (data, status, headers, config) {
					if (data.Status == ResultStatus.Successful) {
						if (data.ResultObject) {
							_this.validateConcurrencyUser(jsonData);
							//_this.validateAllUsers(jsonData);
						}
						else {
							//message, overlayId, yesButtonId, noButtonId, BindMessageEvents
							_this.MessageViewModel.CreateConfirmationMessage(data.Message, "overlayId", "yesButtonId", 'noButtonId', function () {
								$("#yesButtonId").unbind();
								$("#yesButtonId").bind("click", function (e) {
									_this.validateConcurrencyUser(jsonData);
									//_this.validateAllUsers(jsonData);
								});
							});
							_this.MessageViewModel.ShowOverLay();
						}
					}
					else {
						_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
							$("#okButtonId").unbind();
							$("#okButtonId").bind("click", function (e) {
								checkLoginStatus(data);
							});
						});
						_this.MessageViewModel.ShowOverLay();
					}
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		},

		this.checkIndividualUserAlreadyLoggedInSSO = function () {
			//var _this = this;
			var individualUser = {
				IETMemberId: sessionStorage.getItem("token_MembershipNumber"),
				UserName: sessionStorage.getItem("token_email"),
				LoginName: localStorage.getItem("UserName")
			};
			var object = {
				Data: { "individualUserCredential": individualUser }
			};

			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/CheckIndividualUserAlreadyLoggedInSSO',
				function (data, status, headers, config) {
					sessionStorage.setItem("ServiceStatus", data.Status);
					sessionStorage.setItem("FromIndividualUserCheck", true);
					sessionStorage.setItem("IsIndividualUserAlreadyLoggedIn", data.ResultObject);
					sessionStorage.setItem("Message", data.Message);

					if (data.Status == ResultStatus.Successful && data.ResultObject) {
						if (data.ResultObject) {
							_this.validateIndividualUserSSO();
						}
					}
					else {
						location.href = Application.Login.BaseURL;
					}
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		},

		this.checkIndividualUserAlreadyLoggedIn = function () {
			//var _this = this;
			var individualUser = {
				LoginName: localStorage.getItem("UserName")
			};
			var object = {
				Data: { "individualUserCredential": individualUser }
			};

			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/CheckIndividualUserAlreadyLoggedIn',
				function (data, status, headers, config) {
					sessionStorage.setItem("ServiceStatus", data.Status);
					sessionStorage.setItem("FromIndividualUserCheck", true);
					sessionStorage.setItem("IsIndividualUserAlreadyLoggedIn", data.ResultObject);
					sessionStorage.setItem("Message", data.Message);

					if (data.Status == ResultStatus.Successful && data.ResultObject) {
						if (data.ResultObject) {
							_this.validateIndividualUser();
							//location.href = Application.Home.BaseURL;
						}
						else {
						}
						//if (data.ResultObject) {
						//    _this.validateIndividualUser(individualUser);
						//}
						//else {
						//    _this.MessageViewModel.CreateConfirmationMessage(data.Message, "overlayId", "yesButtonId", 'noButtonId', function () {
						//        $("#yesButtonId").unbind();
						//        $("#yesButtonId").bind("click", function (e) {
						//            _this.validateIndividualUser(individualUser);
						//    });
						//    _this.MessageViewModel.ShowOverLay();
						//}
					}
					else {
						location.href = Application.Login.BaseURL;
						//_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
						//    $("#okButtonId").unbind();
						//    $("#okButtonId").bind("click", function (e) {
						//        checkLoginStatus(data);
						//    });
						//});
						//_this.MessageViewModel.ShowOverLay();
					}
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		},

		this.ipLogon = function () {
			//var _this = this;

			Repository.LoadDataFalseAjax(WebService.BaseURL + 'LogonService.svc/IPLogon',
				function (data, status, headers, config) {
					if (ResultStatus.Successful == data.Status) {
						data = data.ResultObject;
						localStorage.setItem("UserName", data.UserName);
						sessionStorage.setItem("LogonId", data.LogonId);
						localStorage.setItem("AccountId", data.AccountId);
						localStorage.setItem("AdditionalLogin_AccountId", data.AccountId);
						localStorage.setItem("IsTermsAndConditionsAccepted", false);
						localStorage.setItem("Welcome", data.Welcome);
						localStorage.setItem("IsIndividualUser", data.IsIndividualUser);
						localStorage.setItem("AccountType", data.AccountType);
						localStorage.setItem("CorporateUserType", data.CorporateUserType);
						localStorage.setItem("IsStaffAccount", data.IsStaffAccount);
						//sessionStorage.setItem("RedirectLocation", Application.Home.BaseURL);
						if (data.IsIPLogin)// && data.IsIPRanges) {
						{
							sessionStorage.setItem("IsIPLogin", true);
						}

						SetAccessCodeDetailsinSession();
						_this.setMessage();
						//_this.loginMessage();
						$("#" + _this.MenuLoginId).hide();
						$("#" + _this.MenuLoggedInAsDifferentUserId).show();
						$("#" + _this.MenuAccountId).show();
						$("#" + _this.MenuChangePassword).hide();
						//For Mobile

						$("#" + _this.MenuBuySubscription).hide();
						$("#" + _this.MobileMenuBuySubscription).hide();
						$("#" + _this.MenuAccountSubMenuMySubscriptionId).hide();
						$("#" + _this.MenuAccountSubMenuMySubscriptionMobileId).hide();
						$("#" + _this.MenuAccountSubMenuUserManagememtId).hide();
						$("#" + _this.MenuAccountSubMenuSystemUsageReportId).hide();
						$("#" + _this.MenuMarcRecordDownloadId).hide();

						$("#" + _this.MenuLoginMobileId).hide();
						$("#" + _this.MenuLoggedInAsDifferentUserMobileId).show();
						$("#" + _this.MenuAccountMobileId).show();
						$("#" + _this.MenuChangePasswordMobileId).hide();
						$("#" + _this.MenuUserGeneratedContentId).hide();
						$("#" + _this.UserGeneratedContentMobileId).hide();
					}
					else {
						if (!data.IsIPLogin) {
							sessionStorage.setItem("IsIPLogin", false);
						}
						$("#" + _this.MenuLoginId).show();
						$("#" + _this.MenuLoginId).css('content', '');
						$("#" + _this.MenuAccountId).hide();
						$("#" + _this.MenuMessageId).hide();
						$("#" + _this.MenuLoggedInAsDifferentUserId).hide();

						//For Mobile
						$("#" + _this.MenuLoginMobileId).show();
						$("#" + _this.MenuLoginMobileId).css('content', '');
						$("#" + _this.MenuAccountMobileId).hide();
						$("#" + _this.MenuMessageMobileId).hide();
						$("#" + _this.MenuLoggedInAsDifferentUserMobileId).hide();
					}
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				});
		},

		this.logOut = function (jsonData, redirectTo, routeName) {
			//var _this = this;
			//var object = {
			//    Data: { "user": jsonData }
			//};
			//if (sessionStorage.getItem("IsIPLogin") == "true") {
			//    _this.loginMessage();
			//}
			//else
			//localStorage.setItem("IndividualUserReg", "0");
			$('#institutionLogoDesktop').addClass("display-none");
			$('#institutionLogoMobile').addClass("display-none");
			$('#access-provided-by-desktop').addClass("display-none");
			$('#access-provided-by-mobile').addClass("display-none");
			$('#account-name-desktop').addClass("display-none");
			$('#account-name-mobile').addClass("display-none");//
			$('#access-provided-container-mobile').addClass("display-none");
			$('#access-provided-container').addClass("display-none");
			var object = {
				Data: {
					"user": {
						LogonId: BrowserStorage.getLogonId()
					}
				}
			};

			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/Logoff',
				function (data) {
					if (ResultStatus.Successful == data.Status) {
						//if IsIndividualUser is true then it will redirect to client domain and come back to local domain.
						_this.clearBrowserStorage();
						if ($.cookie('Shib_EPPN')) {
							$('#shib_Logout_Frame').attr('src', ShibbolethConfig.ShibbolethServiceProviderRootURL + "/Shibboleth.sso/Logout");
							var cookie_expdate = new Date();  // current date & time
							cookie_expdate.setTime(cookie_expdate.getTime() - 1);
							$.cookie('Shib_EPPN', null,
								{
									//expires: ShibbolethConfig.cookietimeOutInMinuts,
									expires: cookie_expdate,
									path: '/',
									domain: ShibbolethConfig.Domain,
									secure: true,
									raw: true
								});
							/*$.cookie('Shib_EPPN', null,
													   {
														   expires: ShibbolethConfig.cookietimeOutInMinuts,
														   path: '/',
														   domain: ShibbolethConfig.Domain,
														   secure: true,
														   raw: true
													   });*/

							_this.MessageViewModel.CreateWarningMessage('For security reasons, please close all your browser windows.', "overlayId", "okButtonId", function () {
								$('#okButtonId').click(function () {
									if (redirectTo.length > 0) {
										location.href = redirectTo;
									}
								});
							});
							_this.MessageViewModel.ShowOverLay();
						}
						else if (parseBool(localStorage.getItem("IsIndividualUser"))) {
							localStorage.setItem("IsIndividualUser", "false");

							policyLogout(helloNetwork.adB2CSignInSignUp, policies.signInSignUpPolicy);
							//$('form[name=logout]').
							//    attr('action', WebService.LogOffRedirctURL).
							//    attr('method', Method.POST).submit();
						}
						else if (redirectTo.length > 0) {
							localStorage.setItem("IsIndividualUser", "false");
							location.href = redirectTo;
						}

						if (routeName == "additionalLogin") {
							localStorage.setItem("AdditionalLogin", "true");
						}
						else {
							localStorage.setItem("AdditionalLogin", "false");
						}
					}

					storeurlDetailsInGA("Logout");
				},
				function (data) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		},

		this.clearUserSession = function () {
			$.cookie("sessionId", "", { path: '/' });
			localStorage.setItem("Welcome", "");
			localStorage.setItem("UserName", "");
			sessionStorage.setItem("LogonId", "");
			localStorage.setItem("AccountId", 0);
			localStorage.setItem("IsTermsAndConditionsAccepted", "false");
			localStorage.setItem("AccountType", "");
			localStorage.setItem("CorporateUserType", "");
			localStorage.setItem("IsStaffAccount", "false");
			localStorage.removeItem("token_email");
		},

		this.clearBrowserStorage = function () {
			$.cookie("sessionId", "", { path: '/' });
			localStorage.setItem("UserName", "");
			localStorage.setItem("LoginStatus", "");
			localStorage.setItem("accessCode", "");
			localStorage.setItem("accessCodeFlag", "");
			localStorage.setItem("accessCodeType", "");
			sessionStorage.setItem("LogonId", "");
			sessionStorage.setItem("ProductId", "");
			sessionStorage.setItem("ChannelId", "");
			sessionStorage.setItem("Type", "");
			sessionStorage.setItem("OrderId", "");
			localStorage.setItem("AccountId", 0);
			localStorage.setItem("IsTermsAndConditionsAccepted", "false");
			localStorage.setItem("Welcome", "");
			sessionStorage.setItem("RedirectLocation", "");
			sessionStorage.setItem("RedirectFrom", "");
			localStorage.setItem("AccountType", "");
			localStorage.setItem("CorporateUserType", "");
			//localStorage.setItem("DisplayBuySubscriptionSubMenu", true);
			sessionStorage.setItem("IsIPLogin", false);
			sessionStorage.removeItem("NotificationFlag");
			sessionStorage.removeItem("SelectedProductId");
			sessionStorage.setItem("IsPasswordReset", '');
			BrowserStorage.setLoginPopup(false);
			sessionStorage.removeItem("CallerPage");
			sessionStorage.removeItem("subscriptionFilter");
			sessionStorage.removeItem("OrderId");
			sessionStorage.removeItem("OrderCode");
			sessionStorage.removeItem("accessCode");
			sessionStorage.removeItem("accessCodeType");
			sessionStorage.removeItem("accessCodeFlag");
			sessionStorage.setItem("accessCodeFlag", false);
			sessionStorage.removeItem("RedirectFromBeforeSSO");
			localStorage.removeItem("token_email");
			//   sessionStorage.removeItem("IsEmergencyShown");
		},

		this.setMessage = function () {
        $('#' + _this.MenuMessageId).show().html("Welcome: " + localStorage.getItem("Welcome"));
        $('#' + _this.MenuMessageId).prop('title', localStorage.getItem("Welcome"));/*Added css for PS-1411 start*/
			//For Mobile
        $('#' + _this.MenuMessageMobileId).show().html("Welcome: " + localStorage.getItem("Welcome"));
        $('#' + _this.MenuMessageMobileId).prop('title', localStorage.getItem("Welcome"));/*Added css for PS-1411 start*/
			$('#' + _this.Menumessage_mobileOffLine).hide();
			_this.loginMessage();
		},

		this.setMessageForSpeaker = function () {
        $('#' + _this.MenuMessageId).show().html("Welcome: " + localStorage.getItem("Welcome"));
        $('#' + _this.MenuMessageId).prop('title', localStorage.getItem("Welcome"));/*Added css for PS-1411 start*/
        $('#' + _this.MenuMessageMobileId).show().html("Welcome: " + localStorage.getItem("Welcome"));
        $('#' + _this.MenuMessageMobileId).prop('title', localStorage.getItem("Welcome"));/*Added css for PS-1411 start*/
			$('#' + _this.Menumessage_mobileOffLine).hide();
			$("#" + _this.MenuLoginId).hide();
			$("#" + _this.MenuAccountId).show();
			$("#" + _this.MenuLogoutId).show();
			$("#" + _this.MenuBuySubscription).hide();
			$("#" + _this.MenuAccountSubMenuMySubscriptionId).hide();
			$("#" + _this.MenuChangePassword).hide();

			//For Mobile
			$("#" + _this.MobileMenuBuySubscription).hide();
			$("#" + _this.MenuAccountSubMenuMySubscriptionMobileId).hide();
			$("#" + _this.MenuAccountSubMenuUserManagememtId).hide();
			$("#" + _this.MenuAccountSubMenuSystemUsageReportId).hide();
			$("#" + _this.MenuMarcRecordDownloadId).hide();
			$("#" + _this.MenuLoginMobileId).hide();
			$("#" + _this.MenuLoggedInAsDifferentUserMobileId).hide();
			$("#" + _this.MenuAccountMobileId).show();
			$("#" + _this.MenuLogoutMobileId).show();
			$("#" + _this.MenuChangePasswordMobileId).hide();
			$("#" + _this.UserGeneratedContentMobileId).hide();
		},
		this.validateCorporateAdminBasedOnLogonId = function (currentRouteSetting, routeProvider, routeCurrentContext) {
			var object = {
				Data: { "logonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId") }
			};

			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/CheckMySubscriptionAccessBasedOnLogonId',
				function (data, status, headers, config) {
					if (ResultStatus.Successful == data.LoginStatus) {
						if (ResultStatus.Successful == data.Status && data.ResultObject
							&& !IsNullOrEmpty(localStorage.getItem("IsTermsAndConditionsAccepted"))
							&& parseBool(localStorage.getItem("IsTermsAndConditionsAccepted"))) {
							if (sessionStorage.getItem("RedirectLocation") == Application.MySubscription.BaseURL) {
								new MySubscription();   //create object of MySubscription() class
								//location.href = Application.MySubscription.BaseURL;
							}
							else if (sessionStorage.getItem("RedirectLocation") == Application.UserManagement.BaseURL) {
								if (!WebService.DisableGA) {
									storeurlDetailsInGA('UserManagement');
								}
								var userManagement = new UserManagement();
								userManagement.GetCorporateAdminUsers(currentRouteSetting, routeProvider, routeCurrentContext);
							}
							else if (sessionStorage.getItem("RedirectLocation") == Application.SystemUsageReport.BaseURL) {
								$.ajax({
									url: currentRouteSetting.configuration.templateUrl,
									success: function (data) {
										$('#viewContent').html(data);
										routeProvider.bindInnerRoutes();
									}
								});
							}
							else if (sessionStorage.getItem("RedirectLocation").toLowerCase() == Application.buySubscription.BaseURL.toLowerCase()) {
								var subscriptionMatrix = new SubscriptionMatrix();
								subscriptionMatrix.InitSubscriptionMatrix()
							}
							else if (sessionStorage.getItem("RedirectLocation").toLowerCase() == Application.UserAccessReport.BaseURL.toLowerCase() || Application.UserAccessNotification.BaseURL.toLowerCase()) {
								$.ajax({
									url: currentRouteSetting.configuration.templateUrl,
									success: function (data) {
										$('#viewContent').html(data);
										routeProvider.bindInnerRoutes();
										if (!WebService.DisableGA) {
											storeurlDetailsInGA('UserAccessReport');
										}
										var userAccessReport = new UserAccessReport();
										userAccessReport.InitilizeReport();
									}
								});
							}
							else {
								if (sessionStorage.getItem("RedirectLocation") !== null) {
									location.href = sessionStorage.getItem("RedirectLocation");
								}
								else {
									sessionStorage.setItem("RedirectLocation", Application.MySubscription.BaseURL);
									location.href = 'view/' + Application.Login.BaseURL;
								}
							}
						}
						else {
							_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
								$("#okButtonId").unbind();
								$("#okButtonId").bind("click", function (e) {
									//  sessionStorage.setItem("RedirectLocation", Application.UserAccessNotification.BaseURL);
									checkLoginStatus(data);
									//  sessionStorage.setItem("RedirectLocation", Application.UserAccessReport.BaseURL);
								});
							});
							_this.MessageViewModel.ShowOverLay();
						}
					}
					else {
						_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
							$("#okButtonId").unbind();
							$("#okButtonId").bind("click", function (e) {
								// sessionStorage.setItem("RedirectLocation", Application.UserAccessNotification.BaseURL);
								checkLoginStatus(data);
							});
						});
						_this.MessageViewModel.ShowOverLay();
					}
				},

				function (data, status, headers, config) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		},
		this.validateCorporateAdminBasedOnLogonIdForReport = function () {
			//var _this = this;

			var object = {
				Data: { "logonId": sessionStorage.getItem("LogonId") }
			};

			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/CheckMySubscriptionAccessBasedOnLogonId',
				function (data, status, headers, config) {
					if (ResultStatus.Successful == data.LoginStatus) {
						if (ResultStatus.Successful == data.Status && data.ResultObject
							&& !IsNullOrEmpty(localStorage.getItem("IsTermsAndConditionsAccepted"))
							&& parseBool(localStorage.getItem("IsTermsAndConditionsAccepted"))) {
							location.href = Application.Report.BaseURL;
						}
						else {
							sessionStorage.setItem("RedirectLocation", Application.Report.BaseURL);
							location.href = 'view/' + Application.Login.BaseURL;
						}
					}
					else {
						_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
							$("#okButtonId").unbind();
							$("#okButtonId").bind("click", function (e) {
								checkLoginStatus(data);
							});
						});
						_this.MessageViewModel.ShowOverLay();
					}
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		},
		this.enableAccounForMySubscription = function () {
			//var _this = this;

			var object = {
				Data: { "logonId": sessionStorage.getItem("LogonId") }
			};
			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/GetAccountSubMenuLinks',
				function (data, status, headers, config) {
					if (ResultStatus.Successful == data.LoginStatus && ResultStatus.Successful == data.Status) {
						//if (!IsNullOrEmpty(data.ResultObject))
						{
							$("#" + _this.MenuAccountSubMenuMySubscriptionId).css('display', 'none');
							$("#" + _this.MenuAccountSubMenuUserManagememtId).css('display', 'none');
							$("#" + _this.MenuUserManagementMobileId).css('display', 'none');
							$("#" + _this.MenuAccountSubMenuMySubscriptionMobileId).css('display', 'none');//
							$("#" + _this.MenuAccountSubMenuSystemUsageReportId).css('display', 'none');
							$("#" + _this.MenuMarcRecordDownloadId).css('display', 'none');
							$("#" + _this.MenuChangePasswordMobileId).css('display', 'none');
							$("#" + _this.UserGeneratedContentMobileId).css('display', 'none');
							$("#" + _this.MenuChangePassword).css('display', 'none');

							if (data.ResultObject.length > 0) {
								$("#" + _this.MenuAccountId).show();
								$("#" + _this.MenuAccountMobileId).show();

								for (i = 0; i < data.ResultObject.length; i++) {
									if (data.ResultObject[i].toLowerCase().indexOf("MySubscription".toLowerCase()) >= 0) {
										$("#" + _this.MenuAccountSubMenuMySubscriptionId).show();
										$("#" + _this.MenuAccountSubMenuMySubscriptionMobileId).show();
									}
									if (data.ResultObject[i].toLowerCase().indexOf("UserManagememt".toLowerCase()) >= 0) {
										$("#" + _this.MenuAccountSubMenuUserManagememtId).show();
										$("#" + _this.MenuUserManagementMobileId).show();
									}
									if (data.ResultObject[i].toLowerCase().indexOf("SystemUsageReport".toLowerCase()) >= 0) {
										$("#" + _this.MenuAccountSubMenuSystemUsageReportId).show();
										$("#" + _this.MenuMarcRecordDownloadId).show();
									}
									if (data.ResultObject[i].toLowerCase().indexOf("HideBuySubscription".toLowerCase()) >= 0) {
										$("#" + _this.MenuBuySubscription).hide();
										$("#" + _this.MobileMenuBuySubscription).hide();
									}
									if (data.ResultObject[i].toLowerCase().indexOf("ChangePassword".toLowerCase()) >= 0) {
										$("#" + _this.MenuChangePassword).show();
										$("#" + _this.MenuChangePasswordMobileId).show();
									}
									if (data.ResultObject[i].toLowerCase().indexOf("UserGeneratedContent".toLowerCase()) >= 0) {
										$("#" + _this.UserGeneratedContentMobileId).show();
									}
								}
							}
							//if (data.ResultObject.length > 0) {
							//    $("#" + _this.MenuAccountId).show();
							//    $("#" + _this.MenuAccountMobileId).show();

							//    for (i = 0; i < data.ResultObject.length; i++) {
							//        if (data.ResultObject[i].toLowerCase().indexOf("MySubsctiption".toLowerCase())) {
							//            $("#" + _this.MenuAccountSubMenuMySubscriptionId).show();
							//            $("#" + _this.MenuAccountSubMenuMySubscriptionMobileId).show();
							//        }
							//        if (data.ResultObject[i].toLowerCase().indexOf("UserManagememt".toLowerCase())) {
							//            $("#" + _this.MenuAccountSubMenuUserManagememtId).show();
							//            $("#" + _this.MenuAccountSubMenuMySubscriptionMobileId).show();
							//        }
							//        if (data.ResultObject[i].toLowerCase().indexOf("SystemUsageReport".toLowerCase())) {
							//            //$("#" + _this.MenuAccountSubMenuSystemUsageReportId).show(); //TO DO for Mobile
							//            $("#" + _this.MenuAccountSubMenuSystemUsageReportId).show();
							//        }
							//        //if (data.ResultObject[i].toLowerCase().indexOf("HideBuySubscription".toLowerCase())) {
							//        //    $("#" + _this.MenuBuySubscription).hide();
							//        //}
							//    }
							//}
							//else {
							//    //Disable Account menu in menu bar
							//    //$("#" + _this.MenuAccountId).hide();
							//    //$("#" + _this.MenuAccountMobileId).hide();

							//    $("#" + _this.MenuAccountSubMenuMySubscriptionId).hide();
							//    $("#" + _this.MenuAccountSubMenuUserManagememtId).hide();
							//    $("#" + _this.MenuAccountSubMenuMySubscriptionMobileId).hide();
							//    $("#" + _this.MenuAccountSubMenuSystemUsageReportId).hide();

							//}
						}
					}
					else {
						location.href = "?" + Application.Home.BaseURL;
					}
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		},

		this.IsRestrictedUser = function () {
			var object = {
				Data: { "logonId": sessionStorage.getItem("LogonId") }
			};
			if ((object.Data.logonId == null) || (object.Data.logonId == '')) {
				Repository.LoadData(WebService.BaseURL + 'LogonService.svc/IsRestrictedUser',
					function (data, status, headers, config) {
						if (ResultStatus.Failed == data.Status) {
							//location.href = "view/RestrictedAccess.html";
						}
						else if (ResultStatus.Successful == data.Status && data.ResultObject != null) {
							//data.ResultObject.RegionType = "Redirect"
							//data.ResultObject.RedirectionUrl = "https://www.google.ru/";
							if (data.ResultObject.RegionType == "Redirect") {
								var redirectmodalmessage = 'The IP Address of the country you are accessing this site from is set to be redirected to the following link';
								$('.redirect-text').text(redirectmodalmessage + ' " ' + data.ResultObject.RedirectionUrl + ' "');
								sessionStorage.setItem("RestrictedRedirect", data.ResultObject.RedirectionUrl);
								//$("#" + _this.redirecthref).text(data.ResultObject.RedirectionUrl);
								//$("#" + _this.redirecthref).attr("href", data.ResultObject.RedirectionUrl);
								$("#" + _this.redirectBtn).text(data.ResultObject.RedirectionText);
								_this.BindRedirectButton();

								$("#modalRedirect").modal({
									backdrop: 'static',
									keyboard: false
								});
								$("#modalRedirect").modal('show');
							}
							else if (data.ResultObject.RegionType == 'Restricted') {
								//console.log('test');
								var modalmessage = 'Access to IET tv from your current location has been restricted. IET Members, please click on login';

								sessionStorage.setItem("RestrictedRedirect", 'view/' + Application.Login.BaseURL);
								//Hide Regitration link in restricted location
								sessionStorage.setItem("IsFromRestricted", '1');

								$('.modal-body').text(modalmessage);
								//$("#" + _this.redirecthref).text('view/' + Application.Login.BaseURL);
								//$("#" + _this.redirecthref).attr("href", 'view/' + Application.Login.BaseURL);
								$("#" + _this.redirectBtn).text('Redirect to Login Page');
								_this.BindRedirectButton();

								$("#modalRedirect").modal({
									backdrop: 'static',
									keyboard: false
								});
								$("#modalRedirect").modal('show');
							}
						}
					},
					function (data, status, headers, config) {
						_this.MessageViewModel.CreateErrorMessage(data);
						_this.MessageViewModel.ShowOverLay();
					});
			}
		},

		this.IsRedirctForLogin = function () {
			var object = {
				Data: { "logonId": sessionStorage.getItem("LogonId") }
			};
			if ((object.Data.logonId == null) || (object.Data.logonId == '')) {
				Repository.LoadData(WebService.BaseURL + 'LogonService.svc/IsRestrictedUser',
					function (data, status, headers, config) {
						if (ResultStatus.Failed == data.Status) {
						}
						else if (ResultStatus.Successful == data.Status && data.ResultObject != null) {
							if (data.ResultObject.RegionType == 'Restricted') {
								$("#registrationLink").hide();
							}
						}
					},
					function (data, status, headers, config) {
						_this.MessageViewModel.CreateErrorMessage(data);
						_this.MessageViewModel.ShowOverLay();
					});
			}
		},

		this.IsRestrictedUser_ByUserId = function (jsonData) {
			var _this = this;
			var object = {
				Data: { "user": jsonData.LoginName }
			};

			var IsRestricted = false;

			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/IsUserRestricted',
				function (data, status, headers, config) {
					if (data.Status == ResultStatus.Successful) {
						if (data.ResultObject == true) {
							$("#modalRestrictedAccess").modal({
								backdrop: 'static',
								keyboard: false
							});
							$("#modalRestrictedAccess").modal('show');
						}
						else {
							var user = {
								LoginName: jsonData.LoginName,
								Password: jsonData.Password,
								RememberMe: jsonData.RememberMe,
								IsAdditionalLogin: jsonData.IsAdditionalLogin,
								AccountId: jsonData.AccountId
							};

							//  _this.validateCorporateAdmin(user);

							if (user.LoginName != '' && user.Password != '') {
								_this.setLoginDetail(user);

								var isValidEmail = validateEmail(user.LoginName);
								if (isValidEmail) {
									_this.checkCorporateUserAlreadyLoggedIn(user);
								}
								//else if (user.LoginName.indexOf("@") < 0) {
								//    //To Doo first validate the individual login
								//    //if success then we assume its returm EmailID,

								//    _this.checkIETServiceAccessibleForLogin(user.LoginName);
								//    //$("#loginDiv").wrap("<form name='login'><form>");
								//    //$('form[name=login]').attr('action', WebService.LogInRedirectURL).attr('method', Method.POST).submit();
								//    //localStorage.setItem("UserName", user.LoginName);
								//}
								else if (!isValidEmail) {
									_this.MessageViewModel.CreateWarningMessage("Please provide your proper Emailid", "overlayId", "okButtonId");
									_this.MessageViewModel.ShowOverLay();
								}
							}
						}
					}
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		},

		this.GetCountryCodeByIPAddress = function () {
			Repository.LoadData(WebService.BaseURL + 'LogonService.svc/GetCountryCodeByIPAddress',
				function (data, status, headers, config) {
					//console.log(data);
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				});
		},

		this.getSessionIdForBrowserAndGetLogonIdExistsForSession = function () {
			//var _this = this;
			if ($.cookie("sessionId") == undefined || $.cookie("sessionId") == "") {
				Repository.LoadDataFalseAjax(WebService.BaseURL + 'LogonService.svc/GetSessionId',
					function (data, status, headers, config) {
						$.cookie("sessionId", data.ResultObject, { path: '/' });
					},
					function (data, status, headers, config) {
						_this.MessageViewModel.CreateErrorMessage(data);
						_this.MessageViewModel.ShowOverLay();
					});
			}
			this.getLogonIdExistsForSession();
			//this.IsRestrictedUser();
		},

		this.getLogonIdExistsForSession = function () {
			Repository.LoadDataFalseAjax(WebService.BaseURL + 'LogonService.svc/GetLogonIdExistsForSession',
				function (data, status, headers, config) {
					if (ResultStatus.Successful == data.Status) {
						//sessionStorage.setItem("LogonId", data.ResultObject);
						//sessionStorage.setItem("RedirectFrom", Application.Root.BaseURL);
						localStorage.setItem("CommingFrom", Application.Home.BaseURL);
						localStorage.setItem("UserIP", data.UserIP);
						if (IsNullOrEmpty(localStorage.getItem("IsTermsAndConditionsAccepted"))) {
							localStorage.setItem("IsTermsAndConditionsAccepted", false);
						}
						$("#" + _this.MenuLogoutId).hide();
						$("#" + _this.MenuLogoutMobileId).hide();
						if (!IsNullOrEmpty(sessionStorage.getItem("LogonId")) && (sessionStorage.getItem("NotificationFlag") == null || parseBool(sessionStorage.getItem("NotificationFlag")) == true)) {
							NotificationRepository.CheckNotificationForUser();
						}
						if (IsNullOrEmpty(sessionStorage.getItem("LogonId")) || parseBool(localStorage.getItem("IsTermsAndConditionsAccepted")) == false) {
							$("#" + _this.MenuAccountId).hide();
							$("#" + _this.MenuLoggedInAsDifferentUserId).hide();

							$("#" + _this.MenuAccountMobileId).hide();
							$("#" + _this.MenuLoggedInAsDifferentUserMobileId).hide();
							if (sessionStorage.getItem("IsIPLogin") == "false" || sessionStorage.getItem("IsIPLogin") == null) {
								_this.clearUserSession();
								$('#' + _this.AdditionalLogin).hide();
							}
							if ($.cookie('Shib_EPPN') && $.cookie('Shib_EPPN') != 'null') {
								_this.ShibbolethLogon();
							}
							else {
								_this.ipLogon();
							}
						}
						else {
							$("#" + _this.MenuAccountId).show();
							$("#" + _this.MenuMessageId).show();
							_this.setMessage();
							//_this.loginMessage();
							$("#" + _this.MenuLoginId).hide();

							// For Mobile
							$("#" + _this.MenuAccountMobileId).show();
							$("#" + _this.MenuMessageMobileId).show();
							$("#" + _this.MenuLoginMobileId).hide();

							if (sessionStorage.getItem("RedirectLocation") == "Home") {
								$("#" + _this.MenuLoggedInAsDifferentUserId).show();
								$("#" + _this.MenuLoggedInAsDifferentUserMobileId).show();
							}
							else {
								$("#" + _this.MenuLogoutId).show();
								$("#" + _this.MenuLoggedInAsDifferentUserId).hide();

								$("#" + _this.MenuLogoutMobileId).show();
								$("#" + _this.MenuLoggedInAsDifferentUserMobileId).hide();
							}

							_this.enableAccounForMySubscription();
						}
					}
				},
				function (data, status, headers, config) {
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				});
		},

		this.AcceptTAndC = function () {
			sessionStorage.setItem("RedirectFrom", Application.Root.BaseURL);
			var userName = localStorage.getItem("UserName")
			var jsonData = {
				logonId: BrowserStorage.getLogonId(),
				userName: userName
			};

			Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/Privacy',
				function (data) {
					if (ResultStatus.Successful == data.Status) {
						localStorage.setItem("IsTermsAndConditionsAccepted", true);
						if (sessionStorage.getItem("IsPasswordReset") == "true") {
							location.href = '../' + Application.ChangePassword.BaseURL;
						}
						//else if (localStorage.getItem("RedirectLocation") == 'Login') {
						//	if (sessionStorage.getItem("RedirectFromBeforeSSO") !== null && sessionStorage.getItem("RedirectFromBeforeSSO") !== "") {
						//		location.href = sessionStorage.getItem("RedirectFromBeforeSSO");
						//	}
						//	else {
						//		location.href = '../?' + BrowserStorage.getRedireceLocationwithIndex();
						//	}
						//}
						//else if (localStorage.getItem("RedirectLocation") != undefined || localStorage.getItem("RedirectLocation") != '') {
						//	if (sessionStorage.getItem("IsPasswordReset") == "true") {
						//		location.href = '../' + Application.ChangePassword.BaseURL;
						//	} else {
						//		if (sessionStorage.getItem("RedirectFromBeforeSSO") !== null && sessionStorage.getItem("RedirectFromBeforeSSO") !== "") {
						//			location.href = sessionStorage.getItem("RedirectFromBeforeSSO");
						//		}
						//		else {
						//			location.href = '../?' + BrowserStorage.getRedireceLocationwithIndex();
						//		}
						//	}
						//}
						else {
							if (sessionStorage.getItem("RedirectFromBeforeSSO") !== null && sessionStorage.getItem("RedirectFromBeforeSSO") !== "") {
								location.href = sessionStorage.getItem("RedirectFromBeforeSSO");
							}
							else {
								location.href = '../?' + BrowserStorage.getRedireceLocationwithIndex();
							}
						}
					}
				},
				function (data) {
					_this.MessageViewModel.CreateErrorMessage(data.Message);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(jsonData));
		}

	this.HasChild = function (lookup, rootId, element) {
		var hasChild = false;
		for (k = 0; k < lookup.length; k++) {
			if (eval("lookup[k]." + element) == rootId) {
				hasChild = true;
			}
		}
		return hasChild;
	};

	this.GetChildTaxonomyMenu = function (rootId, elementRootId, parentMenuContext) {
		var object = {
			Data: {
				"taxonomy": {
					"RootId": rootId
				}
			}
		};

		Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/SubMenu',
			function (data) {
				if (ResultStatus.Successful == data.Status) {
					var classList = $(parentMenuContext).parents(".dropdown-menu").attr("class").split(" ");
					var parentcombination = $(parentMenuContext).attr("data-parentcombination");

					var className = "";
					for (i = 0; i < classList.length; i++) {
						if (classList[i].indexOf("Ul_") > -1) {
							className = classList[i];
						}
					}

					var rootId = 0;
					var desktopString = "<ul class=\"dropdown-menu-sub drop_downmenu_Custom_sub " + className + "\">";
					desktopString += "<div class=\"Back_parent\"><span class=\"glyphicon glyphicon-chevron-left\"></span> &nbsp;" + data.ResultObject[0].RootName + "</div>";
					desktopString += "<li>";
					desktopString += "<div class=\"row\" style=\"width: 600px;\">";

					for (i = 0; i < data.ResultObject.length; i++) {
						desktopString += "<a href=\"#\" data-dismiss=\"modal\" class=\"sub_menu_custom col-md-4 close_div\" data-RootId=" + data.ResultObject[i].RootId + " data-ChildId=" + data.ResultObject[i].ChildId +
							" data-routeName=\"taxonomyLandingPage\" data-combination=\"" + parentcombination + " AND " + data.ResultObject[i].RootName + " AND " + data.ResultObject[i].ChildName +
							"\">" + data.ResultObject[i].ChildName + "</a>";
					}
					desktopString += "</div>";
					desktopString += "</li>";
					desktopString += "</ul>";

					var parentElement = $(parentMenuContext).parents(".dropdown");
					$(parentElement).remove(".drop_downmenu_Custom_sub");
					$(parentElement).append(desktopString);
					$(parentMenuContext).closest('.drop_downmenu_Custom').parent().find('.drop_downmenu_Custom').hide();
					$(parentMenuContext).closest('.drop_downmenu_Custom').parent().find('.drop_downmenu_Custom_sub').show();

					RouteProvider.bindRoutes();

					$('.Back_parent').unbind("click");
					$('.Back_parent').bind("click", function () {
						$(this).closest('.drop_downmenu_Custom_sub').hide();
						$(this).closest('.drop_downmenu_Custom_sub').parent().find('.drop_downmenu_Custom').show();
					});

					$('.close_div').click(function () {
						$('.drop_downmenu_Custom_sub').hide();
					});
				}
			},
			function (data) {
				_this.MessageViewModel.CreateErrorMessage(data.Message);
				_this.MessageViewModel.ShowOverLay();
			}, JSON.stringify(object.Data));
	};

	this.checkIETServiceAccessibleForLogin = function (userName) {
		var _this = this;
		var object = {
			Data: { "keyId": "login" }
		};

		Repository.LoadDataJSON(WebService.BaseURL + 'Utility/UtilityService.svc/GetGeneralParameters',
			function (data, status, headers, config) {
				if (data.Status == ResultStatus.Successful && data.ResultObject) {
					var url = window.location.pathname;
					var Filename = getPageName(url);

					if (Filename == "Registration") {
						$("#loginDiv").wrap("<form name='login'></form>");
					}

					$('form[name=login]').attr('action', WebService.LogInRedirectURL).attr('method', Method.POST).submit();
					localStorage.setItem("UserName", userName);
				}
				else {
					_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
					_this.MessageViewModel.ShowOverLay();
				}
			},
			function (data, status, headers, config) {
				_this.MessageViewModel.CreateWarningMessage(data, "overlayId", "okButtonId", function () {
					$("#okButtonId").unbind();
					$("#okButtonId").bind("click", function (e) {
						checkLoginStatus(data);
					});
				});
				_this.MessageViewModel.ShowOverLay();
			}, JSON.stringify(object.Data));
	};

	function getPageName(url) {
		var index = url.lastIndexOf("/") + 1;
		var filenameWithExtension = url.substr(index);
		var filename = filenameWithExtension.split(".")[0];
		return filename;
	};

	this.UnbindRedirectButton = function () {
		$("#" + _this.redirectBtn).unbind('click')
	};

	this.BindRedirectButton = function () {
		_this.UnbindRedirectButton();

		$("#" + _this.redirectBtn).bind('click', function (e) {
			location.href = sessionStorage.getItem("RestrictedRedirect");
		});
	};

	this.UnbindHelpPage = function () {
		$("#" + _this.helpPage).unbind('click')
	};

	this.BindHelpPage = function () {
		_this.UnbindHelpPage();

		$("#" + _this.helpPage).bind('click', function (e) {
			location.href = sessionStorage.getItem("");
		});
	};

	this.UnbindAccessDetailsPage = function () {
		$("#" + _this.myIETTvPage).unbind('click')
	};

	this.BindAccessDetailsPage = function () {
		_this.UnbindAccessDetailsPage();

		$("#" + _this.myIETTvPage).bind('click', function (e) {
			location.href = sessionStorage.getItem("mySubscription");
		});
	};

	this.ShibbolethLogin = function () {
		$(_this.btnShibbolethLogin).unbind('click');
		$(_this.btnShibbolethLogin).bind('click', function () {
			var externalOrg = $(this).attr("data-Val").toUpperCase();
			$.cookie('Shib_RedirectURL', ShibbolethConfig.RedirectURL + '?' + BrowserStorage.getRedireceLocationwithIndex(),
				{
					expires: ShibbolethConfig.cookietimeOutInMinuts,
					path: '/',
					domain: ShibbolethConfig.Domain,
					secure: true,
					raw: true
				});

			$.cookie('Shib_RedirectFrom', ShibbolethConfig.RedirectFrom,
				{
					expires: ShibbolethConfig.cookietimeOutInMinuts,
					path: '/',
					domain: ShibbolethConfig.Domain,
					secure: true,
					raw: true
				});

			$.cookie('Shib_LoginPage', window.location.href,
				{
					expires: ShibbolethConfig.cookietimeOutInMinuts,
					path: '/',
					domain: ShibbolethConfig.Domain,
					secure: true,
					raw: true
				});

			$.cookie('Shib_DesktopViewLogoURL', ShibbolethConfig.DesktopViewLogoURL,
				{
					expires: ShibbolethConfig.cookietimeOutInMinuts,
					path: '/',
					domain: ShibbolethConfig.Domain,
					secure: true,
					raw: true
				});

			$.cookie('Shib_MobileViewLogoURL', ShibbolethConfig.MobileViewLogoURL,
				{
					expires: ShibbolethConfig.cookietimeOutInMinuts,
					path: '/',
					domain: ShibbolethConfig.Domain,
					secure: true,
					raw: true
				});

			if (externalOrg == "SB") {
				window.location.href = ShibbolethConfig.ShibbolethServiceProviderURL;
			}
			else {
				var EntityId = "https://idp.eduserv.org.uk/openathens";
				var ShibbolethTargetURL = ShibbolethConfig.ShibbolethServiceProviderRootURL;
				window.location.href = ShibbolethTargetURL + "/Shibboleth.sso/Login?entityID=" + EntityId + "&forceAuthn=false&target=" + ShibbolethTargetURL + "/home/success";
			}
		});
	};

	this.ShibbolethLogon = function () {
		Repository.LoadData(WebService.BaseURL + 'LogonService.svc/ShibbolethLogon?instituteAttribute=' + $.cookie('Shib_EPPN'),
			function (data, status, headers, config) {
				if (ResultStatus.Successful == data.Status) {
					data = data.ResultObject;
					localStorage.setItem("UserName", data.UserName);
					sessionStorage.setItem("LogonId", data.LogonId);
					localStorage.setItem("AccountId", data.AccountId);
					localStorage.setItem("IsTermsAndConditionsAccepted", false);
					localStorage.setItem("Welcome", data.Welcome);
					localStorage.setItem("IsIndividualUser", data.IsIndividualUser);
					localStorage.setItem("AccountType", data.AccountType);
					localStorage.setItem("CorporateUserType", data.CorporateUserType);
					//sessionStorage.setItem("RedirectLocation", Application.Home.BaseURL);
					//sessionStorage.setItem("IsShibbolethLogin", true);
					sessionStorage.setItem("IsIPLogin", true);
					SetAccessCodeDetailsinSession();
					_this.setMessage();
					//_this.loginMessage();
					$("#" + _this.MenuLoginId).hide();
					$("#" + _this.MenuLoggedInAsDifferentUserId).show();
					$("#" + _this.MenuAccountId).show();
					$("#" + _this.MenuChangePassword).hide();
					//For Mobile

					$("#" + _this.MenuBuySubscription).hide();
					$("#" + _this.MobileMenuBuySubscription).hide();
					$("#" + _this.MenuAccountSubMenuMySubscriptionId).hide();
					$("#" + _this.MenuAccountSubMenuMySubscriptionMobileId).hide();
					$("#" + _this.MenuAccountSubMenuUserManagememtId).hide();
					$("#" + _this.MenuAccountSubMenuSystemUsageReportId).hide();
					$("#" + _this.MenuMarcRecordDownloadId).hide();

					$("#" + _this.MenuLoginMobileId).hide();
					$("#" + _this.MenuLoggedInAsDifferentUserMobileId).show();
					$("#" + _this.MenuAccountMobileId).show();
					$("#" + _this.MenuChangePasswordMobileId).hide();
					$("#" + _this.MenuUserGeneratedContentId).hide();
					$("#" + _this.UserGeneratedContentMobileId).hide();
				}
				else {
					$("#" + _this.MenuLoginId).show();
					$("#" + _this.MenuLoginId).css('content', '');
					$("#" + _this.MenuAccountId).hide();
					$("#" + _this.MenuMessageId).hide();
					$("#" + _this.MenuLoggedInAsDifferentUserId).hide();

					//For Mobile
					$("#" + _this.MenuLoginMobileId).show();
					$("#" + _this.MenuLoginMobileId).css('content', '');
					$("#" + _this.MenuAccountMobileId).hide();
					$("#" + _this.MenuMessageMobileId).hide();
					$("#" + _this.MenuLoggedInAsDifferentUserMobileId).hide();
					_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
					_this.MessageViewModel.ShowOverLay();
					$.cookie('Shib_EPPN', null,
						{
							expires: ShibbolethConfig.cookietimeOutInMinuts,
							path: '/',
							domain: ShibbolethConfig.Domain,
							secure: true,
							raw: true
						});
				}
			},
			function (data, status, headers, config) {
				_this.MessageViewModel.CreateErrorMessage(data);
				_this.MessageViewModel.ShowOverLay();
			});
	};

	//End
	var _this = this;
};

function CallServiceURL(ServiceURL) {
	//Closing the Mobile menu
	var containerResource = $("#cbp-spmenu-s1");
	if (parseInt($("#cbp-spmenu-s1").css('left')) == 0) {
		$("#showLeftPush").trigger('click');
	}
	//close desktop service menu view
	if ($('#divServices').hasClass("in")) {
		$('#divServices').collapse('toggle');
	}
	url = $.trim(ServiceURL);
	var pattern = /^((http|https|ftp):\/\/)/;
	if (!pattern.test(url) && url != "") {
		url = "http://" + url;
	}
	if (url != "") {
		window.open(url, '_blank');
	}
}

function callloginfaq() {
	location.href = "../?faq";
}

function SetAccessCodeDetailsinSession() {
	var accessCode = "";
	var accessCodeType = "";
	var accessCodeFlag = "";
	var routeSeriesVideoId = "seriesvideoid";

	if (!IsNullOrEmpty(localStorage.getItem("accessCode"))) {
		accessCode = localStorage.getItem("accessCode");
		sessionStorage.setItem("accessCode", accessCode);
	}

	if (!IsNullOrEmpty(localStorage.getItem("accessCodeType"))) {
		accessCodeType = localStorage.getItem("accessCodeType");
		sessionStorage.setItem("accessCodeType", accessCodeType);
	}

	if (!IsNullOrEmpty(localStorage.getItem("accessCodeFlag"))) {
		accessCodeFlag = localStorage.getItem("accessCodeFlag");
		sessionStorage.setItem("accessCodeFlag", accessCodeFlag);
	}

	if (!IsNullOrEmpty(sessionStorage.getItem("RedirectFrom"))) {
		var redirectFrom = sessionStorage.getItem("RedirectFrom")
		if (redirectFrom == routeSeriesVideoId) {
			sessionStorage.setItem("RedirectLocation", routeSeriesVideoId)
		}
	}
}
var PurchasedChannelList = [];
var BuyMoreTotal = 0;
var SelectedBuyTotal = 0;
var MsgForBuyMore = "";
var MemberShipPage = "";
var premiumVideoIds = [];
var channelCatalogList;

var SubscriptionRepository = {
	GetPendingMarcDownloadDetails: function (callback) {
		var userInfo = {
			"subInfo": {
				AccountId: IsNullOrEmpty(localStorage.getItem("AccountId")) ? 0 : localStorage.getItem("AccountId"),
				LogonId: IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")
			}
		};

		Repository.LoadDataJSON(WebService.BaseURL + 'Subscriptions/SubscriptionService.svc/MarcSubscriptions',
			function (data, status, headers, config) {
				if (data.LoginStatus == ResultStatus.Successful) {
					if (data.Status == ResultStatus.Successful && data.ResultObject != null) {
						if ($.isFunction(callback)) {
							callback(data.ResultObject);
						}
					}
					else {
						Spinner.Stop();
						var messageViewModel = new MessageViewModel();
						messageViewModel.CreateErrorMessage(data.Message);
						messageViewModel.ShowOverLay();
					}
				}
				else {
					sessionStorage.setItem("RedirectLocation", Application.MySubscription.BaseURL);
					sessionStorage.setItem("RedirectFrom", Application.SearchResult.BaseURL);
					sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);
					_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
						$("#okButtonId").unbind();
						$("#okButtonId").bind("click", function (e) {
							checkLoginStatus(data);
							location.href = "view/" + Application.Login.BaseURL;
						});
					});
					_this.MessageViewModel.ShowOverLay();
				}
				RouteProvider.bindInnerRoutes();
			},
			function (data, status, headers, config) {
				Spinner.Stop();
				var messageViewModel = new MessageViewModel();
				messageViewModel.CreateErrorMessage(data.Message);
				messageViewModel.ShowOverLay();
			},
			JSON.stringify(userInfo));
	},

	DownloadMarcRecords: function (params, callback) {
		var data = {
			accountId: IsNullOrEmpty(localStorage.getItem("AccountId")) ? 0 : localStorage.getItem("AccountId"),
			logonId: IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
			time: new Date($.now()).getHours() + new Date($.now()).getMinutes() + new Date($.now()).getSeconds()
		};

		$.extend(data, params);
		var downloadUrl = WebService.BaseURL + 'Subscriptions/SubscriptionService.svc/DownloadMarcRecords?' + decodeURIComponent($.param(data));
		var $downloadFrame = $("#fileDownload");
		if ($downloadFrame.length == 1) {
			$downloadFrame.attr('src', downloadUrl);
		} else {
			window.location = downloadUrl;
		}
		callback();
	},

	GetUserSubscriptionDetails: function (requestType) {
		var object = {
			Data: {
				"subInfo": {
					AccountId: IsNullOrEmpty(localStorage.getItem("AccountId")) ? 0 : localStorage.getItem("AccountId"),
					LogonId: IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")//,
					// RequestType: requestType
				}
			}
		};

		Repository.LoadDataJSON(WebService.BaseURL + 'Subscriptions/SubscriptionService.svc/MarcSubscriptions',
			function (data, status, headers, config) {
				if (ResultStatus.Successful == data.LoginStatus) {
					if (ResultStatus.Successful == data.Status && data.ResultObject != null) {
						var subscriptionSet = [];

						if (data.ResultObject.Subscription.length != 0) {
							$.each(data.ResultObject.Subscription, function (index, data) {
								subscriptionSet.push({ ChannelId: data.ChannelID, CatalogueStartDate: data.CatalogueFrom, CatalogueEndDate: data.CatalogueTo });
							});

							channelCatalogList = "<Video>";
							$.each(subscriptionSet, function (index, data) {
								channelCatalogList += "<Channel><ChannelId>" +
									data.ChannelId +
									"</ChannelId><CatalogueStartYear>" +
									data.CatalogueStartDate +
									"</CatalogueStartYear><CatalogueEndYear>" +
									data.CatalogueEndDate +
									"</CatalogueEndYear></Channel>";
							});
							channelCatalogList += "<ModifiedDateFilter>1900-03-24T00:00:00</ModifiedDateFilter><AccountId>" +
								object.Data.subInfo.AccountId +
								"</AccountId></Video>";
						} else {
							$('#SubscriptionTable').html("No records found.");
							var IndividualUserType = data.ResultObject.IndividualUserType != null ? data.ResultObject.IndividualUserType : "";
							if (parseBool(localStorage.getItem("IsIndividualUser")) && IndividualUserType.toLowerCase() != "registered") {
								$('#SubscriptionTable').html(data.ResultObject.MemberMessage);
							}
						}
						if (data.ResultObject.PurchasedContent.length != 0) {
							premiumVideoIds = [];
							$.each(data.ResultObject.PurchasedContent, function (index, data) {
								premiumVideoIds.push(data.ProdContentId);
							});
						}
						else { }
					}
					else {
						Spinner.Stop();
						var messageViewModel = new MessageViewModel();
						messageViewModel.CreateErrorMessage(data.Message);
						messageViewModel.ShowOverLay();
					}
				}
				else {
					sessionStorage.setItem("RedirectLocation", Application.MySubscription.BaseURL);
					sessionStorage.setItem("RedirectFrom", Application.SearchResult.BaseURL);
					_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
						$("#okButtonId").unbind();
						$("#okButtonId").bind("click", function (e) {
							checkLoginStatus(data);
							location.href = "view/" + Application.Login.BaseURL;
						});
					});
					_this.MessageViewModel.ShowOverLay();
				}
				RouteProvider.bindInnerRoutes();
			},
			function (data, status, headers, config) {
				Spinner.Stop();
				var messageViewModel = new MessageViewModel();
				messageViewModel.CreateErrorMessage(data.Message);
				messageViewModel.ShowOverLay();
			},
			JSON.stringify(object.Data));
	},

	getAllSubscriptions: function () {
		var object = {
			Data: {
				"subInfo": {
					AccountId: IsNullOrEmpty(localStorage.getItem("AccountId")) ? 0 : localStorage.getItem("AccountId"),
					LogonId: IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")
				}
			}
		};
		Repository.LoadDataJSON(WebService.BaseURL + 'Subscriptions/SubscriptionService.svc/Subscriptions',
			function (data, status, headers, config) {
				if (ResultStatus.Successful == data.LoginStatus) {
					if (ResultStatus.Successful == data.Status && data.ResultObject != null) {
						$('.mysubscriptionNotification').attr('checked', data.ResultObject.IsNotificationEnabled);

						if (data.ResultObject.Subscription.length != 0) {
							var subscriptionTable = '<tr  class="table-heading-background hidden-sm hidden-xs">' +
								'<th class="hidden-md hidden-lg"></th>' +
								'<th>Channels</th>' +
								'<th>Catalogue</th>' +
								'<th>Type</th>' +
								'<th>Purchase Date</th>' +
								'<th>Access Start Date</th>' +
								'<th>Access Expiry date</th>';
							subscriptionTable += '</tr>';
							$.each(data.ResultObject.Subscription, function (index, data) {
								subscriptionTable += '<tr>' +


                                    //For Mobile menu start
                                   '<td class="hidden-md hidden-lg">' +
                                  '<table class="table-heading-background table inner_table_border">' +
                                  '<tbody><tr><td class="inner_table_td">Channels</td><td class="inner_table_value" style="color: #222222; font-style:bold;">' + "<a data-innerroutename='Channel' class='custom_pointer subscription-table-mobile'  data-ChannelId='" + data.ChannelID + "' data-name='" + data.ChannelName + "' data-color='" + data.ChannelColor + "'>" + data.ChannelName + "</a>" + '</td></tr>' +
                                   '<tr> <td class="inner_table_td">Catalogue</td> <td class="inner_table_value">' + data.CatalogueName + '</td></tr>  ' +
                                      '<tr> <td class="inner_table_td">Type</td> <td class="inner_table_value">' + data.Type + '</td></tr>  ' +
                                         '<tr> <td class="inner_table_td">Purchase Date</td> <td class="inner_table_value">' + data.PurchaseDate + '</td></tr>  ' +
                                            '<tr> <td class="inner_table_td">Access Start Date</td> <td class="inner_table_value">' + data.SubscriptionStartDate + '</td></tr>  ' +
                                            '<tr> <td class="inner_table_td">Access Expiry date</td> <td class="inner_table_value">' + data.SubscriptionEndDate + '</td></tr>  ' +
                                   '</tbody> </table> </td>' +

									//For Mobile menu end

									'<td class="hidden-sm hidden-xs">' + "<a data-innerroutename='Channel' class='custom_pointer' data-ChannelId='" + data.ChannelID + "' data-name='" + data.ChannelName + "' data-color='" + data.ChannelColor + "'>" + data.ChannelName + "</a>" + '</td>' +
									'<td class="hidden-sm hidden-xs">' + data.CatalogueName + '</td>' +
									'<td class="hidden-sm hidden-xs">' + data.Type + '</td>' +
									'<td class="hidden-sm hidden-xs">' + data.PurchaseDate + '</td>' +
									'<td class="hidden-sm hidden-xs">' + data.SubscriptionStartDate + '</td>' +
									'<td class="hidden-sm hidden-xs">' + data.SubscriptionEndDate + '</td>';

								subscriptionTable += '</tr>';
							});
							$('#SubscriptionTable').html(subscriptionTable);
							//To show catalogue description
							$('#divCatalogueText').html("");
							if (parseBool(localStorage.getItem("IsIndividualUser"))) {
								$("#divCataloguelist").show();
								var StrCatalogueDesc = "";
								$.each(data.ResultObject.CatalogueList, function (index, Cataloguedata) {
									StrCatalogueDesc += Cataloguedata + "<br/>";
								});
								$('#divCatalogueText').append(StrCatalogueDesc);
							}
						}
						else {
							$('#SubscriptionTable').html("No records found.");
							var IndividualUserType = data.ResultObject.IndividualUserType != null ? data.ResultObject.IndividualUserType : "";
							//Check for member user
							if (parseBool(localStorage.getItem("IsIndividualUser")) && IndividualUserType.toLowerCase() != "registered") {
								$('#SubscriptionTable').html(data.ResultObject.MemberMessage);
							}
							//Check for staff user
							if (data.ResultObject.IsStaffAccount) {
								$('#SubscriptionTable').html(data.ResultObject.MemberMessage);
							}
						}
						if (data.ResultObject.PurchasedContent.length != 0) {
							var PurchasedContentTable = '<tr  class="table-heading-background hidden-sm hidden-xs">' +

								'<th class="hidden-md hidden-lg"></th>' +
								'<th >Content Type</th>' +
								'<th>Title</th>' +
								'<th>Purchase Date</th>' +
								'<th>Start Date</th>' +
								'<th>End Date</th>';
							PurchasedContentTable += '</tr>';

							$.each(data.ResultObject.PurchasedContent, function (index, data) {
								if (data.ContentType == "Video") {
									PurchasedContentTable += '<tr>' +

                                      //For Mobile menu start
                                        '<td class="hidden-md hidden-lg">' +
                                  '<table class="table inner_table_border table_layout">' +
                                  '<tbody>  <tr><td class="inner_table_td width_40">ContentType</td><td class="width_60" style="color: #222222;">' + data.ContentType + '</td></tr>' +
                                   '<tr> <td class="inner_table_td width_40">Title</td> <td class="width_60">' + "<a data-innerroutename='videoid' class='custom_pointer' data-videono='" + data.ProdContentNo + "'  data-ChannelId='0' data-hasindex='true' data-videoId='" + data.ProdContentId + "' data-videoTitle=\'" + data.Title + "\' data-Duration='" + data.Duration + " '  data-SubscriptionType='" + data.SubscriptionType + " '>" + data.Title + "</a>" + '</td></tr>  ' +
                                         '<tr> <td class="inner_table_td width_40">Purchase Date</td> <td class="width_60">' + data.PurchaseDate + '</td></tr>  ' +
                                            '<tr> <td class="inner_table_td width_40">Start Date</td> <td class="width_60">' + data.SubscriptionStartDate + '</td></tr>  ' +
                                            '<tr> <td class="inner_table_td width_40">End date</td> <td class="width_60">' + data.SubscriptionEndDate + '</td></tr>  ' +
                                   '</tbody> </table> </td>' +
                                    //Mobile menu end

										'<td class="hidden-sm hidden-xs">' + data.ContentType + '</td>' +
										'<td class="hidden-sm hidden-xs">' + "<a data-innerroutename='videoid' class='custom_pointer' data-videono='" + data.ProdContentNo + "' data-ChannelId='0' data-hasindex='true' data-videoId='" + data.ProdContentId + "'  data-videoTitle=\'" + data.Title + "\' data-Duration='" + data.Duration + " '  data-SubscriptionType='" + data.SubscriptionType + " '>" + data.Title + "</a>" + '</td>' +
										'<td class="hidden-sm hidden-xs">' + data.PurchaseDate + '</td>' +
										'<td class="hidden-sm hidden-xs">' + data.SubscriptionStartDate + '</td>' +
										'<td class="hidden-sm hidden-xs">' + data.SubscriptionEndDate + '</td>';

									PurchasedContentTable += '</tr>';
								}
								else if (data.ContentType == "Event") {
									PurchasedContentTable += '<tr>' +

                                      //For Mobile menu start
                                        '<td class="hidden-md hidden-lg">' +
                                  '<table class="table inner_table_border table_layout">' +
                                  '<tbody>  <tr><td class="inner_table_td width_40">ContentType</td><td class="width_60" style="color: #222222;">' + data.ContentType + '</td></tr>' +
                                   '<tr> <td class="inner_table_td width_40">Title</td> <td class="width_60">' + "<a data-innerroutename='event' class='custom_pointer' data-hasindex='true' data-eventid='" + data.ProdContentId + "' data-eventTitle=\'" + data.Title + "\'>" + data.Title + "</a>" + '</td></tr>  ' +
                                         '<tr> <td class="inner_table_td width_40">Purchase Date</td> <td class="width_60">' + data.PurchaseDate + '</td></tr>  ' +
                                            '<tr> <td class="inner_table_td width_40">Start Date</td> <td class="width_60">' + data.SubscriptionStartDate + '</td></tr>  ' +
                                            '<tr> <td class="inner_table_td width_40">End date</td> <td class="width_60">' + data.SubscriptionEndDate + '</td></tr>  ' +
                                   '</tbody> </table> </td>' +
                                    //Mobile menu end

										'<td class="hidden-sm hidden-xs">' + data.ContentType + '</td>' +
										'<td class="hidden-sm hidden-xs">' + "<a data-innerroutename='event' class='custom_pointer' data-hasindex='true' data-eventid='" + data.ProdContentId + "' data-eventTitle=\'" + data.Title + "\'>" + data.Title + "</a>" + '</td>' +
										'<td class="hidden-sm hidden-xs">' + data.PurchaseDate + '</td>' +
										'<td class="hidden-sm hidden-xs">' + data.SubscriptionStartDate + '</td>' +
										'<td class="hidden-sm hidden-xs">' + data.SubscriptionEndDate + '</td>';


                                    PurchasedContentTable += '</tr>';
                                }

                            });
                            
                            $('#PurchasedContentTable').html(PurchasedContentTable);
                            $("#PurchasedContentTable tr th:visible:even").css("background-color", "white");
                            $("#PurchasedContentTable tr td:visible:even").css("background-color", "white");
                            
                        }
                        else
                        {
                            $('#PurchasedContentTable').html("No records found.");
                            //Check for staff user
                            if (data.ResultObject.IsStaffAccount)
                            {
                                $('#PurchasedContentTable').html(data.ResultObject.MemberMessage);
                            }
                        }

                    }
                    else
                    {
                        Spinner.Stop();
                        var messageViewModel = new MessageViewModel();
                        messageViewModel.CreateErrorMessage(data.Message);
                        messageViewModel.ShowOverLay();
                    }
                }
                else {
                    sessionStorage.setItem("RedirectLocation", Application.MySubscription.BaseURL);
                    sessionStorage.setItem("RedirectFrom", Application.SearchResult.BaseURL);
                    _this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
                        $("#okButtonId").unbind();
                        $("#okButtonId").bind("click", function (e) {
                            checkLoginStatus(data);
                            location.href = "view/" + Application.Login.BaseURL;
                        });
                    });
                    _this.MessageViewModel.ShowOverLay();

                }
                RouteProvider.bindInnerRoutes();
                if (!WebService.DisableGA) {
                     storeurlDetailsInGA('MySubscription');
                }

            },
            function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data.Message);
                messageViewModel.ShowOverLay();

            }, JSON.stringify(object.Data));
    },

	getSubscriptionMatrix: function (CallerPage) {
		var _this = this;
		SelectedBuyTotal = 0;
		BuyMoreTotal = 0;
		var VideoId = "";

		//To Clear Buy More Fields.
		$('.divPurchaseChannels').empty();
		$("#divSubscription_message").empty();

		$("#divCatalogueText").empty();
		$(".video-specific-channel-text").addClass("display-none");
		$("#divBuyMore").hide();
		$("#spnTotal").html('Total : ' + '£');

		if (CallerPage == "BuyChannel" && (IsNullOrEmpty(sessionStorage.getItem("VideoId")) == false)) {
			VideoId = sessionStorage.getItem("VideoId");
		}
		// hide  div if no channel block is selected.
		parseFloat(SelectedBuyTotal) > 0 ? $(".purchase-final-price-div-container").show() : $(".purchase-final-price-div-container").hide();
		var object = {
			Data: {
				"logonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
				"VideoId": VideoId
			}
		};
		Repository.LoadDataJSON(WebService.BaseURL + 'Subscriptions/SubscriptionService.svc/GetChannelAccess',
			function (data) {
				if (data.Status == ResultStatus.Successful) {
					if (data.ResultObject != null) {
						//To show catalogue description
						var StrCatalogueDesc = "";
						$.each(data.ResultObject.CatalogueList, function (index, Cataloguedata) {
							StrCatalogueDesc += Cataloguedata + "<br/>";
						});
						$('#divCatalogueText').html(StrCatalogueDesc);
						var divPurchaseChannels = $('.divPurchaseChannels');

						if (data.ResultObject.ChannelList.length != 0) {
							var ChannelSubscriptionsLen = data.ResultObject.ChannelList.length;
							//do not change "channel-widget-btn" class as it is using for further functionality
							if (ChannelSubscriptionsLen != 0) {
								var ChannelSubscriptions = data.ResultObject.ChannelList;
								var strVideoblock = "";
								for (var varcnt = 0; varcnt < ChannelSubscriptionsLen; varcnt++) {
									//         create channel block

                                strVideoblock += '<div  class="channel-widget-container col-md-3 col-sm-4 no-padding">';
                                strVideoblock += '<div class="channel-widget-border">';
                                strVideoblock += '<div class="channel-widget-header">';
                                if (parseBool(ChannelSubscriptions[varcnt].ChannelIconShowOnPortal) == true) {
                                    strVideoblock += '<img src="' + ChannelSubscriptions[varcnt].IconImage + '"height="30px"/>';
                                }
                                strVideoblock += " " + ChannelSubscriptions[varcnt].ChannelName + ' </div>';

									//  <!-- Create Channel Block & assign unique Id to them-- >
									strVideoblock += '<div id="ChannelBlock' + varcnt + '"  class="btn-group channel-widget-price-container btn-channel-widget" data-toggle="buttons">';

									//  <!-- Full Price-- >
									strVideoblock += '<label id="ChannelBlock' + varcnt + 'btn1" ChannelId="' + ChannelSubscriptions[varcnt].ChannelId + '"  Price="' + ChannelSubscriptions[varcnt].CombinePrice + '"  ProductCode="' + ChannelSubscriptions[varcnt].CombineProdCode + '" class="btn channel-widget-full-price channel-widget-btn All" title="(videos from 2013 and backwards , Videos from 2013 and onwards)" onclick="selectChannelBlock(this);" data-channelblock="ChannelBlock' + varcnt + '" data-val="channelCommunication">';

									strVideoblock += 'All £' + ChannelSubscriptions[varcnt].CombinePrice + '</label>';
									strVideoblock += '<div style="text-align:center;font-weight:bold;">or</div>';
									strVideoblock += '<label id="ChannelBlock' + varcnt + 'btn2" ChannelId="' + ChannelSubscriptions[varcnt].ChannelId + '"  Price="' + ChannelSubscriptions[varcnt].ArchivePrice + '"  ProductCode="' + ChannelSubscriptions[varcnt].ArchiveProdCode + '" class="btn channel-widget-part-price channel-widget-btn Back" title="(videos from 2013 and backwards)"   onclick="selectChannelBlock(this);" data-channelblock="ChannelBlock' + varcnt + '" data-val="channelCommunication">';
									//  <!-- Archive Price-- >
									strVideoblock += 'Archive £' + ChannelSubscriptions[varcnt].ArchivePrice + ' </label>';
									strVideoblock += '<label id="ChannelBlock' + varcnt + 'btn3" ChannelId="' + ChannelSubscriptions[varcnt].ChannelId + '"  Price="' + ChannelSubscriptions[varcnt].FrontPrice + '"  ProductCode="' + ChannelSubscriptions[varcnt].FrontProdCode + '" class="btn channel-widget-part-price channel-widget-btn Front" title="(Videos from 2013 and onwards)" onclick="selectChannelBlock(this);" data-channelblock="ChannelBlock' + varcnt + '" data-val="channelCommunication">';
									strVideoblock += 'Front  £' + ChannelSubscriptions[varcnt].FrontPrice + ' </label>';
									strVideoblock += '</div>';
									//<!--                Pricing Radio buttons End-->
									strVideoblock += '</div>';
									strVideoblock += ' </div>';
								}
							}
							$(divPurchaseChannels).html(strVideoblock);

							//to disable the catalogue in case of video specific channels
							if ((IsNullOrEmpty(sessionStorage.getItem("VideoId")) == false) && CallerPage == "BuyChannel") {
								$(".video-specific-channel-text").removeClass("display-none");
								$("#purchaseMessage").hide();
								if (!IsNullOrEmpty(data.ResultObject.CatalogueType)) {
									$(divPurchaseChannels).find('.' + data.ResultObject.CatalogueType).attr("disabled", "disabled");
								}
							}

							$("#spnTotal").html('Total : ' + '£' + parseFloat(SelectedBuyTotal).toString());
						}
						else { $(divPurchaseChannels).html("No Records found"); }
						//To bind configuration values
						if (data.ResultObject.ChannelConfiguration.length != 0) {
							var ChannelConfiguration = data.ResultObject.ChannelConfiguration;
							for (var varcnt = 0; varcnt < data.ResultObject.ChannelConfiguration.length; varcnt++) {
								if (ChannelConfiguration[varcnt].Key.toLowerCase() == "channeloffer") {
									BuyMoreTotal = parseFloat(ChannelConfiguration[varcnt].Value);
									MsgForBuyMore = ChannelConfiguration[varcnt].Description;
								}
								if (ChannelConfiguration[varcnt].Key.toLowerCase() == "membershipoffer") {
									MemberShipPage = ChannelConfiguration[varcnt].Value;
								}
								if (ChannelConfiguration[varcnt].Key.toLowerCase() == "buychannelstext") {
									$("#purchaseMessage").text(ChannelConfiguration[varcnt].Value);
								}
							}
						}
						//To disable already Purchased product .execute only when user is logged in
						if (data.ResultObject.PurchasedProduct.length != 0) {
							var ids = data.ResultObject.PurchasedProduct;
							var lis = $(divPurchaseChannels).find(".channel-widget-btn");

							lis.filter(function () {
								if ($.inArray($(this).attr('ProductCode'), ids) !== -1) {
									//If 'All' catalogue is disabled then disable other two
									if ($(this).hasClass("All")) {
										$(".divPurchaseChannels").find("[data-channelblock=" + $(this).attr('data-channelblock') + "]").addClass('disabled');
										$(".divPurchaseChannels").find("[data-channelblock=" + $(this).attr('data-channelblock') + "]").attr("disabled", "disabled");
									}
									else {
										$(this).addClass('disabled');
										$(this).attr("disabled", "disabled");
									}
									//If Front & Back catalogues are disabled then disable all.
									//If more than one catalogue is disabled then disable all.
									if ($(".divPurchaseChannels").find("#" + $(this).attr('data-channelblock')).find(".disabled").length > 1) {
										$(".divPurchaseChannels").find("[data-channelblock=" + $(this).attr('data-channelblock') + "]").addClass('disabled');
										$(".divPurchaseChannels").find("[data-channelblock=" + $(this).attr('data-channelblock') + "]").attr("disabled", "disabled");
									}
								}
							})
						}
						//To  show seleted value in case of Renew & Buy channel from Video Page
						if (!IsNullOrEmpty(sessionStorage.getItem("SelectedProductId"))) {
							showSelectedProduct(sessionStorage.getItem("SelectedProductId"));
							sessionStorage.removeItem("SelectedProductId");
						}
					}
					else {
						Spinner.Stop();
						var messageViewModel = new MessageViewModel();
						messageViewModel.CreateErrorMessage(data.Message);
						messageViewModel.ShowOverLay();
					}
					if (!WebService.DisableGA) {
						storeurlDetailsInGA('SubscriptionMatrix');
					}
				}
				else {
					var IndividualUserType = data.ResultObject != null ? data.ResultObject.IndividualUserType : "";
					if (!parseBool(localStorage.getItem("IsIndividualUser")) || (IndividualUserType.toLowerCase() != "registered")) {
						BrowserStorage.setRedireceLocation(Application.BaseURL);
						RouteProvider.config(Application.Home.BaseURL);
					}
					var messageViewModel = new MessageViewModel();
					messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
					messageViewModel.ShowOverLay();
				}
			},
			function (data) {
				var messageViewModel = new MessageViewModel();
				messageViewModel.CreateErrorMessage(data);
				messageViewModel.ShowOverLay();
			}, JSON.stringify(object.Data));
	},

	CallAddressPage: function (currentRouteSetting, routeProvider, CallerPage) {
		sessionStorage.setItem("ProductId", "");
		var strProductCodeList = "";
		var divPurchaseChannels = $(".divPurchaseChannels");
		if ($(divPurchaseChannels).find(".channel-widget-btn-selected").length != 0) {
			$(divPurchaseChannels).find(".channel-widget-btn-selected").each(function (i) {
				strProductCodeList += $(this).attr('ProductCode') + ",";
			});
			if (strProductCodeList != "") {
				strProductCodeList = strProductCodeList.slice(0, -1);
			}

			sessionStorage.setItem("ProductId", strProductCodeList);
			sessionStorage.setItem("Type", "channel");
			sessionStorage.setItem("OrderId", "");
			sessionStorage.setItem("OrderCode", "");

			if (IsNullOrEmpty(sessionStorage.getItem("ProductId"))) {
				var messageViewModel = new MessageViewModel();
				messageViewModel.CreateInfoMessage("Please select channel.", "overlayId", "okButtonId");
				messageViewModel.ShowOverLay();
			}
			else {
				var object = {
					Data: {
						"logonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
						"ProductId": IsNullOrEmpty(sessionStorage.getItem("ProductId")) ? "" : sessionStorage.getItem("ProductId"),
						"Type": IsNullOrEmpty(sessionStorage.getItem("Type")) ? "" : sessionStorage.getItem("Type")
					}
				};

				Repository.LoadDataJSON(WebService.BaseURL + 'Transactions/WebPortalTransaction.svc/CheckUserIsAllowedToBuyProduct',
					function (data, status, headers, config) {
						if (ResultStatus.Successful == data.LoginStatus) {
							if (data.ResultObject != null) {
								if (ResultStatus.Successful == data.Status) {
									//location.href = "?" + Application.Payment.BaseURL;
									routeProvider.config(Application.Payment.BaseURL);
								}
								else {
									_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
									_this.MessageViewModel.ShowOverLay();
								}
							}
						}
						else {
							_this.MessageViewModel.CreateConfirmationMessageWithOKCancelWithTitle(data.Message, "overlayId", "LoginButtonId", "RegisterButtonId", 'Login', 'Register', function () {
								$("#LoginButtonId").unbind();
								$("#LoginButtonId").bind("click", function (e) {
									sessionStorage.setItem("RedirectLocation", window.location.href);
									sessionStorage.setItem("RedirectFrom", window.location.href);
									sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);

									location.href = "view/" + Application.Login.BaseURL;
								});

								$("#RegisterButtonId").unbind();
								$("#RegisterButtonId").bind("click", function (e) {
									sessionStorage.setItem("RedirectLocation", window.location.href);
									sessionStorage.setItem("RedirectFrom", window.location.href);
									sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);
									policyLogin(helloNetwork.adB2CSignInSignUp, loginDisplayType.Page);
								});
							});
							_this.MessageViewModel.ShowOverLay();
						}
					},
					function (data, status, headers, config) {
						Spinner.Stop();
						_this.MessageViewModel.CreateErrorMessage(data);
						_this.MessageViewModel.ShowOverLay();
					}, JSON.stringify(object.Data));
			}
		}
		else {
			var messageViewModel = new MessageViewModel();
			messageViewModel.CreateWarningMessage("Please select channel.", "overlayId", "okButtonId");
			messageViewModel.ShowOverLay();
		}
	},

	CallAddressPageForVideo: function () {
		if (!IsNullOrEmpty(sessionStorage.getItem("VideoId"))) {
			var subscriptionFilter = {
				lastRouteName: '',
				DisplayVideoDetails: 0,
				EventId: 0,
				VideoNo: 0,
				SeriesId: 0
			};
			subscriptionFilter.lastRouteName = $(".btnCheckOutRedirect").attr("data-lastRouteName");
			subscriptionFilter.DisplayVideoDetails = $(".btnCheckOutRedirect").attr("data-displayvideodetails");
			subscriptionFilter.EventId = $(".btnCheckOutRedirect").attr("data-eventId");
			subscriptionFilter.VideoNo = $(".btnCheckOutRedirect").attr("data-videono");
			subscriptionFilter.SeriesId = $(".btnCheckOutRedirect").attr("data-seriesid");

			sessionStorage.setItem("subscriptionFilter", JSON.stringify(subscriptionFilter));
			sessionStorage.setItem("ProductId", sessionStorage.getItem("VideoId"));
			sessionStorage.setItem("Type", "video");
			sessionStorage.setItem("OrderId", "");
			sessionStorage.setItem("OrderCode", "");

			var object = {
				Data: {
					"logonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
					"ProductId": IsNullOrEmpty(sessionStorage.getItem("ProductId")) ? "" : sessionStorage.getItem("ProductId"),
					"Type": IsNullOrEmpty(sessionStorage.getItem("Type")) ? "" : sessionStorage.getItem("Type")
				}
			};

			Repository.LoadDataJSON(WebService.BaseURL + 'Transactions/WebPortalTransaction.svc/CheckUserIsAllowedToBuyProduct',
				function (data, status, headers, config) {
					if (ResultStatus.Successful == data.LoginStatus) {
						if (data.ResultObject != null) {
							if (ResultStatus.Successful == data.Status) {
								$(".btnCheckOutRedirect").click();
							}
							else if (data.Status == ResultStatus.Failed) {
								_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
								_this.MessageViewModel.ShowOverLay();
							}
						}
					}
					else {
						_this.MessageViewModel.CreateConfirmationMessageWithOKCancelWithTitle(data.Message, "overlayId", "LoginButtonId", "RegisterButtonId", 'Login', 'Register', function () {
							$("#LoginButtonId").unbind();
							$("#LoginButtonId").bind("click", function (e) {
								sessionStorage.setItem("withindex", -1);
								sessionStorage.setItem("RedirectLocation", window.location.href);
								sessionStorage.setItem("RedirectFrom", window.location.href);
								sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);
								location.href = "view/" + Application.Login.BaseURL;
							});

							$("#RegisterButtonId").unbind();
							$("#RegisterButtonId").bind("click", function (e) {
								sessionStorage.setItem("RedirectLocation", window.location.href);
								sessionStorage.setItem("RedirectFrom", window.location.href);
								sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);
								policyLogin(helloNetwork.adB2CSignInSignUp, loginDisplayType.Page);
							});
						});
						_this.MessageViewModel.ShowOverLay();
					}
				},
				function (data, status, headers, config) {
					Spinner.Stop();
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		}
		else {
			var messageViewModel = new MessageViewModel();
			messageViewModel.CreateWarningMessage("Please select video.", "overlayId", "okButtonId");
			messageViewModel.ShowOverLay();
		}
	},
	redirectMembershipPage: function () {
		if (MemberShipPage != "") {
			url = $.trim(MemberShipPage);
			var pattern = /^((http|https|ftp):\/\/)/;
			if (!pattern.test(url) && url != "") {
				url = "http://" + url;
			}
			if (url != "") {
				window.open(url, '_blank');
			}
		}
	},
	GotoHomePage: function () {
		location.href = "?" + Application.Root.BaseURL;
	},

	CallAddressPageForEvent: function () {
		if (!IsNullOrEmpty(sessionStorage.getItem("EventId"))) {
			var subscriptionFilter = {
				lastRouteName: '',
				DisplayVideoDetails: 0,
				EventId: 0,
				VideoNo: 0,
				SeriesId: 0
			};
			subscriptionFilter.lastRouteName = $(".btnEventCheckOutRedirect").attr("data-lastRouteName");
			subscriptionFilter.DisplayVideoDetails = $(".btnEventCheckOutRedirect").attr("data-displayvideodetails");
			subscriptionFilter.EventId = $(".btnEventCheckOutRedirect").attr("data-eventId");
			subscriptionFilter.VideoNo = $(".btnEventCheckOutRedirect").attr("data-videono");
			subscriptionFilter.SeriesId = $(".btnEventCheckOutRedirect").attr("data-seriesid");

			sessionStorage.setItem("subscriptionFilter", JSON.stringify(subscriptionFilter));
			sessionStorage.setItem("ProductId", sessionStorage.getItem("EventId"));
			sessionStorage.setItem("Type", "event");
			sessionStorage.setItem("OrderId", "");
			sessionStorage.setItem("OrderCode", "");

			var object = {
				Data: {
					"logonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
					"ProductId": IsNullOrEmpty(sessionStorage.getItem("ProductId")) ? "" : sessionStorage.getItem("ProductId"),
					"Type": IsNullOrEmpty(sessionStorage.getItem("Type")) ? "" : sessionStorage.getItem("Type")
				}
			};

			Repository.LoadDataJSON(WebService.BaseURL + 'Transactions/WebPortalTransaction.svc/CheckUserIsAllowedToBuyProduct',
				function (data, status, headers, config) {
					if (ResultStatus.Successful == data.LoginStatus) {
						if (data.ResultObject != null) {
							if (ResultStatus.Successful == data.Status) {
								$(".btnEventCheckOutRedirect").click();
							}
							else if (data.Status == ResultStatus.Failed) {
								_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
								_this.MessageViewModel.ShowOverLay();
							}
						}
					}
					else {
						_this.MessageViewModel.CreateConfirmationMessageWithOKCancelWithTitle(data.Message, "overlayId", "LoginButtonId", "RegisterButtonId", 'Login', 'Register', function () {
							$("#LoginButtonId").unbind();
							$("#LoginButtonId").bind("click", function (e) {
								sessionStorage.setItem("withindex", -1);
								sessionStorage.setItem("RedirectLocation", window.location.href);
								sessionStorage.setItem("RedirectFrom", window.location.href);
								sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);
								location.href = "view/" + Application.Login.BaseURL;
							});

							$("#RegisterButtonId").unbind();
							$("#RegisterButtonId").bind("click", function (e) {
								//sessionStorage.setItem("withindex", -1);
								//BrowserStorage.setRedireceLocation(Application.Address.BaseURL);
								//BrowserStorage.setRedireceFrom(Application.Video.BaseURL);
								//location.href = "view/" + Application.Login.BaseURL;
								sessionStorage.setItem("withindex", -1);
								sessionStorage.setItem("RedirectLocation", window.location.href);
								sessionStorage.setItem("RedirectFrom", window.location.href);
								sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);
								policyLogin(helloNetwork.adB2CSignInSignUp, loginDisplayType.Page);
							});
						});
						_this.MessageViewModel.ShowOverLay();
					}
				},
				function (data, status, headers, config) {
					Spinner.Stop();
					_this.MessageViewModel.CreateErrorMessage(data);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		}
		else {
			var messageViewModel = new MessageViewModel();
			messageViewModel.CreateWarningMessage("Please select event.", "overlayId", "okButtonId");
			messageViewModel.ShowOverLay();
		}
	}
};

function showSelectedProduct(SelectedProduct) {
	var SelectedIds = SelectedProduct.split(',');
	var CatalogueArray = $(".divPurchaseChannels").find(".channel-widget-btn");
	CatalogueArray.filter(function () {
		if ($.inArray($(this).attr('ProductCode'), SelectedIds) !== -1) {
			selectChannelBlock(this);
		}
	})
}
function selectChannelBlock(childElement) {
	//get Clicked element id
	var childElementId = $(childElement).attr('id');
	//get Parent Element of Clicked element
	var parentElement = $(childElement).parent();

	$($(parentElement).find(".channel-widget-btn")).each(function (i) {
		if ($(this).hasClass('channel-widget-btn-selected')) {
			SelectedBuyTotal = parseFloat(SelectedBuyTotal) - parseFloat($(this).attr('Price'));
		}
		if ($(this).attr('id') != childElementId || $(this).hasClass('channel-widget-btn-selected')) {
			$(this).removeClass('channel-widget-btn-selected');
			// PurchasedChannelList.splice($.inArray(ChannelObj, PurchasedChannelList), 1);
		}
		else {
			$(this).addClass('channel-widget-btn-selected');
			SelectedBuyTotal = parseFloat(SelectedBuyTotal) + parseFloat($(this).attr('Price'));
		}
	});

	if (!isNaN(SelectedBuyTotal)) {
		SelectedBuyTotal = SelectedBuyTotal.toFixed(2);
	}
	//  $(".spntotalOfPurchasedChannel").text("£ " + parseFloat(SelectedBuyTotal).toString());
	$("#spnTotal").html('Total : ' + '£' + parseFloat(SelectedBuyTotal).toString());
	// hide  div if no channel block is selected.
	parseFloat(SelectedBuyTotal) > 0 ? $(".purchase-final-price-div-container").show() : $(".purchase-final-price-div-container").hide();

	if (parseFloat(SelectedBuyTotal) >= parseFloat(BuyMoreTotal)) {
		$("#divBuyMore").show();
		$("#divSubscription_message").html("<span style='line-height: 23px;font-family:sans-serif; font-size: 14px;'>" + MsgForBuyMore.toString() + '</span>');
	}
	else {
		$("#divBuyMore").hide();
		$("#divSubscription_message").text("");
	}
}

var SearchData = {};
var DefaultDisplayPage = 3;
this.CurrentSearchVideoDetail = {};
var SearchResultRepository = {
    previousValue: 1,
    MessageViewModel: new MessageViewModel(),
    MenuMessageId: 'message',
    RouteProvider: null,
    RouteCurrentContext: null,
    CurrentRouteSetting: null,
    ByTabClick: false,


    SearchResult: function (jsonData, currentRouteSetting, routeProvider, routeCurrentContext) {

        var _this = this;
        sessionStorage.setItem("byTabClick", _this.ByTabClick);
        _this.RouteProvider = routeProvider;
        _this.RouteCurrentContext = routeCurrentContext;
        _this.CurrentRouteSetting = currentRouteSetting;
        var object = {
            Data: { "contentRequest": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'ContentManagement/ContentAccess.svc/SearchResult',
          function success(data) {

              var XMLString = (data.ResultObject.XMLString == null) ? "" : data.ResultObject.XMLString;
              if (sessionStorage.getItem("RedirectFrom") != Application.SearchResult.BaseURL) {
                  $.ajax({
                      url: currentRouteSetting.configuration.templateUrl,
                      success: function (data) {
                          $('#viewContent').html(data);
                          routeProvider.bindRoutes();
                          ManageResourceTab();
                          $('#textSearch').html(jsonData.SearchTerm);
                          if (IsNullOrEmpty($('.pagebox').val())) {
                              $('.pagebox').val(1);
                          }
                          if ($('#chkMySubscription').length > 0) {
                              _this.PageNumberKeyUp();
                              _this.PreviousClick();
                              _this.ForworkClick();
                              _this.LastClick();
                              _this.FirstClick();
                              _this.GoClick();
                              _this.MySubscriptionChange();
                              _this.SortByChange();
                              _this.PageSizeChange();
                              _this.TabClick();
                              if (IsNullOrEmpty(sessionStorage.getItem("LogonId"))) {
                                  $('#chkMySubscription').attr('disabled', 'disabled');
                              }
                              else {
                                  $('#chkMySubscription').removeAttr('disabled');
                              }
                          }

                          _this.XMLParse(XMLString, jsonData.SearchCategory);
                          _this.SetSessionValueToControl();
                          _this.RouteProvider.bindInnerRoutes();
                      }
                  });
                  sessionStorage.setItem("RedirectFrom", Application.SearchResult.BaseURL);
              }
              else {
                  _this.XMLParse(XMLString, jsonData.SearchCategory);
                  $('#textSearch').html(jsonData.SearchTerm);
                  _this.RouteProvider.bindInnerRoutes();
              }
          },
          function error(data) {
          }, JSON.stringify(object.Data)
          );
    },
    SearchResult1: function (searchInput, currentRouteSetting, routeProvider, routeCurrentContext, eviSearchPagination) {

        var _this = this;
        _this.RouteProvider = routeProvider;
        _this.RouteCurrentContext = routeCurrentContext;
        _this.CurrentRouteSetting = currentRouteSetting;
        var tempChannelId = searchInput.ChannelId;
        if (eviSearchPagination != '') {
            searchInput.eviSearchRoute = eviSearchPagination;
        }
        else
        {
            searchInput.eviSearchRoute = false;
        }
        //  $("#hdnCurrentPage").val((sessionStorage.getItem("CurrentPageNumber")));


        //   _this.channelName = channelName;
        var object = {
            Data: {
                "searchInput": searchInput

            }
        };






        var searchkeyword = '';
        if (searchInput.SearchText == '') {
            searchkeyword = searchInput.VideoType + " Videos";

        }
        else {
            searchkeyword = searchInput.SearchText;
        }

        $.ajax({
            url: currentRouteSetting.configuration.templateUrl,
            async: false,
            success: function (data) {

                //    $("#hdnCurrentPage").val((sessionStorage.getItem("CurrentPageNumber")));
                $('#viewContent').html(data);
                if (!routeCurrentContext) {
                    if (searchInput.SearchText != "" && searchInput.VideoType == "") {
                        if ($(window).width() < 992) {
                            $("#mobsearchtxtbox").val(searchInput.SearchText);

                        }
                        else {
                            if (searchInput.SearchCategory == "Date") {
                                var monthNames = ["January", "February", "March", "April", "May", "June",
                                      "July", "August", "September", "October", "November", "December"];

                                var newDate = new Date(searchInput.SearchText);
                                var formattedDate = monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear();


                                $("#searchtextbox").val(formattedDate);


                            }
                            else {


                                $("#searchtextbox").val(searchInput.SearchText);
                            }
                        }
                    }
                }


                if (searchInput.SortBy == "CreatedDes") {
                    $(".searchResultdropdown-text").html("Created Date (Newest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "CreatedDes");

                }

                if (searchInput.SortBy == "CreatedAsc") {
                    $(".searchResultdropdown-text").html("Created Date (Oldest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "CreatedAsc");

                }

                if (searchInput.SortBy == "PublishedDes") {
                    $(".searchResultdropdown-text").html("Published Date (Newest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "PublishedDes");

                }

                if (searchInput.SortBy == "PublishedAsc") {
                    $(".searchResultdropdown-text").html("Published Date (Oldest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "PublishedAsc");

                }

                if (searchInput.SortBy == "Recent") {
                    $(".searchResultdropdown-text").html("Date (Newest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "Recent");

                }

                if (searchInput.SortBy == "Popular") {
                    $(".searchResultdropdown-text").html("Popularity");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "Popular");
                }

                if (searchInput.SortBy == "Relevance") {
                    $(".searchResultdropdown-text").html("Relevance");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "Relevance");
                }
                if (searchInput.SortBy == "Oldest") {
                    $(".searchResultdropdown-text").html("Date (oldest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "Oldest");

                }

                if (searchInput.SortBy == "TitleAscending") {
                    $(".searchResultdropdown-text").html("Title (A-Z)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "TitleAscending");

                }


                if (searchInput.SortBy == "TitleDescending") {
                    $(".searchResultdropdown-text").html("Title (Z-A)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "TitleDescending");
                }

                if (searchInput.SortBy == "Like") {
                    $(".searchResultdropdown-text").html("Like");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "Like");
                }

                $('#search_param').val(searchInput.SearchCategory);
                $('#Search_button').html(searchInput.SearchCategory + '<svg version="1.1" class="searchArrow" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 16.8 21" xml:space="preserve"><path id="Master_arrow_small" d="M2.2,10.4L6.8,15V0H10v15l4.6-4.6l2.2,2.2L8.4,21L0,12.6L2.2,10.4z" /></svg>');
                $('#Mobile-btn').html(searchInput.SearchCategory + '<svg version="1.1" class="searchArrowMob" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 16.8 21" xml:space="preserve"><path id="Master_arrow_small" d="M2.2,10.4L6.8,15V0H10v15l4.6-4.6l2.2,2.2L8.4,21L0,12.6L2.2,10.4z" /></svg>');
                routeProvider.bindInnerRoutes();
                //_this.GetSearchOutput(currentRouteSetting, routeProvider, routeCurrentContext);
            }
        });
        //routeProvider.bindInnerRoutes();
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetSearchResult',
           function (data, status, headers, config) {
               if (ResultStatus.Successful == data.Status && data.ResultObject) {
                   if (data.ResultObject == null) {
                       $(".result").html("<p>No result found</p>");
                       $(".pagination_btn").attr("disabled", "disabled");
                       $('#SearchResult').html("");
                       if (searchkeyword == "**") {
                           searchkeyword = searchInput.VideoType;
                       }

                       sessionStorage.setItem("SeriesID", data.ResultObject.SeriesID);

                       sessionStorage.setItem("EventID", data.ResultObject.EventID);

                       if (searchInput.VideoType == "") {
                           sessionStorage.setItem("ChannelName", "");
                       }

                       var searchKey = searchkeyword;

                       var channelName = sessionStorage.getItem("ChannelName");
                       if (channelName == "" || channelName == undefined || channelName == "undefined") {

                           if (searchInput.VideoType == "") {

                               if ($(window).width() < 992) {
                                   if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                                       $(".search-title-new").html("<span>EVI transcript search - " + $("#mobsearchtxtbox").val() + " </span>");
                                   else
                                       $(".search-title-new").html("<span>" + $("#mobsearchtxtbox").val() + " </span>");
                                   //searchTerm = $("#mobsearchtxtbox").val();
                               }
                               else {
                                   if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                                       $(".search-title-new").html("<span>EVI transcript search - " + $("#searchtextbox").val() + " </span>");
                                   else
                                       $(".search-title-new").html("<span>" + $("#searchtextbox").val() + " </span>");
                               }
                           }

                           else {

                               if (searchInput.VideoType == "Popular") {
                                   $(".search-title-new").html("<span>Most " + searchKey.replace("Popular", "Viewed") + " Videos  </span>");
                               }
                               else if (searchInput.VideoType == "Latest") {
                                   $(".search-title-new").html("<span>Latest Videos  </span>");
                               }
                               else if (searchInput.VideoType == "Forthcoming") {
                                   $(".search-title-new").html("<span>Coming up Videos </span>");
                               }
                               else {
                                   $(".search-title-new").html("<span>" + searchKey + " Videos  </span>");
                               }
                           }
                       }
                       else {

                           if (searchKey == "Popular") {
                               $(".search-title-new").html("<span>Most " + searchKey.replace("Popular", "Viewed") + " Videos  in " + channelName + "</span>");
                           }
                           
                           else {
                               $(".search-title-new").html("<span>" + searchKey + " Videos  in " + channelName + "</span>");

                           }
                       }

                       $("#mobileresult").html("<p class=\"float-left\"> No result found</p>")
                       $(".pagination_btn").attr("disabled", "disabled");
                       var width = $(window).width();
                       if (width <= 992) {

                           //  $(".pagination-panel").hide();
                       }
                       else {
                           //   $(".pagination-panel").show();
                       }

                       $(".pageno").html("<p></p>");
                       $("#footerpaging").hide();
                   }
                   else {

                       sessionStorage.setItem("SeriesId", data.ResultObject.SeriesID);
                       sessionStorage.setItem("EventID", data.ResultObject.EventID);

                       if (searchkeyword == "**") {
                           searchkeyword = searchInput.VideoType;

                           if (searchInput.VideoType == 'Forthcoming')
                               searchkeyword = 'Coming up';

                       }
                       var Result = data.ResultObject;

                       _this.LoadChannels(Result.Facets, searchInput.Facets);
                       //   totalRecords = searchdata.Videos.TotalRecord;
                       var videothumbnail = '';
                       var searchHTML = ''
                       var VideosPerPage = 20;
                       SearchData = {
                           SearchVideos: Result.SearchVidoes,
                           TotalRecords: Result.TotalRecords,
                           DisplayPages: Result.TotalRecords / VideosPerPage
                       }

                       if (SearchData.TotalRecords <= 20 && SearchData.TotalRecords >= 1) {
                           DefaultDisplayPage = 1;
                       }
                       else if (SearchData.TotalRecords > 20 && SearchData.TotalRecords <= 40) {
                           DefaultDisplayPage = 2;
                       }
                       else if (SearchData.TotalRecords > 40) {
                           DefaultDisplayPage = 3;
                       }
                       else if (SearchData.TotalRecords == 0) {

                           $(".result").html("<p>No result found</p>");
                           $(".pagination_btn").attr("disabled", "disabled");
                           if (searchInput.VideoType == "") {
                               sessionStorage.setItem("ChannelName", "");
                           }

                           var searchKeyName = searchkeyword;

                           var channelName = sessionStorage.getItem("ChannelName");
                           if (channelName == "" || channelName == undefined || channelName == "undefined") {

                               if (searchInput.VideoType == "") {
                                   if ($(window).width() < 992) {
                                       if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                                           $(".search-title-new").html("<span>EVI transcript search - " + $("#mobsearchtxtbox").val() + " </span>");
                                       else
                                           $(".search-title-new").html("<span>" + $("#mobsearchtxtbox").val() + " </span>");

                                       //searchTerm = $("#mobsearchtxtbox").val();
                                   }
                                   else {
                                       if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                                           $(".search-title-new").html("<span>EVI transcript search - " + $("#searchtextbox").val() + " </span>");
                                       else
                                           $(".search-title-new").html("<span>" + $("#searchtextbox").val() + " </span>");
                                   }
                               }

                               else {

                                   if (searchInput.VideoType == "Popular") {
                                       $(".search-title-new").html("<span >Most " + searchKeyName.replace("Popular", "Viewed") + " Videos  </span>");
                                   }
                                   else if (searchInput.VideoType == "Latest") {
                                       $(".search-title-new").html("<span>Latest Videos  </span>");
                                   }
                                   else if (searchInput.VideoType == "Forthcoming") {
                                       $(".search-title-new").html("<span>Coming up Videos </span>");
                                   }
                                   else {
                                       $(".search-title-new").html("<span>" + searchKeyName + " Videos  </span>");
                                   }
                               }
                           }
                           else {
                               if (searchKeyName == "Popular") {
                                   $(".search-title-new").html("<span>Most " + searchKeyName.replace("Popular", "Viewed") + " Videos  in " + channelName + "</span>");
                               }
                               else {
                                   $(".search-title-new").html("<span>" + searchKeyName + " Videos  in " + channelName + "</span>");
                               }
                           }
                           $("#mobileresult").html("<p class=\"float-left\"> No result found</p>");
                           $(".pagination_btn").attr("disabled", "disabled");
                           $('#SearchResult').html("");
                       }
                       var width = $(window).width();
                       if (width <= 992) {
                       }
                       $(".pageno").html("<p></p>");
                       $("#footerpaging").hide();
                   }

                   if (SearchData.SearchVideos != null) {

                       if (SearchData.SearchVideos.length != 0) {

                           if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                               $(".search-title-new").html("<span>EVI transcript search - " + $("#mobsearchtxtbox").val() + " </span>");
                           else
                               $(".search-title-new").html("<span>" + $("#mobsearchtxtbox").val() + " </span>");

                           var SearchResultctrl = $("#SearchResult");
                           var SearchText = searchInput.SearchText;
                           if ($('#search_param').val() == 'Date') {
                               SearchText = $("#ui-datepicker-div .ui-datepicker-month :selected").text() + " " + $("#ui-datepicker-div .ui-datepicker-year :selected").text();
                           }
                           
                           $.each(SearchData.SearchVideos, function (index, data) {
                               var time = new Date();
                               if (data.HasPromo) {
                                   searchHTML = searchVideos(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage, data.HasLock, data.ChannelId, data.ChannelColor, data.ChannelMappingDetail, data.IsJisc, data.SubscriptionType, data.Duration, data.IsEvent, data.EventId, data.LikesCount, data.DisLikesCount, data.ViewsCount, data.VideoCreatedDate, data.IsSeries, data.EventName, data.ShortDescription, data.IsHideRecord, data.EventStatus, data.PublishStartDate, data.PublishStartTime, data.PublishExpiryDate, data.PublishExpiryTime, data.SeriesDetailsList, data.FinalStartDateTime, data.DisplayCPD, data.CPDLogo, data.VideoAbstract, eviSearchPagination, data.TranscriptVideoCount);
                               }
                               else
                               {
                                   searchHTML = searchVideos(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.ChannelColor, data.ChannelMappingDetail, data.IsJisc, data.SubscriptionType, data.Duration, data.IsEvent, data.EventId, data.LikesCount, data.DisLikesCount, data.ViewsCount, data.VideoCreatedDate, data.IsSeries, data.EventName, data.ShortDescription, data.IsHideRecord, data.EventStatus, data.PublishStartDate, data.PublishStartTime, data.PublishExpiryDate, data.PublishExpiryTime, data.SeriesDetailsList, data.FinalStartDateTime, data.DisplayCPD, data.CPDLogo, data.VideoAbstract, eviSearchPagination, data.TranscriptVideoCount);
                               }
                                            
                               $(SearchResultctrl).append(searchHTML);
                               $(".highLightSearchTerm" + data.VideoNo + " *").highlight(SearchText, "searchword_highlight");
                           });
                           if (searchInput.VideoType == "") {
                               sessionStorage.setItem("ChannelName", "");
                           }


                           var searchValueKey = searchkeyword;

                           var channelName = sessionStorage.getItem("ChannelName");
                           if (channelName == "" || channelName == undefined || channelName == "undefined") {


                               if (searchInput.VideoType == "") {
                                   if ($(window).width() < 992) {
                                       if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                                           $(".search-title-new").html("<span>EVI transcript search - " + $("#mobsearchtxtbox").val() + " </span>");
                                       else
                                           $(".search-title-new").html("<span>" + $("#mobsearchtxtbox").val() + " </span>");
                                       //searchTerm = $("#mobsearchtxtbox").val();
                                   }
                                   else {
                                       if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                                           $(".search-title-new").html("<span>EVI transcript search - " + $("#searchtextbox").val() + " </span>");
                                       else
                                           $(".search-title-new").html("<span>" + $("#searchtextbox").val() + " </span>");
                                   }
                               }
                               else {

                                   if (searchInput.VideoType == "Popular") {
                                       $(".search-title-new").html("<span>Most " + searchValueKey.replace("Popular", "Viewed") + " Videos  </span>");
                                   }
                                   else if (searchInput.VideoType == "Latest") {
                                       $(".search-title-new").html("<span>Latest Videos  </span>");
                                   }
                                   else if (searchInput.VideoType == "Forthcoming") {
                                       $(".search-title-new").html("<span>Coming up Videos </span>");
                                   }
                                   else {
                                       $(".search-title-new").html("<span  >" + searchValueKey + " Videos  </span>");

                                   }
                               }
                           }
                           else {

                               if (searchValueKey == "Popular") {
                                   $(".search-title-new").html("<span>Most " + searchValueKey.replace("Popular", "Viewed") + " Videos  in " + channelName + "</span>");
                               }
                               else {
                                   $(".search-title-new").html("<span>" + searchValueKey + " Videos  in " + channelName + "</span>");

                               }
                           }

                           //var filtr = '<div class="clearfix"></div>';

                           //$('#searchText').append(filtr);

                           var facetString = "";

                           for (i = 0; i < searchInput.Facets.length; i++) {

                               var facet = searchInput.Facets[i];
                               var str = "<span class=\"search_facet_breadcrum font-size-12\">" + facet.Name +
                                                       "<i class=\"fa fa-times fa-lg closeFacet\" style=\"cursor:pointer;\" data-innerroutename=\"searchFacets\" data-hasIndex='true' data-facetType=\"" + facet.Type + "\" data-facetName=\"" + facet.Name +
                                                       "\" data-facetKey=\"" + facet.Key + "\"   data-facetSubType=\"" + facet.SubType + "\"          data-facetId=\"" + facet.Key + "\"></i></span>";

                               facetString += str;
                           }

                           if ($('.facetsPanel').find('input:checked').length <= 0) {
                               $('.reset').removeClass('visibleBtn');
                           }
                           if (searchInput.Facets.length > 0) {
                               $('.reset').addClass('visibleBtn');
                           }
                           if (searchInput.Facets.length == 0) {
                               $('.reset').removeClass('visibleBtn');
                           }
                           /*checking for the video type*/
                           if (searchInput.VideoType != "") {
                               //$("#searchedfor").addClass("resetbtn");
                               $("#hdnVideoType").val(searchInput.VideoType);
                               $('#SearchReset').attr("data-videotype", searchInput.VideoType);
                               $('#SearchResult1').attr("data-videotype", searchInput.VideoType);



                               if (tempChannelId === "undefined" || tempChannelId === undefined || tempChannelId === "") {
                                   tempChannelId = 0;
                               };
                               $('#SearchResult1').attr("data-channelid", tempChannelId)
                               $('#SearchReset').attr("data-channelid", tempChannelId)
                               $("#hdnChannelId").val(tempChannelId);
                           }

                           if (!IsNullOrEmpty(facetString)) {
                               $('#activefiltersearch').append("<div class='font-size-12 margin-top-10'>Active Filters</div><div class='margin-bottom-10 clearfix'>" + facetString + "</div>");
                           }

                           if (SearchData.TotalRecords == 1) {
                               $(".result").html("<p>" + SearchData.TotalRecords + " result found, </p>");
                               $("#mobileresult").html("<p class=\"float-left\">" + SearchData.TotalRecords + " result found, page 1 of " + Math.ceil(SearchData.DisplayPages) + " </p>")
                           } else {
                               $(".result").html("<p>" + SearchData.TotalRecords + " results found, </p>");
                               $("#mobileresult").html("<p class=\"float-left\">" + SearchData.TotalRecords + " results found, page 1 of " + Math.ceil(SearchData.DisplayPages) + " </p>")
                           }

                           $(".pageno").html("<p>page 1 of " + Math.ceil(SearchData.DisplayPages) + "</p>");

                           //$(".pageNavigation").remove('li');
                           //if ($(".pageNavigation").data('twbs-pagination')) {
                           //    $(".pageNavigation").data('twbs-pagination', undefined);
                           //} 
                           $("#footerpaging").show();
                           $(".pageNavigation").twbsPagination({
                               totalPages: Math.ceil(SearchData.DisplayPages),

                               visiblePages: DefaultDisplayPage,
                               first: "First",
                               last: "Last",
                               EnableRoute: true
                           });
                           showVideoDetails();
                           routeProvider.bindInnerRoutes();
                           if (!WebService.DisableGA) {

                               storeurlDetailsInGA('SearchResult');
                           }
                       }
                   }
               }


               else {
                   var messageViewModel = new MessageViewModel();
                   messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {

                   });
                   messageViewModel.ShowOverLay();
               }
           }, function (data, status, headers, config) {
               Spinner.Stop();
               var messageViewModel = new MessageViewModel();
               messageViewModel.CreateErrorMessage(data);
               messageViewModel.ShowOverLay();
           }, JSON.stringify(object.Data));

        if ($('#search_param').val() != 'Date') {
            $('#searchtextbox').datepicker('destroy')
                               .removeClass('hasDatepicker');
        }
    },


    PageSearch: function (searchInput, eviSearchPagination) {

        var _this = this;
        if (eviSearchPagination != '') {
            searchInput.eviSearchRoute = eviSearchPagination;
        }
        else
        {
            searchInput.eviSearchRoute = false;
        }
        var tempChannelId = searchInput.ChannelId;
        var object = {
            Data: { "searchInput": searchInput }
        };


        var searchkeyword = '';
        var seachTextOldVal = $("#searchtextbox").val();
        if (searchInput.SearchText == '') {
            searchkeyword = searchInput.VideoType + " Videos";
        }
        else {
            searchkeyword = searchInput.SearchText;
        }

        $.ajax({
            url: 'View/Search.html',
            async: false,
            success: function (data) {
                $('#viewContent').html(data);
                //  $('.page a').attr("data-hasIndex", "true");
                if (searchInput.SortBy == "CreatedDes") {
                    $(".searchResultdropdown-text").html("Created Date (Newest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "CreatedDes");

                }

                if (searchInput.SortBy == "CreatedAsc") {
                    $(".searchResultdropdown-text").html("Created Date (Oldest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "CreatedAsc");

                }

                if (searchInput.SortBy == "PublishedDes") {
                    $(".searchResultdropdown-text").html("Published Date (Newest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "PublishedDes");

                }

                if (searchInput.SortBy == "PublishedAsc") {
                    $(".searchResultdropdown-text").html("Published Date (Oldest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "PublishedAsc");

                }

                if (searchInput.SortBy == "Recent") {
                    $(".searchResultdropdown-text").html("Date (Newest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "Recent");

                }

                if (searchInput.SortBy == "Popular") {
                    $(".searchResultdropdown-text").html("Popularity");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "Popular");
                }

                if (searchInput.SortBy == "Relevance") {
                    $(".searchResultdropdown-text").html("Relevance");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "Relevance");
                }
                if (searchInput.SortBy == "Oldest") {
                    $(".searchResultdropdown-text").html("Date (oldest First)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "Oldest");

                }

                if (searchInput.SortBy == "TitleAscending") {
                    $(".searchResultdropdown-text").html("Title (A-Z)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "TitleAscending");
                }

                if (searchInput.SortBy == "TitleDescending") {
                    $(".searchResultdropdown-text").html("Title (Z-A)");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "TitleDescending");
                }

                if (searchInput.SortBy == "Like") {
                    $(".searchResultdropdown-text").html("Like");
                    $(".searchResultdropdown-text").attr("data-sorttypekey", "Like");
                }
				
				$('#search_param').val(searchInput.SearchCategory);
                $('#Search_button').html(searchInput.SearchCategory + '<svg version="1.1" class="searchArrow" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 16.8 21" xml:space="preserve"><path id="Master_arrow_small" d="M2.2,10.4L6.8,15V0H10v15l4.6-4.6l2.2,2.2L8.4,21L0,12.6L2.2,10.4z" /></svg>');
                $('#Mobile-btn').html(searchInput.SearchCategory + '<svg version="1.1" class="searchArrowMob" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 16.8 21" xml:space="preserve"><path id="Master_arrow_small" d="M2.2,10.4L6.8,15V0H10v15l4.6-4.6l2.2,2.2L8.4,21L0,12.6L2.2,10.4z" /></svg>');

            }
        });
		if ($(window).width() < 992) {
            if ($("#mobsearchtxtbox").val() == "") {
                $("#mobsearchtxtbox").val(searchInput.SearchText);
            }
        }
        else {
            if ($("#searchtextbox").val() == "") {
                if (searchInput.SearchCategory == "Date") {
                    var monthNames = ["January", "February", "March", "April", "May", "June",
                          "July", "August", "September", "October", "November", "December"];

                    var newDate = new Date(searchInput.SearchText);
                    var formattedDate = monthNames[newDate.getMonth()] + ' ' + newDate.getFullYear();


                    $("#searchtextbox").val(formattedDate);


                }
                else {


                    $("#searchtextbox").val(searchInput.SearchText);
                }
            }
        }
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetSearchResult',
           function (data, status, headers, config) {
               if (ResultStatus.Successful == data.Status && data.ResultObject) {
                   if (data.ResultObject == null) {
                       $(".result").html("<p>No result found</p>");
                       $(".pagination_btn").attr("disabled", "disabled");

                       if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                           $(".search-title-new").html("<span>EVI transcript search - " + seachTextOldVal + "</span>");
                       else
                           $(".search-title-new").html("<span>" + seachTextOldVal + "</span>");

                       $("#mobileresult").html("<p class=\"float-left\"> No result found</p>");
                       $(".pagination_btn").attr("disabled", "disabled");
                       $(".pageno").html("<p></p>");

                       sessionStorage.setItem("SeriesID", data.ResultObject.SeriesID);

                       sessionStorage.setItem("EventID", data.ResultObject.EventID);
                   }
                   else {
                       if ($(window).width() < 992) {
                           if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                               $(".search-title-new").html("<span>EVI transcript search - " + $("#mobsearchtxtbox").val() + " </span>");
                           else
                               $(".search-title-new").html("<span>" + $("#mobsearchtxtbox").val() + " </span>");
                           //searchTerm = $("#mobsearchtxtbox").val();
                       }
                       else {
                           if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                               $(".search-title-new").html("<span>EVI transcript search - " + seachTextOldVal + " </span>");
                           else
                               $(".search-title-new").html("<span>" + seachTextOldVal + " </span>");
                       }

                       sessionStorage.setItem("SeriesID", data.ResultObject.SeriesID);

                       sessionStorage.setItem("EventID", data.ResultObject.EventID);

                       var videothumbnail = '';
                       var searchHTML = ''
                       var VideosPerPage = 20;
                       var Result = data.ResultObject;
                       _this.LoadChannels(Result.Facets, searchInput.Facets);

                       var videothumbnail = '';
                       SearchData = {
                           SearchVideos: Result.SearchVidoes,
                           TotalRecords: Result.TotalRecords,
                           DisplayPages: Result.TotalRecords / VideosPerPage
                       }
                       if (SearchData.TotalRecords <= 20 && SearchData.TotalRecords >= 1) {
                           DefaultDisplayPage = 1;
                       }
                       else if (SearchData.TotalRecords > 20 && SearchData.TotalRecords <= 40) {
                           DefaultDisplayPage = 2;
                       }
                       else if (SearchData.TotalRecords > 40) {
                           DefaultDisplayPage = 3;
                       }
                       else if (SearchData.SearchVideos.length == 0) {
                           $(".result").html("<p>No result found</p>");
                           $(".pagination_btn").attr("disabled", "disabled");

                           if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                               $(".search-title-new").html("<span>EVI transcript search - " + seachTextOldVal + "</span>");
                           else
                               $(".search-title-new").html("<span>" + seachTextOldVal + "</span>");
                           $("#mobileresult").html("<p class=\"float-left\"> No result found</p>");
                           $(".pagination_btn").attr("disabled", "disabled");
                           $(".pageno").html("<p></p>");
                       }



                       if (SearchData.SearchVideos != null)
                       {
                           var SearchResultctrl = $('#SearchResult');
                           var SearchText = searchInput.SearchText;
                           if ($('#search_param').val() == 'Date') {
                               SearchText = $("#ui-datepicker-div .ui-datepicker-month :selected").text() + " " + $("#ui-datepicker-div .ui-datepicker-year :selected").text();
                           }
                           $.each(SearchData.SearchVideos, function (index, data) {
                               var time = new Date();
                               if (data.HasPromo) {
                                   searchHTML = searchVideos(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage, data.HasLock, data.ChannelId, data.ChannelColor, data.ChannelMappingDetail, data.IsJisc, data.SubscriptionType, data.Duration, data.IsEvent, data.EventId, data.LikesCount, data.DisLikesCount, data.ViewsCount, data.VideoCreatedDate, data.IsSeries, data.EventName, data.ShortDescription, data.IsHideRecord, data.EventStatus, data.PublishStartDate, data.PublishStartTime, data.PublishExpiryDate, data.PublishExpiryTime, data.SeriesDetailsList, data.FinalStartDateTime, data.DisplayCPD, data.CPDLogo, data.VideoAbstract, eviSearchPagination, data.TranscriptVideoCount);
                               }
                               else
                               {
                                   searchHTML = searchVideos(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.ChannelColor, data.ChannelMappingDetail, data.IsJisc, data.SubscriptionType, data.Duration, data.IsEvent, data.EventId, data.LikesCount, data.DisLikesCount, data.ViewsCount, data.VideoCreatedDate, data.IsSeries, data.EventName, data.ShortDescription, data.IsHideRecord, data.EventStatus, data.PublishStartDate, data.PublishStartTime, data.PublishExpiryDate, data.PublishExpiryTime, data.SeriesDetailsList, data.FinalStartDateTime, data.DisplayCPD, data.CPDLogo, data.VideoAbstract, eviSearchPagination, data.TranscriptVideoCount);
                               }
                               $(SearchResultctrl).append(searchHTML);
                               $(".highLightSearchTerm" + data.VideoNo + " *").highlight(SearchText, "searchword_highlight");
                           });
                       }
                       if (searchInput.VideoType == "") {
                           sessionStorage.setItem("ChannelName", "");
                       }
                       var channelName = sessionStorage.getItem("ChannelName");

                       if (channelName == "" || channelName == undefined || channelName == "undefined") {


                           if (searchInput.VideoType == "Popular") {


                               $(".search-title-new").html("<span> Most " + searchkeyword.replace("Popular", "Viewed") + " </span>");

                           }
                           else if (searchInput.VideoType == "Forthcoming") {


                               $(".search-title-new").html("<span> " + searchkeyword + " </span>");

                           }
                           else if (searchInput.VideoType == "Latest") {


                               $(".search-title-new").html("<span> " + searchkeyword + " </span>");

                           }

                           else {
                               if (searchInput.SearchCategory == "Date") {

                                   $(".search-title-new").html("<span>" + ($('#searchtextbox').val()) + " </span>");
                               }

                               else {
                                   if ($(window).width() < 992) {
                                       if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                                           $(".search-title-new").html("<span>EVI transcript search - " + $("#mobsearchtxtbox").val() + " </span>");
                                       else
                                           $(".search-title-new").html("<span>" + $("#mobsearchtxtbox").val() + " </span>");
                                       //searchTerm = $("#mobsearchtxtbox").val();
                                   }
                                   else {
                                       if (eviSearchPagination && localStorage.getItem("SearchTerm") != "" && localStorage.getItem("SearchTerm") != null)
                                           $(".search-title-new").html("<span>EVI transcript search - " + ($('#searchtextbox').val()) + " </span>");
                                       else
                                           $(".search-title-new").html("<span>" + ($('#searchtextbox').val()) + " </span>");
                                   }
                                   //$(".search-title-new").html("<span>" + searchkeyword + " </span>");

                               }


                           }
                       }

                       else {

                           if (searchInput.VideoType == "Popular") {
                               $(".search-title-new").html("<span>Most " + searchInput.VideoType.replace("Popular", "Viewed") + " Videos in " + channelName + "</span>");
                           }
                           else {
                               $(".search-title-new").html("<span>" + searchInput.VideoType + "  Videos  in " + channelName + "</span>");

                           }
                       }

                       $(window).scrollTop(0);
                       //point3
                       //   $(".pageno").html("<p>page 1 of " + Math.ceil(SearchData.DisplayPages) + "</p>"); 	 	
                       //$(".pageNavigation").remove('li'); 	 	
                       //if ($(".pageNavigation").data('twbs-pagination')) { 	 	
                       //    $(".pageNavigation").data('twbs-pagination', undefined); 	 	
                       //}  	 	
                       $("#footerpaging").show();
                       $(".pageNavigation").twbsPagination({
                           totalPages: Math.ceil(SearchData.DisplayPages),

                           visiblePages: DefaultDisplayPage,
                           first: "First",

                           last: "Last",
                           selectedPage: searchInput.PageNumber,
                           EnableRoute: true
                       });



                       var facetString = '';

                       for (i = 0; i < searchInput.Facets.length; i++) {
                           var facet = searchInput.Facets[i]


                           var str = "<span class=\"search_facet_breadcrum font-size-12\">" + facet.Name +
                                                                  "<i class=\"fa fa-times fa-lg closeFacet\" style=\"cursor:pointer;\" data-hasIndex='true' data-innerroutename=\"searchFacets\" data-facetType=\"" + facet.Type + "\" data-facetName=\"" + facet.Name +
                                                                  "\" data-facetKey=\"" + facet.Key + "\"  data-facetSubType=\"" + facet.SubType + "\"       data-facetId=\"" + facet.Key + "\"></i></span>";
                           facetString += str;

                       }


                       if ($('.facetsPanel').find('input:checked').length <= 0) {
                           $('.reset').removeClass('visibleBtn');
                       }
                       if (searchInput.Facets.length > 0) {
                           $('.reset').addClass('visibleBtn');
                       }
                       if (searchInput.Facets.length == 0) {
                           $('.reset').removeClass('visibleBtn');
                       }
                       /*checking for the video type*/
                       if (searchInput.VideoType != "") {
                           //$("#searchedfor").addClass("resetbtn");
                           $("#hdnVideoType").val(searchInput.VideoType);
                           $('#SearchReset').attr("data-videotype", searchInput.VideoType);
                           $('#SearchResult1').attr("data-videotype", searchInput.VideoType);



                           if (tempChannelId === "undefined" || tempChannelId === undefined || tempChannelId === "") {
                               tempChannelId = 0;
                           };
                           $('#SearchResult1').attr("data-channelid", tempChannelId)
                           $('#SearchReset').attr("data-channelid", tempChannelId)
                           $("#hdnChannelId").val(tempChannelId);
                       }


                        if ($("#hdnCurrentPage").val() == "" && searchInput.PageNumber != "")
                       {
                           $("#hdnCurrentPage").val(searchInput.PageNumber);
                       }


                       if (!IsNullOrEmpty(facetString)) {
                           $('#activefiltersearch').append("<div class='clearfix'></div><div class='font-size-12 margin-top-10'>Active Filters</div><div  class='clearfix margin-bottom-10'>" + facetString + "</div>");
                       }
                       if (SearchData.TotalRecords == 1) {
                           $(".result").html("<p>" + SearchData.TotalRecords + " result found, </p>");
                           $("#mobileresult").html("<p class=\"float-left\">" + SearchData.TotalRecords + " result found, page " + $("#hdnCurrentPage").val() + " of " + Math.ceil(SearchData.DisplayPages) + " </p>")
                       } else {
                           $(".result").html("<p>" + SearchData.TotalRecords + " results found, </p>");
                           $("#mobileresult").html("<p class=\"float-left\">" + SearchData.TotalRecords + " results found, page " + $("#hdnCurrentPage").val() + " of " + Math.ceil(SearchData.DisplayPages) + " </p>")
                       }

                       
                       $(".pageno").html("<p>page " + $("#hdnCurrentPage").val() + " of " + Math.ceil(SearchData.DisplayPages) + "</p>");

                       //  sessionStorage.setItem("CurrentPageNumber", searchInput.PageNumber);
                       showVideoDetails();
                       RouteProvider.bindInnerRoutes();

                   }
               }
               else {

               }
           }, function (data, status, headers, config) {
               Spinner.Stop();
               var messageViewModel = new MessageViewModel();
               messageViewModel.CreateErrorMessage(data);
               messageViewModel.ShowOverLay();
           }, JSON.stringify(object.Data));
    },
    SetSessionValueToControl: function () {
        var _this = this;
        if (IsNullOrEmpty(sessionStorage.getItem("currentTab")) != true) {
            $('#searchContent').val(sessionStorage.getItem("searchTerm"));
            $('#textSearch').html(sessionStorage.getItem("searchTerm"));
            $('#selectedCategory').attr("data-value", sessionStorage.getItem("selectedCategory"));
            if (sessionStorage.getItem("selectedCategory") == "all") {
                $('#selectedCategory').html("All");
                $('#WRDTab').show();
                $('#GNOSGTab').show();
                $('#OTHERSTab').show();
                $('.nav-tabs').find('li').removeClass('active');
            }
            else if (sessionStorage.getItem("selectedCategory") == "wrd") {
                $('#selectedCategory').html("Wiring Regulations");
                $('#WRDTab').show();
                $('#GNOSGTab').hide();
                $('#OTHERSTab').hide();
                $('.nav-tabs').find('li').removeClass('active');
            }
            else if (sessionStorage.getItem("selectedCategory") == "gnosg") {
                $('#selectedCategory').html("Guidance Notes");
                $('#WRDTab').hide();
                $('#GNOSGTab').show();
                $('#OTHERSTab').hide();
                $('.nav-tabs').find('li').removeClass('active');
                $('#GNOSGTab').addClass('active');
            }
            else if (sessionStorage.getItem("selectedCategory") == "others") {
                $('#selectedCategory').html("Others");
                $('#WRDTab').hide();
                $('#GNOSGTab').hide();
                $('#OTHERSTab').show();
                $('.nav-tabs').find('li').removeClass('active');
                $('#OTHERSTab').addClass('active');
            }
            $('#' + sessionStorage.getItem("currentTab").toUpperCase() + 'Tab').addClass('active');
            $('.mobile-search-native-tabs button').html($($("ul[role='tablist']").find('.active')[0])[0].innerText + ' <span class="caret"></span>');

            if (sessionStorage.getItem("sortKey") == "Regnum" && sessionStorage.getItem("sortOrder") == "asc") {
                $('#sortKey').html("Regnum Ascending");

            }
            else if (sessionStorage.getItem("sortKey") == "Regnum" && sessionStorage.getItem("sortOrder") == "desc") {
                $('#sortKey').html("Regnum Decending");
            }
            else if (sessionStorage.getItem("sortKey") == "relevance") {
                $('#sortKey').html("Relevance");
            }
            $('.pagebox').val(sessionStorage.getItem("pageNumber"));
            $('#sortKey').attr("data-value", sessionStorage.getItem("sortKey"));
            $('#sortKey').attr("order-by", sessionStorage.getItem("sortOrder"));
            $('.selectedPageSize').html(sessionStorage.getItem("recordPerPage"));
            $('#chkMySubscription').checked = sessionStorage.getItem("isMySubscription");

            sessionStorage.setItem("currentTab", '');
            sessionStorage.setItem("searchTerm", '');
            sessionStorage.setItem("selectedCategory", '');
            sessionStorage.setItem("sortKey", '');
            sessionStorage.setItem("sortOrder", '');
            sessionStorage.setItem("recordPerPage", '');
            sessionStorage.setItem("isMySubscription", '');
        }
    },

    Numeric: function (e) {
        var _this = this;
        this.specialKeys = new Array();
        _this.specialKeys.push(8);
        var keyCode = e.which ? e.which : e.keyCode
        var ret = ((keyCode >= 48 && keyCode <= 57) || _this.specialKeys.indexOf(keyCode) != -1);
        return ret;
    },

    PageNumberKeyUp: function () {
        var _this = this;
        _this.previousValue = (parseInt($('.pagebox').val() == '') ? 1 : $('.pagebox').val());
        $('.pagebox').unbind('keypress');
        $('.pagebox').bind('keypress', function (e) {
            var key = e.keyCode || e.which;
            if (String.fromCharCode(key).match(/[^0-9\t\b]/g)) {
                return false;
            }
        });
        $('.pagebox').unbind('focusin');
        $('.pagebox').bind('focusin', function () {
            _this.previousValue = (parseInt($(this).val() == '') ? 1 : $(this).val());
        });
        $('.pagebox').unbind('focusout');
        $('.pagebox').bind('focusout', function () {
            if (parseInt($(this).val()) > parseInt($('#hdnTotalCount').val())) {
                $('.pagebox').val(_this.previousValue);
            }
            else if (parseInt($(this).val()) == 0) {
                $('.pagebox').val(1);
            }
            else {
                _this.previousValue = $(this).val();
                $('.pagebox').val($(this).val());
            }
        })
    },

    PreviousClick: function () {
        var _this = this;
        $('.previous').click(function (event) {
            _this.PageCount();
            this.previousVal = (parseInt($('.pagebox').val() == '') ? 1 : $('.pagebox').val());
            if (parseInt($('.pagebox').val()) > 1 && $('.pagebox').val() != '') {
                $('.pagebox').val(parseInt($('.pagebox').val()) - 1);
                _this.EnableDesablePageButton();
                _this.FilterData();
            }
            event.preventDefault();
        });
    },

    ForworkClick: function () {
        var _this = this;
        $('.forward').click(function (event) {
            _this.PageCount();
            if ($('.pagebox').val() == '') {
                $('.pagebox').val(1);
            }
            if (parseInt($('.pagebox').val()) < parseInt($('#hdnTotalCount').val()) && $('.pagebox').val() != '') {
                $('.pagebox').val(parseInt($('.pagebox').val()) + 1);
                _this.EnableDesablePageButton();
                _this.FilterData();
            }

            event.preventDefault();
        });
    },

    LastClick: function () {
        var _this = this;
        $('.last').click(function (event) {
            _this.PageCount();
            if ($('.pagebox').val() == '') {
                $('.pagebox').val(1);
            }
            if (parseInt($('.pagebox').val()) != parseInt($('#hdnTotalCount').val()) && $('.pagebox').val() != '') {
                $('.pagebox').val(parseInt($('#hdnTotalCount').val()));
                _this.EnableDesablePageButton();
                _this.FilterData();
            }

            event.preventDefault();
        });
    },

    FirstClick: function () {
        var _this = this;

        $('.first').click(function (event) {
            _this.PageCount();
            if ($('.pagebox').val() != 1) {
                $('.pagebox').val(1);
                _this.EnableDesablePageButton();
                _this.FilterData();
            }
            event.preventDefault();
        });

    },

    GoClick: function () {
        var _this = this;
        $('.go').click(function (event) {
            _this.PageCount();
            if ($('.pagebox').val() == '') {
                $('.pagebox').val(1);
            }
            if (parseInt($('.pagebox').val()) <= parseInt($('#hdnTotalCount').val()) && $('.pagebox').val() != '') {
                _this.EnableDesablePageButton();
                _this.FilterData();
            }

            event.preventDefault();
        });
    },

    EnableDesablePageButton: function () {
        var _this = this;
        _this.PageCount();
        $('.forward').removeAttr('disabled');
        $($('.forward').parent()).removeClass('disabled');
        $('.last').removeAttr('disabled');
        $($('.last').parent()).removeClass('disabled');
        $('.first').removeAttr('disabled');
        $($('.first').parent()).removeClass('disabled');
        $('.previous').removeAttr('disabled');
        $($('.previous').parent()).removeClass('disabled');

        if (parseInt($('.pagebox').val()) == parseInt($('#hdnTotalCount').val()) && (parseInt($('.pagebox').val()) == 1)) {
            $('.forward').attr('disabled', 'disabled');
            $($('.forward').parent()).addClass('disabled')
            $('.last').attr('disabled', 'disabled');
            $($('.last').parent()).addClass('disabled')
            $('.first').attr('disabled', 'disabled');
            $($('.first').parent()).addClass('disabled')
            $('.previous').attr('disabled', 'disabled');
            $($('.previous').parent()).addClass('disabled')
        }
        else if (parseInt($('.pagebox').val()) == parseInt($('#hdnTotalCount').val()) && (parseInt($('.pagebox').val()) != 1)) {
            $('.forward').attr('disabled', 'disabled');
            $($('.forward').parent()).addClass('disabled')
            $('.last').attr('disabled', 'disabled');
            $($('.last').parent()).addClass('disabled')
            $('.first').removeAttr('disabled');
            $($('.first').parent()).removeClass('disabled');
            $('.previous').removeAttr('disabled');
            $($('.previous').parent()).removeClass('disabled');
        }
        else if (parseInt($('.pagebox').val()) == 1) {
            $('.first').attr('disabled', 'disabled');
            $($('.first').parent()).addClass('disabled');
            $('.previous').attr('disabled', 'disabled');
            $($('.previous').parent()).addClass('disabled');
        }
        else {
            $('.forward').removeAttr('disabled');
            $($('.forward').parent()).removeClass('disabled');
            $('.last').removeAttr('disabled');
            $($('.last').parent()).removeClass('disabled');
            $('.first').removeAttr('disabled');
            $($('.first').parent()).removeClass('disabled');
            $('.previous').removeAttr('disabled');
            $($('.previous').parent()).removeClass('disabled');
        }


    },

    MySubscriptionChange: function () {
        var _this = this;
        $('#chkMySubscription').change(function () {
            $('.pagebox').val(1);
            _this.previousValue = 1;
            _this.FilterData();
        });
    },

    SortByChange: function () {
        var _this = this;
        $('.sortKey').click(function (event) {
            $('#sortKey').attr("order-by", $(this).attr("order-by"));
            $('#sortKey').attr("data-value", $(this).attr("data-value"));
            $('#sortKey').html($.trim($(this).html()));
            $('.pagebox').val(1);
            _this.previousValue = 1;
            _this.FilterData();
            event.preventDefault();
        });
    },

    PageSizeChange: function () {
        var _this = this;
        $('.pageSize').click(function (event) {
            $('.selectedPageSize').html($.trim($(this).html()));
            $('.pagebox').val(1);
            _this.previousValue = 1;
            _this.FilterData();
            event.preventDefault();
        });
    },

    FilterData: function () {
        var _this = this;
        $('.pagebox').val((IsNullOrEmpty($('.pagebox').val()) == true) ? '1' : $('.pagebox').val());
        var currentTab = '';
        //if ($.trim($($("ul[role='tablist']").find('.active')[0]).find('a')[0].childNodes[0].data).toLowerCase() == 'wiring regulations') {
        //    currentTab = 'wrd';
        //    PageCount(parseInt($.trim($('#wiringRegulationsNo')[0].innerText)), parseInt($.trim($('.selectedPageSize').html())));
        //}
        //else if ($.trim($($("ul[role='tablist']").find('.active')[0]).find('a')[0].childNodes[0].data).toLowerCase() == 'guidance notes') {
        //    currentTab = 'gnosg';
        //    PageCount(parseInt($.trim($('#GuidenceNotesNo')[0].innerText)), parseInt($.trim($('.selectedPageSize').html())));
        //}
        //else if ($.trim($($("ul[role='tablist']").find('.active')[0]).find('a')[0].childNodes[0].data).toLowerCase() == 'others') {
        //    currentTab = 'others';
        //    PageCount(parseInt($.trim($('#OthersNo')[0].innerText)), parseInt($.trim($('.selectedPageSize').html())));
        //}
        PageCount(100, 20);


        var searchInput = {
            SearchText: $("#searchtextbox").val(),
            PageNumber: (IsNullOrEmpty($('.pagebox').val()) == true) ? '1' : $('.pagebox').val(),
            TotalPages: 10,
            PageNumber: (IsNullOrEmpty($('.pagebox').val()) == true) ? '1' : $('.pagebox').val(),
            RecordPerPage: $.trim($('.selectedPageSize').html()),
            SortKey: $.trim($('#sortKey').attr("data-value")),
            SortOrder: $('#sortKey').attr("order-by")
        };


        SearchResultRepository.SearchResult1(searchInput, _this.CurrentRouteSetting, _this.RouteProvider, _this.RouteCurrentContext);
    },

    PageCount: function () {
        var _this = this;
        //  PageCount($('#hdnTotalCount').text(), parseInt($.trim($('.selectedPageSize').html())));
        // console.log('hidden value:' + totalRecords);
        PageCount(100, 20);
    },

    TabClick: function () {
        var _this = this;
        $("a[role='tab']").click(function () {
            if ($.trim($("ul[role='tablist']").find('.active').find('a')[0].childNodes[0].data).toLowerCase() !=
                $.trim($(this)[0].childNodes[0].data).toLowerCase()) {
                $('.pagebox').val(1);
                _this.previousValue = 1;
                _this.ByTabClick = true;
                var currentTab = '';
                if ($.trim($(this)[0].childNodes[0].data).toLowerCase() == 'wiring regulations') {
                    currentTab = 'wrd';
                    $("#selectmobileTab").text('Wiring Regulations');
                }
                else if ($.trim($(this)[0].childNodes[0].data).toLowerCase() == 'guidance notes') {
                    currentTab = 'gnosg';
                    $("#selectmobileTab").text('Guidance Notes');
                }
                else if ($.trim($(this)[0].childNodes[0].data).toLowerCase() == 'others') {
                    currentTab = 'others';
                    $("#selectmobileTab").text('Others');
                }

                var facetsCheckboxes = JSON.parse(sessionStorage.getItem("FacetsCheckboxes"));

                var searchResults = {
                    CurrentTab: currentTab,
                    SearchTerm: $('#textSearch').text(),
                    SearchCategory: $.trim($('#selectedCategory').attr("data-value")),
                    PageNumber: (IsNullOrEmpty($('.pagebox').val()) == true) ? '1' : $('.pagebox').val(),
                    RecordPerPage: $.trim($('.selectedPageSize').html()),
                    SortKey: $.trim($('#sortKey').attr("data-value")),
                    SortOrder: $('#sortKey').attr("order-by"),
                    LogonId: (IsNullOrEmpty(sessionStorage.getItem("LogonId")) == true) ? GUID() : sessionStorage.getItem("LogonId"),
                    IsMySubscription: ($('#chkMySubscription').length > 0) ? $('#chkMySubscription').is(':checked') : false,
                    FacetConditions: facetsCheckboxes
                }
                SearchResultRepository.SearchResult(searchResults, _this.CurrentRouteSetting, _this.RouteProvider, _this.RouteCurrentContext);
            }
        });
    },

    XMLParse: function (XMLString, SearchCategory) {
        var _this = this;
        $('#wiringRegulations').html('');
        $('#guidanceNotes').html('');
        $('#others').html('');
        var xml = Xsl.StringToXML(XMLString);
        $(xml).find("taxonomyTerm").each(function () {
            $('.searchAside').find("input[data-id='" + $(this).attr('id') + "']").siblings("a").html($(this).attr('text') + '(' + $(this).attr('termCount') + ')');
        });
        if (SearchCategory == 'all') {
            var xmlObject = Xsl.StringToXML(XMLString);
            var xslObject = Xsl.Load("view/SearchPage.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "wiringRegulations");
            var xslObject = Xsl.Load("view/GN_SearchPage.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "guidanceNotes");
            Xsl.xslTransform(xmlObject, xslObject, "others");
            var xslObject = Xsl.Load("view/SearchTabPageW.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "wiringRegulationsNo");
            Xsl.xslTransform(xmlObject, xslObject, "Mob_wiringRegulationsNo");
            if (!_this.ByTabClick) {
                Xsl.xslTransform(xmlObject, xslObject, "DropMob_wiringRegulationsNo");
            }
            var xslObject = Xsl.Load("view/SearchTabPageG.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "GuidenceNotesNo");
            Xsl.xslTransform(xmlObject, xslObject, "Mob_GuidenceNotesNo");

            var xslObject = Xsl.Load("view/EIDG_SearchPage.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "others");
            var xslObject = Xsl.Load("view/SearchTabPageEIDG.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "OthersNo");
            Xsl.xslTransform(xmlObject, xslObject, "Mob_OtherNo");

            $('#WRDTab').show();
            $('#GNOSGTab').show();
            $('#lstWiring').show();
            $('#lstGuidance').show();

            $('#OTHERSTab').show();
            $('#lstOther').show();

            if (!_this.ByTabClick) {
                $('#wiringRegulations').show();
                $('#wiringRegulations').addClass('active')
                $('#guidanceNotes').hide();
                $('#guidanceNotes').removeClass('active')
                $('#others').hide();
                $('#others').removeClass('active')
                $('.nav-tabs').find('li').removeClass('active');
                $('#WRDTab').addClass('active');
                $("#selectmobileTab").text('Wiring Regulations');
            }
            else {
                if ($('#WRDTab').hasClass('active')) {
                    $('#wiringRegulations').show();
                    $('#wiringRegulations').addClass('active')
                    $('#guidanceNotes').hide();
                    $('#guidanceNotes').removeClass('active')
                    $('#others').hide();
                    $('#others').removeClass('active')
                    $('.nav-tabs').find('li').removeClass('active');
                    $('#GNOSGTab').removeClass('active');
                    $('#OTHERSTab').removeClass('active');
                    $('#WRDTab').addClass('active');
                    $("#selectmobileTab").text('Wiring Regulations');
                    $("#DropMob_wiringRegulationsNo").text($('#wiringRegulationsNo').text());
                }
                else if ($('#GNOSGTab').hasClass('active')) {

                    $('#wiringRegulations').hide();
                    $('#wiringRegulations').removeClass('active')
                    $('#others').hide();
                    $('#others').removeClass('active')
                    $('#guidanceNotes').show();
                    $('#guidanceNotes').addClass('active')
                    $('.nav-tabs').find('li').removeClass('active');
                    $('#WRDTab').removeClass('active');
                    $('#OTHERSTab').removeClass('active');
                    $('#GNOSGTab').addClass('active');
                    $("#selectmobileTab").text('Guidance Notes');
                    $("#DropMob_wiringRegulationsNo").text($('#GuidenceNotesNo').text());
                }
                else if ($('#OTHERSTab').hasClass('active')) {

                    $('#wiringRegulations').hide();
                    $('#wiringRegulations').removeClass('active')
                    $('#guidanceNotes').hide();
                    $('#guidanceNotes').removeClass('active')
                    $('#others').show();
                    $('#others').addClass('active')
                    $('.nav-tabs').find('li').removeClass('active');
                    $('#WRDTab').removeClass('active');
                    $('#GNOSGTab').removeClass('active');
                    $('#OTHERSTab').addClass('active');
                    $("#selectmobileTab").text('Others');
                    $("#DropMob_wiringRegulationsNo").text($('#OthersNo').text());
                }

            }
        }
        else if (SearchCategory == 'wrd') {
            var xmlObject = $.parseXML(XMLString);
            var xslObject = Xsl.Load("view/SearchPage.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "wiringRegulations");
            var xslObject = Xsl.Load("view/SearchTabPageW.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "wiringRegulationsNo");
            Xsl.xslTransform(xmlObject, xslObject, "Mob_wiringRegulationsNo");

            if (!_this.ByTabClick) {
                Xsl.xslTransform(xmlObject, xslObject, "DropMob_wiringRegulationsNo");
            }

            $('#lstWiring').show();
            $('#lstGuidance').hide();
            $('#lstOther').hide();

            $('#WRDTab').show();
            $('#GNOSGTab').hide();
            $('#OTHERSTab').hide();

            $('#wiringRegulations').show();
            $('#wiringRegulations').addClass('active')

            $('#guidanceNotes').hide();
            $('#guidanceNotes').removeClass('active')

            $('#others').hide();
            $('#others').removeClass('active')

            if (!_this.ByTabClick) {
                $('.nav-tabs').find('li').removeClass('active');
                $('#WRDTab').addClass('active');
                $("#selectmobileTab").text('Wiring Regulations');
            }

        }
        else if (SearchCategory == 'gnosg') {

            var xmlObject = $.parseXML(XMLString);
            var xslObject = Xsl.Load("view/GN_SearchPage.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "guidanceNotes");
            var xslObject = Xsl.Load("view/SearchTabPageG.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "GuidenceNotesNo");
            Xsl.xslTransform(xmlObject, xslObject, "Mob_GuidenceNotesNo");
            $('#lstWiring').hide();
            $('#lstGuidance').show();
            $('#lstOther').hide();

            $('#WRDTab').hide();
            $('#GNOSGTab').show();
            $('#OTHERSTab').hide();

            $('#wiringRegulations').hide();
            $('#wiringRegulations').removeClass('active')
            $('#guidanceNotes').show();
            $('#guidanceNotes').addClass('active')
            $('#others').hide();
            $('#others').removeClass('active')

            if (!_this.ByTabClick) {
                $('.nav-tabs').find('li').removeClass('active');
                $('#GNOSGTab').addClass('active');
                $("#selectmobileTab").text('Guidance Notes');
                Xsl.xslTransform(xmlObject, xslObject, "DropMob_wiringRegulationsNo");
            }
        }
        else if (SearchCategory == 'others') {

            var xmlObject = $.parseXML(XMLString);
            var xslObject = Xsl.Load("view/EIDG_SearchPage.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "others");
            var xslObject = Xsl.Load("view/SearchTabPageEIDG.xsl");
            Xsl.xslTransform(xmlObject, xslObject, "OthersNo");
            Xsl.xslTransform(xmlObject, xslObject, "Mob_OtherNo");
            $('#lstWiring').hide();
            $('#lstGuidance').show();
            $('#lstOther').hide();

            $('#WRDTab').hide();
            $('#GNOSGTab').hide();
            $('#OTHERSTab').show();

            $('#wiringRegulations').hide();
            $('#wiringRegulations').removeClass('active')
            $('#guidanceNotes').hide();
            $('#guidanceNotes').removeClass('active')
            $('#others').show();
            $('#others').addClass('active')

            if (!_this.ByTabClick) {
                $('.nav-tabs').find('li').removeClass('active');
                $('#OTHERSTab').addClass('active');
                $("#selectmobileTab").text('Others');
                Xsl.xslTransform(xmlObject, xslObject, "DropMob_wiringRegulationsNo");
            }
        }
        else if (SearchCategory == 'wm') {

            //to doo
        }
        $('.mobile-search-native-tabs ul.dropdown-menu li a').unbind('click');
        $('.mobile-search-native-tabs ul.dropdown-menu li a').bind('click', function () {
            $('selectmobileTab').text($(this).text().split('(')[0]);
            $('#DropMob_wiringRegulationsNo').text($(this).find('span').text());
            $('.searchHolder .seachHoldIns .nav.nav-tabs li').eq($(this).attr('tab') - 1).find('a').trigger('click');
            $('.mobile-search-native-tabs').removeClass('open');
            return false;
        });
        try {
            $('.toolTipHold').tooltip('toggle');
            $('.toolTipHold').tooltip('hide');
        }
        catch (err) {
            //to doo
        }
        sessionStorage.setItem("RedirectLocation", Application.SearchResult.BaseURL);
        _this.PageCount();
        if ($('.pagebox').val() == '') {
            $('.pagebox').val(1);
        }
        _this.EnableDesablePageButton();
    },

    SearchResultAccess: function () {
        var _this = this;
        $('.panel-body').click(function () {
            var bookID = $(this).attr('book-id');
            sessionStorage.setItem("bookId", bookID);
            if (IsNullOrEmpty(sessionStorage.getItem("LogonId"))) {
                sessionStorage.setItem("RedirectFrom", Application.SearchResult.BaseURL);
                location.href = "view/" + Application.Login.BaseURL;
            }
            else {
                var searchDetail = {
                    LogonId: (IsNullOrEmpty(sessionStorage.getItem("LogonId")) == true) ? GUID() : sessionStorage.getItem("LogonId"),
                    BookId: bookID
                }
                object = {
                    Data: { "contentRequest": searchDetail }
                };
                Repository.LoadDataJSON(WebService.BaseURL + 'ContentManagement/ContentAccess.svc/GetPackageContent',
                  function success(accessData) {
                      if (accessData.ResultObject) {
                          var v = new InlineReader();
                      }
                      else {
                          _this.MessageViewModel.CreateWarningMessage(accessData.Message, "overlayId", "okButtonId");
                          _this.MessageViewModel.ShowOverLay();
                      }
                  },
                  function error(accessData) { },

                  JSON.stringify(object.Data))
            }
        });

    },

    LoadChannels: function (facets, selectedFacets) {


        var chanelHtml = "";
        var keywordHtml = "";
        var priceHtml = "";
        var lengthHtml = "";
        var videoCategoryHtml = "";
        var videoOptionshtml = "";
        var seriesHtml = "";
        var checked = "";
        var channelCount = 0;
        var videoCategoryCount = 0;
        var keywordCount = 0;
        var seriesCount = 0;
        for (i = 0; i < facets.length; i++) {
            var facet = facets[i];
            checked = "";
            var inactiveFacets = "";
            if (facet.Type == "ChannelFacets") {

                var channels = getArrayByKey(selectedFacets, "Key", "channel_" + facet.Id);
                if (channels.length > 0) {
                    checked = "checked";
                }
                channelCount++;
                if (channelCount > 4) {
                    inactiveFacets = "inactiveFacets display-none";
                }

                chanelHtml += "<li class=\"list-group-item " + inactiveFacets + "\">" +
                                "<label class='option-container' style='position: relative;width: 100%;padding-left: 15px;'>" +
                                    "<input type=\"checkbox\"  style='position: absolute;left: 0;' data-innerroutename=\"searchFacets\" data-hasIndex='true' class=\"chkbox facetsCheckBox \" data-facetType=\"" + facet.Type + "\" data-facetName=\"" + facet.Name +
                    "\" data-facetKey=\"" + facet.Key + "\" data-facetId=\"channel_" + facet.Id + "\" " + checked + "/><span style='word-wrap: break-word; margin-left:10px;'>" + facet.Name + "</span><span class=\"item_count\">(" + facet.Count + ")</span><span class='checkmark'></span></label></li>";
            }
            else if (facet.Type == "KeywordFacets") {

                var channels = getArrayByKey(selectedFacets, "Key", facet.Key);
                if (channels.length > 0) {
                    checked = "checked";
                }
                keywordCount++;
                if (keywordCount > 5) {
                    inactiveFacets = "inactiveKeywordFacets display-none";
                }
                keywordHtml += "<li class=\"list-group-item " + inactiveFacets + "\">" +
                                "<label class='option-container' style='position: relative;width: 100%;padding-left: 15px;'>" +
                                    "<input type=\"checkbox\" style='position: absolute;left: 0;' data-hasIndex='true' data-innerroutename=\"searchFacets\" class=\"chkbox facetsCheckBox\" data-facetType=\"" + facet.Type + "\" data-facetName=\"" + facet.Name +
                    "\" data-facetKey=\"" + facet.Key + "\" data-facetSubType=\"" + facet.SubType + "\"   data-facetId=\"" + facet.Key + "\" " + checked + "/><span style='word-wrap: break-word;margin-left:10px;'>" + facet.Name + "</span><span class=\"item_count\">(" + facet.Count + ")</span><span class='checkmark'></span></label></li>";
            }
            else if (facet.Type == "Price") {

                var channels = getArrayByKey(selectedFacets, "Key", "price_" + facet.Id);
                if (channels.length > 0) {
                    checked = "checked";
                }

                priceHtml += "<li class=\"list-group-item\">" +
                                "<label class='option-container'>" +
                                    "<input type=\"checkbox\" data-innerroutename=\"searchFacets\" data-hasIndex='true' class=\"chkbox facetsCheckBox\" data-facetType=\"" + facet.Type + "\" data-facetName=\"" + facet.Name +
                    "\" data-facetKey=\"" + facet.Key + "\" data-facetId=\"price_" + facet.Id + "\" " + checked + "/><span>" + facet.Name + "</span><span class=\"item_count\">(" + facet.Count + ")</span><span class='checkmark'></span></label></li>";
            }
            else if (facet.Type == "Length") {

                var channels = getArrayByKey(selectedFacets, "Key", "length_" + facet.Id);
                if (channels.length > 0) {
                    checked = "checked";
                }

                lengthHtml += "<li class=\"list-group-item\">" +
                                "<label class='option-container'>" +
                                    "<input type=\"checkbox\" data-hasIndex='true' data-innerroutename=\"searchFacets\" class=\"chkbox facetsCheckBox\" data-facetType=\"" + facet.Type + "\" data-facetName=\"" + facet.Name +
                    "\" data-facetKey=\"" + facet.Key + "\" data-facetId=\"length_" + facet.Id + "\" " + checked + "/><span>" + facet.Name + "</span><span class=\"item_count\">(" + facet.Count + ")</span><span class='checkmark'></span></label></li>";



            }
            else if (facet.Type == "VideoCategory") {

                var videoCategorys = getArrayByKey(selectedFacets, "Key", facet.Key);
                if (videoCategorys.length > 0) {
                    checked = "checked";
                }
                videoCategoryCount++;
                if (videoCategoryCount > 4) {
                    inactiveFacets = "inactiveVideoTypeFacets display-none";
                }

                videoCategoryHtml += "<li class=\"list-group-item " + inactiveFacets + "\">" +
                                "<label class='option-container'>" +
                                    "<input type=\"checkbox\" data-innerroutename=\"searchFacets\" class=\"chkbox facetsCheckBox \" data-hasIndex='true' data-facetType=\"" + facet.Type +
                    "\" data-facetName=\"" + facet.Name + "\" data-facetKey=\"" + facet.Key + "\" data-facetId=\"" + facet.Key + "\" " + checked + "/><span>" + facet.Name + "</span><span class=\"item_count\">(" + facet.Count + ")</span><span class='checkmark'></span></label></li>";
            }

            else if (facet.Type == "Attachment") {

                var attachment = getArrayByKey(selectedFacets, "Key", "attachment_" + facet.Id);
                if (attachment.length > 0) {
                    checked = "checked";
                }

                videoOptionshtml += "<li class=\"list-group-item\">" +
                                "<label class='option-container'>" +
                                    "<input type=\"checkbox\" data-innerroutename=\"searchFacets\" data-hasIndex='true' class=\"chkbox facetsCheckBox\" data-facetType=\"" + facet.Type + "\" data-facetName=\"" + facet.Name +
                    "\" data-facetKey=\"" + facet.Key + "\" data-facetId=\"attachment_" + facet.Id + "\" " + checked + "/><span>" + facet.Name + "</span><span class=\"item_count\">(" + facet.Count + ")</span><span class='checkmark'></span></label></li>";



            }
            else if (facet.Type == "boxSet")
            {
                var series = getArrayByKey(selectedFacets, "Key", "boxSet_" + facet.Id);
                if (series.length > 0) {
                    checked = "checked";
                }
                seriesCount++;
                if (seriesCount > 4) {
                    inactiveFacets = "inactiveFacets display-none";
                }

                seriesHtml += "<li class=\"list-group-item " + inactiveFacets + "\">" +
                                "<label class='option-container' style='position: relative;width: 100%;padding-left: 15px;'>" +
                                    "<input type=\"checkbox\"  style='position: absolute;left: 0;' data-innerroutename=\"searchFacets\" data-hasIndex='true' class=\"chkbox facetsCheckBox \" data-facetType=\"" + facet.Type + "\" data-facetName=\"" + facet.Name +
                                    "\" data-facetKey=\"" + facet.Key + "\" data-facetId=\"boxSet_" + facet.Id + "\" " + checked + "/><span style='word-wrap: break-word; margin-left:5px;'>" + facet.Name + "</span><span class=\"item_count\">(" + facet.Count + ")</span><span class='checkmark'></span></label></li>";



            }

        }
        //Adding Show More Channels only if channel list is greater than 5
        if (channelCount > 4) {
            //html for show more
            //chanelHtml += "<li class=\"list-group-item show_all_items_channels\"><a href=\"#\"><span class=\"pull-left\">Show all channels</span><span aria-hidden=\"true\" class=\"glyphicon glyphicon-chevron-down\"></span></a></li>";
            chanelHtml += "<li class='list-group-item show_all_items_channels pull-left width100 fb'><a><span style='cursor: pointer;' Id='linkAllChannel'>Show all channels</span><span aria-hidden='true' class='glyphicon glyphicon-arrow-down showallCaret'></span></a></li>";
        }

        if (videoCategoryCount > 4) {
            //html for show more
            videoCategoryHtml += "<li class=\"list-group-item show_all_items_Video_Type\"><a ><span class='font-bold'  style='cursor: pointer;' Id='linkAllVideo'>Show all Video Type</span><span aria-hidden=\"true\" class=\"glyphicon glyphicon-arrow-down showallCaret\"></span></a></li>";
        }
        if (keywordCount > 5) {

            //html for show more
            keywordHtml += "<li class=\"list-group-item show_all_items_keywords\"><a ><span class='font-bold'  style='cursor: pointer;' Id='linkAllKeywords'>Show all Keywords</span><span aria-hidden=\"true\" class=\"glyphicon glyphicon-arrow-down showallCaret\"></span></a></li>";
        }
        if (seriesCount > 4)
        {
            seriesHtml += "<li class='list-group-item show_all_items_channels pull-left width100 fb'><a><span style='cursor: pointer;' Id='linkAllSeries'>Show all Series</span><span aria-hidden='true' class='glyphicon glyphicon-chevron-down showallCaret'></span></a></li>";
        }





        $("#ChannelFacets").html(chanelHtml);

        $("#KeywordFacets").html(keywordHtml);

        $("#PriceFacets").html(priceHtml);
        $("#LengthFacets").html(lengthHtml);
        $("#VideoType").html(videoCategoryHtml);
        $("#VideoOptions").html(videoOptionshtml);
        $("#BoxSet").html(seriesHtml);
        //Click event for show more
        //$(".show_all_items_channels").unbind('click');
        $(".show_all_items_channels").off('click', function () {
            //toggle display of facets
            $('.inactiveFacets').toggleClass('display-none');
            //toggle arrow
            $(this).find('.glyphicon').toggleClass('glyphicon-chevron-down');
            $(this).find('.glyphicon').toggleClass('glyphicon-chevron-up');

        });
        $(".show_all_items_channels").on('click', function () {
            //toggle display of facets
            $('.inactiveFacets').toggleClass('display-none');
            //toggle arrow
            $(this).find('.glyphicon').toggleClass('glyphicon-arrow-down');
            $(this).find('.glyphicon').toggleClass('glyphicon-arrow-up');
            var showChanneltext = $(this).find('.glyphicon').hasClass('glyphicon-arrow-down') == true ? 'Show all channels' : 'Show less channels';
            $('#linkAllChannel').text(showChanneltext);
        });
        $(".show_all_items_Video_Type").off('click', function () {
            //toggle display of facets
            $('.inactiveVideoTypeFacets').toggleClass('display-none');
            //toggle arrow
            $(this).find('.glyphicon').toggleClass('glyphicon-chevron-down');
            $(this).find('.glyphicon').toggleClass('glyphicon-chevron-up');
        });
        $(".show_all_items_Video_Type").on('click', function () {
            //toggle display of facets
            $('.inactiveVideoTypeFacets').toggleClass('display-none');
            //toggle arrow
            $(this).find('.glyphicon').toggleClass('glyphicon-arrow-down');
            $(this).find('.glyphicon').toggleClass('glyphicon-arrow-up');
            var showVideoTypetext = $(this).find('.glyphicon').hasClass('glyphicon-arrow-down') == true ? 'Show all Video Type' : 'Show less Video Type';
            $('#linkAllVideo').text(showVideoTypetext);
        });

        $(".show_all_items_keywords").off('click', function () {
            //toggle display of facets
            $('.inactiveKeywordFacets').toggleClass('display-none');
            //toggle arrow
            $(this).find('.glyphicon').toggleClass('glyphicon-chevron-down');
            $(this).find('.glyphicon').toggleClass('glyphicon-chevron-up');
        });
        $(".show_all_items_keywords").on('click', function () {
            //toggle display of facets
            $('.inactiveKeywordFacets').toggleClass('display-none');
            //toggle arrow
            $(this).find('.glyphicon').toggleClass('glyphicon-arrow-down');
            $(this).find('.glyphicon').toggleClass('glyphicon-arrow-up');
            var showKeywordText = $(this).find('.glyphicon').hasClass('glyphicon glyphicon-arrow-down') == true ? 'Show all Keywords' : 'Show less Keywords';
            $('#linkAllKeywords').text(showKeywordText);
        });

    }
}

function searchVideos(videoId, videoNo, channelName, videoTitle, displayImage, hasLock, channelId, channelColor, channelMappingDetail, IsJisc, SubscriptionType, Duration, IsEvent, EventId, LikesCount, DisLikesCount, ViewsCount, VideoCreatedDate, IsSeries, EventName, ShortDescription, IsHideRecord, EventStatus, PublishStartDate, PublishStartTime, PublishExpiryDate, PublishExpiryTime, SeriesDetailsList, FinalStartDateTime, DisplayCPD, CPDLogo, VideoAbstract, eviSearchPagination, TranscriptVideoCount) {
    videoTitle = videoTitle.replace(/\"/g, "&quot;").replace(/\'/g, "&#39;");
    var accessbtn = '';
    if (hasLock == false) {
        accessbtn = 'play.png';
    }
    else {
        accessbtn = 'lock.png';
    }

    var channels = "";
    for (i = 0; i < channelMappingDetail.length; i++) {
        var channel = channelMappingDetail[i];

        if (channels.length > 0) {
            channels += ' , ';
        }

        //PS-913: Added style color to show channel names  in the respective color
        channels += '<a data-innerroutename="Channel" data-hasindex="true" data-name="' + channel.ChannelDetail.Name + '"  data-channelId=\'' + channel.ChannelDetail.Id + '\' style="color:' + channel.ChannelDetail.ButtonColor + '; font-weight:bold;">' + channel.ChannelDetail.Name + '</a>';
    }

    var routName = "";
    var VideoRouteName = "";
    var seriesRouteName = "";
    var EventDetails = "";
    var SeriesDetails = "";
    if (IsEvent && EventId > 0) {
        var eventHTML = "";

        var PublishStartDatetime = PublishStartDate != null ? toJSDate(PublishStartDate, PublishStartTime) : "";
        var CurrentDateTime = new Date();
        var PublishEpiryDatetime = PublishExpiryDate != null ? toJSDate(PublishExpiryDate, PublishExpiryTime) : "";
            
        if(IsHideRecord == true)
        {
            $('.eventdetails' + videoNo).addClass("display-none");
        }
        else
        {
            if(EventStatus == 1)
            {
                if(PublishStartDatetime != "" && PublishEpiryDatetime != "")
                {
                    if (PublishEpiryDatetime > CurrentDateTime)
                    {
                        $('.eventdetails').removeClass("display-none");
                        routName = (IsJisc == true) ? 'JiscVideoSearch' : 'event';
                        EventDetails = '<a class="font-size-12 text-color" data-hasindex="true" data-innerroutename=\"' + routName + '\" data-eventId=\"' + EventId + '\"style="cursor:pointer">' + EventName + '</a>'
                            
                    }
                    else if (PublishEpiryDatetime < CurrentDateTime) {
                        $('.eventdetails' + videoNo).addClass("display-none");
                    }

                }
                else if (PublishStartDatetime != "" && PublishEpiryDatetime == "") {
                    
                    $('.eventdetails').removeClass("display-none");
                    routName = (IsJisc == true) ? 'JiscVideoSearch' : 'event';
                    EventDetails = '<a class="font-size-12 text-color" data-hasindex="true" data-innerroutename=\"' + routName + '\" data-eventId=\"' + EventId + '\"style="cursor:pointer">' + EventName + '</a>'

                    //}
                    //else if (PublishStartDatetime > CurrentDateTime) {
                    //    $('.eventdetails' + videoNo).addClass("display-none");
                    //}
                }
                           
            }
            else {
                $('.eventdetails' + videoNo).addClass("display-none");
            }

        }

    }
    else {
        $('.eventdetails' + videoNo).addClass("display-none");
    }

    if (EventDetails != "") {
        EventDetails = '<div class="small">Event:</div><div class="series-list small">' + EventDetails + '</div>';
    }


    VideoRouteName = (IsJisc == true) ? 'JiscVideoSearch' : 'videoid';

    if (IsSeries && SeriesDetailsList.length > 0) {
        seriesRouteName = 'series';
        var seriesHTML = "";
        for (i = 0; i < SeriesDetailsList.length; i++) {
            var series = SeriesDetailsList[i];

            if (seriesHTML.length > 0) {
                seriesHTML += ', ';
            }
            seriesHTML += '<a class="font-size-12 text-color" data-hasindex="true" data-innerroutename=\"' + seriesRouteName + '\" data-videoId=\'0\'  data-videoNo=\'0\' data-seriesId=\'' + series.SeriesId + '\'style="cursor:pointer">' + series.SeriesName + '</a>'
        }

        SeriesDetails = seriesHTML;
    }
    else {
        $('.seriesdetails' + videoNo).addClass("display-none");
    }

    if (SeriesDetails != "") {
        SeriesDetails = '<div class="small">Series:</div><div class="series-list small">' + SeriesDetails + '</div>';
    }
    if (ViewsCount == 1) {
        ViewsCount = ViewsCount + " Play";
    }
    else {
        ViewsCount = ViewsCount + " Plays";
    }
    var searchvideohtml = "";

    if (DisplayCPD == true) {
        //CPDLogo = '<div style="">' + '<img style="float: right;  margin-right: 18px; width: 40px;" class="img-responsive" src="' + CPDLogo + '">' + '</div>';
        CPDLogo = '<img src="' + CPDLogo + '" class="cpd-img" />';

    }
    else {
        CPDLogo = "";
    }

    var transcriptsearch = "";
    var transcriptplaybutton = "";
    if (eviSearchPagination) {
        if (localStorage.getItem("SearchTerm").length > 0) {
            if (TranscriptVideoCount == 0) {
                transcriptsearch += '<div class="transcript-count">Partial match found in the transcript</div>'; //for displaying Transcript Count
            }
            else
            {
                transcriptsearch += '<div class="transcript-count">This video has <span>' + TranscriptVideoCount + '</span> instances in the transcript</div>'; //for displaying Transcript Count
            }
            transcriptplaybutton += '<a class="btn btn-orange btn-sm" style="cursor:pointer;" data-hasindex="true" data-innerroutename=\"' + VideoRouteName + '\"  data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\'' + videoId + '\' data-transcriptSearch=\'' + localStorage.getItem("SearchTerm") + '\' data-videoNo=\"' + videoNo + '\" data-channelId=\"' + channelId + '\"' + '>' +
                                        'Show Transcript</a>';
        }
    }
    else {
        transcriptplaybutton += '<a class="btn btn-orange btn-sm" style="cursor:pointer;" data-hasindex="true" data-innerroutename=\"' + VideoRouteName + '\"  data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\'' + videoId + '\' data-videoNo=\"' + videoNo + '\" data-channelId=\"' + channelId + '\"' + '>' +
                                        'Watch</i></a>';
    }

    var VideoAbstractConditional = "";

    if (eviSearchPagination) {
        VideoAbstractConditional = truncateString(VideoAbstract, 85);
    }
    else {
        VideoAbstractConditional = truncateString(VideoAbstract, 150);
    }


    var bindvideohtml = "";

    bindvideohtml = '<div class="row search-result-new">' +
                        '<div class="row margin-md-0">' +
                            '<div class="col-xs-8 col-sm-10 col-md-10 left-divider search-item-block">' +
                                '<div class="row">' +
                                    '<div class="col-md-6 col-sm-6 search-item-thumbnail-container search-video-new">' +
                                     '<a class="video-thumbnail" style="cursor:pointer; background-image:url(\'' + displayImage + '\');position:relative;" data-hasindex="true" data-innerroutename=\"' + VideoRouteName + '\"  data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\'' + videoId + '\' data-videoNo=\"' + videoNo + '\" data-channelId=\"' + channelId + '\"' + '>' +
                                        '<img class="play-btn-search" src="Images/' + accessbtn + '">' +
                                        '</a>' +
                                        '<div class="channel-color" style="background-color:' + channelColor + ';"></div>' +
                                        '<div class="video-duration">' + Duration + '</div>' +
										'<div class="row"><div class="col-md-7 pull-left">'+
										 '<div class="like-dislike">' +
											'<svg id="Component_158_1" data-name="Component 158 – 1" xmlns="http://www.w3.org/2000/svg" width="21.616" height="20.146" viewBox="0 0 21.616 20.146"><path id="Path_130" data-name="Path 130" d="M280.528,241.332c2.344-.047,3.8-.047,4.882-.02,4.495.113.714,13.308-3.018,13.274-6.5-.322-8.633-1.213-9.575-1.7l-.018-.009a1.3,1.3,0,0,1-.667-1.148l0-7.882a.613.613,0,0,1,.422-.653s.953-.6,1.347-.887a11.672,11.672,0,0,0,3.858-5.7,2.946,2.946,0,0,1,1.656-2.112,2.012,2.012,0,0,1,2.364,1.593,8.575,8.575,0,0,1-.611,3.839C280.969,240.346,280.778,240.774,280.528,241.332Z" transform="translate(-265.841 -234.44)" fill="#fff"/><rect id="Rectangle_130" data-name="Rectangle 130" width="5.341" height="8.951" transform="translate(0 8.901)" fill="#fff"/></svg><span class="thumbs-up-count">' + LikesCount + '</span>' +
											'<svg id="Component_159_1" style="margin-top:2px;" data-name="Component 159 – 1" xmlns="http://www.w3.org/2000/svg" width="21.615" height="20.146" viewBox="0 0 21.615 20.146"><path id="Path_131" data-name="Path 131" d="M6.928,13.254c-2.344.047-3.8.047-4.882.02C-2.449,13.161,1.332-.034,5.063,0c6.5.322,8.633,1.212,9.575,1.7l.018.009a1.3,1.3,0,0,1,.667,1.148l0,7.881a.613.613,0,0,1-.422.653s-.953.6-1.347.887a11.672,11.672,0,0,0-3.858,5.7A2.946,2.946,0,0,1,8.044,20.1,2.012,2.012,0,0,1,5.68,18.5a8.575,8.575,0,0,1,.611-3.839C6.487,14.239,6.678,13.811,6.928,13.254Z" fill="#fff"/><rect id="Rectangle_131" data-name="Rectangle 131" width="5.341" height="8.951" transform="translate(16.274 2.294)" fill="#fff"/></svg>' + DisLikesCount + '</span>' +
										'</div>' +
										'</div><div class="col-md-5">'+
										'<div class="play-count text-right"><span>' + ViewsCount + '</span></div>' +
										'</div></div>'+
                                    '</div>' +
                                    '<div class="col-md-6 col-sm-6 search-item-data">' +
                                        transcriptsearch +
                                        '<div class="transcript-count"><span></span></div>' +
                                        '<div class="search-item-channel">' + channels + '</div>' +
                                        '<div class="search-item-title">' +
                                        '<a data-hasindex="true" data-innerroutename=\"' + VideoRouteName + '\"  data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\'' + videoId + '\' data-videoNo=\"' + videoNo + '\" data-channelId=\"' + channelId + '\" title=\"' + videoTitle + '\"' + '>' +
        videoTitle +
                                                '</a>' +
                                        '</div>' +
                                        '<div class="search-item-description">' + VideoAbstractConditional + '</div>' +
                                    '</div>' +
                                    '<div id="searchItemMore' + videoNo + '" class="col-xs-12 search-result-more" style="display:none;">' +
                                        '<div class="row search-result-speakers speaker-section' + videoNo + '">' +
                                        '</div>' +
                                        '<div class="search-result-keywords keyword-section' + videoNo + '">' +
                                        '</div>' +
                                    '</div>' +
                                    '<div class="search-item-actions col-sm-6 col-sm-offset-6 col-md-6 col-md-offset-6">' +
                                        '<div class="btn btn-default margin-right-10 searchVideoResultBtnMore btn-sm" data-toggle="collapse" data-hasindex="true"  data-videono="' + videoNo + '" data-target="searchItemMore' + videoNo + '">More</div>' +
                                            transcriptplaybutton +
                                    '</div>' +
                                '</div>' +
                            '</div>' +
                            '<div class="col-xs-4 col-sm-2 col-md-2 search-result-metadata ">' +
                                '<div class="like-dislike">' +
                                    CPDLogo +
                                '</div>' +
                                '<div style="line-height:25px">Created on:</div>' +
                                '<div class="created-on-date">' + VideoCreatedDate + '</div>' +
                                '<div style="line-height:25px">Published on:</div>' +
                                '<div class="published-on-date">' + FinalStartDateTime + '</div>' +
                                '<div class="event-series-block">' + EventDetails + SeriesDetails + '</div>' +
                                //'<div class="small">Event:</div>' +
                                //'<div class="series-list small">' + EventDetails + '</div>' +
                                //'<div class="small">Series:</div>' +
                                //'<div class="series-list small">' + SeriesDetails + '</div>' +
                                '</div>' +
                              '</div>';


    searchvideohtml = '<div class="col-md-12 col-xs-12 search_result_videos bottom-margin-15 searchresultrecord pos-relative">' +
                        '<div class="search-like-unlike-panel clearfix" style="padding: 0">' +
                          '<div class="float-left" style="width: 50%">' +
                           '<button class="fa fa-thumbs-up fa-2x  button_style_none no-padding likeDislikeBtnFontSize" id="btnVideoLike" style="cursor:default">' + '</button>' +
                           '<span id="likevalue" class="font-size-15 likevalue">' + LikesCount + '</span>' +
                          '</div>' +
                          '<div class="" style="float: left; width: 50%">' +
                           '<button class="fa fa-thumbs-down fa-2x  button_style_none no-padding likeDislikeBtnFontSize" id="btnVideoDisLike" style="cursor:default">' + '</button>' +
                           '<span id="dislikevalue" class="font-size-15 dislikevalue">' + DisLikesCount + '</span>' +
                         '</div>' +
                       CPDLogo +

                        '</div>' +

                        '<div class="bottom-margin-10 pull-left" style="cursor:pointer;margin-right:10px;">' +
                          '<a class="thumbnail-background thumbnail-desktop-list" style="position: relative;border: 3px solid black;background-image:url(\'' + displayImage + '\');" data-hasindex="true" data-innerroutename=\"' + VideoRouteName + '\"  data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\'' + videoId + '\' data-videoNo=\"' + videoNo + '\" data-channelId=\"' + channelId + '\"' + '>' +
                                            '<img class="playBtn-small-search" src="Images/' + accessbtn + '">' +
                            '<span class="video_duration">' + Duration + '</span>' +
                                        '</a>' +
                                    '</div>' +
                        '<div class="margin-left-148 margin-right video-description-clear-both highLightSearchTerm' + videoNo + '">' +
                                    '<span class=" ">' +
                            '<a class="text-color font-bold custom_pointer margin-right-15" data-hasindex="true" data-innerroutename=\"' + VideoRouteName + '\"  data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\'' + videoId + '\' data-videoNo=\"' + videoNo + '\" data-channelId=\"' + channelId + '\" title=\"' + videoTitle + '\"' + '>' +
                                              truncateString(videoTitle, 30) +
                                            '</a>' +
                                        '</span>' +
                          '<br>' +
                          '<div class="">' + channels + '</div>' +
                          '<span style="cursor:default;font-size: 10px;">' + "Created On :" +VideoCreatedDate + '</span>' + '<br>' +
                          //'<span style="cursor:default;font-size: 10px;">' + "Created On :" + VideoCreatedDate + " - " + ViewsCount + '</span>' + '<br>' +
                          //'<span style="cursor:default;font-size: 10px;">' + "Created On :" +"24 Jun 2015"+ '</span>' + '<br>' +
                          '<span style="cursor:default;font-size: 10px;">' + "Published On :" + FinalStartDateTime + '</span>' + '<br>' +
                          '<span style="cursor:default;font-size: 10px;">' + ViewsCount + '</span>' +

                           '<div class="font-size-12 eventdetails' + videoNo + '">' + EventDetails + '</div>' +

                          '<div class="font-size-12 seriesdetails' + videoNo + '">' + SeriesDetails + '</div>' +
                                    '</div>' +
                        '<div class="hide-video-details clearfix highLightMoreDetail' + videoNo + '" style="display:none;position:relative;clear: both;">' +
                        '<div class="no-padding col-sm-12 col-xs-12 user-block margin-bottom-10 margin-top-10">' +
                          ' <div class="speaker-section' + videoNo + '">' +
                          '</div>' +
                        '</div>' +
                        '<div class="font-size-12 clear-both searchResultsDescription_margin">' + ShortDescription + ' </div>' +

                        '<div  class="search-keywords-container float-left keyword-section' + videoNo + '">' +
                        '</div>' +
                         '</div>' +
                        '<div class="clearfix btn-hide-show-video-details">' +
                          '<span class="searchVideoResultBtnMore"  data-hasindex="true"  data-videono="' + videoNo + '" >' + "More" + '</span>' +
                        '</div>' +
                      '</div>'//ends very first div
    return bindvideohtml;
}


function showVideoDetails() {
    var spinnerSection = ' <img src="Images/img_loader.gif" class="overlaySpinnerImage clearfix" style="top: 45px;">';

    $(".searchVideoResultBtnMore").on('click', function () {
        var hidden_div = $(this).parent().closest(".search-result-new").find(".search-result-more");
        var hidden_series_event = $(this).parents('.search-item-block').next('.search-result-metadata').find('.event-series-block');
        if ($(this).text() == 'More') {
            $(this).parent().parent().append(spinnerSection);
            hidden_div.prepend(spinnerSection);
            var outer_height = $(".search-result-new").width() / 2;
            $(".overlaySpinnerImage").css("left", outer_height - 22);
            //Script for other open search results to close and change bg color start
            $(".searchVideoResultBtnMore").parent().parent().find(".search-result-more").slideUp(500);//To close open results
            $(".searchVideoResultBtnMore").parents('.search-item-block').next('.search-result-metadata').find('.event-series-block').slideUp(500);
            $(".searchVideoResultBtnMore").text('More');
            //$(".searchVideoResultBtnMore").removeClass("btn_more_background_color");
            //$(".searchVideoResultBtnMore").parent().removeClass("backgroundColorblue");
            //$(".searchVideoResultBtnMore").parent().parent().removeClass("active_search_result_border");
            //Script for other open search results to close and change bg color end

            //$(this).parent().addClass("backgroundColorblue");
            //$(this).parent().parent().addClass("active_search_result_border");
            //$(this).addClass("btn_more_background_color");
            $(this).text('Less');

            GetAdditionalVideoDetailsOnSearchPage($(this).attr("data-videono"));
            setTimeout(function () {
                $('.overlaySpinnerImage').hide(); disableSpinner = false;
            }, 500);
            hidden_div.slideDown(750);
            hidden_series_event.slideDown(750);

        } else {
            //$(this).removeClass("btn_more_background_color");
            //$(this).parent().removeClass("backgroundColorblue");
            //$(this).parent().parent().removeClass("active_search_result_border");
            hidden_div.slideUp(500);
            hidden_series_event.hide();
            $("#searchItemMore" + $(this).attr("data-videono")).hide();
            $(this).text('More');
            
        }


    });
}

function GetAdditionalVideoDetailsOnSearchPage(videoNo) {


    var _this = this;
    var videoFilter = {
        LogonId: BrowserStorage.getLogonId(),
        VideoNo: videoNo
    };
    var object = {
        Data: { "videoFilter": videoFilter }
    };
    disableSpinner = true;
    Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetAdditionalVideoDetailsOnSearchPage',
    function (data, status, headers, config) {
        if (ResultStatus.Successful == data.Status && data.ResultObject) {

            if (data.ResultObject == null) {
                //console.log("DisLike Activity could not be logged");
            }
            else {
                var videoDetail = data.ResultObject;
                this.CurrentSearchVideoDetail = {
                    Speakers: videoDetail.Speaker,
                    SpeakerImageSource: videoDetail.SpeakerImageSource,
                    Keywordlist: videoDetail.Keywordlist,
                    Description: videoDetail.ShortDescription
                };
                // Speaker logic
                var speakersection = ''
                if (CurrentSearchVideoDetail.Speakers != null) {
                    $.each(CurrentSearchVideoDetail.Speakers, function (index, speaker) {
                        var SpeakerImage = '';
                        if (speaker.PictureUrl.indexOf("$") != -1) {
                            SpeakerImage = speaker.PictureUrl.slice(0, speaker.PictureUrl.lastIndexOf("$"));
                        }
                        else
                            SpeakerImage = CurrentSearchVideoDetail.SpeakerImageSource + speaker.PictureUrl;

                        speakersection += VideoSpeakerHTML(index, speaker.Title, speaker.FirstName, speaker.LastName, SpeakerImage);
                    });
                    $(".speaker-section" + videoNo).html(speakersection);
                }
                //Keywords logic
                var keywordsection = ''
                if (CurrentSearchVideoDetail.Keywordlist.length != 0) {
                    $.each(CurrentSearchVideoDetail.Keywordlist, function (index, keyword) {

                        keywordsection += VideoKeywordHTML(keyword.KeywordName, keyword.KeywordId);
                    });

                }

                $(".keyword-section" + videoNo).html(keywordsection);
                $('.keyword-search').unbind("click");
                $('.keyword-search').bind("click", function (e) {
                    var width = $(window).width();
                    if (width <= 992) {
                        $("#mobsearchtxtbox").val($(this).text());
                        $('#search_param').val('All');
                        $('#Mobile-btn').html("All categories" + '<svg version="1.1" class="searchArrowMob" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 16.8 21" xml:space="preserve"><path id="Master_arrow_small" d="M2.2,10.4L6.8,15V0H10v15l4.6-4.6l2.2,2.2L8.4,21L0,12.6L2.2,10.4z" /></svg>');
                        if (localStorage.getItem('eviSearchRoute')) {
                            $('#btnSearchNewMob').trigger('click');
                            if (localStorage.getItem('SearchTerm') != '') {
                                $('#searchtextbox').val(localStorage.getItem('SearchTerm'));
                                $('#mobsearchtxtbox').val(localStorage.getItem('SearchTerm'));
                            }
                        }
                        else {
                            $("[data-innerroutename='potraitsearchResult']").click();
                            if (localStorage.getItem('SearchTerm') != '') {
                                $('#searchtextbox').val(localStorage.getItem('SearchTerm'));
                                $('#mobsearchtxtbox').val(localStorage.getItem('SearchTerm'));
                            }

                        }

                    }
                    else {
                        $("#searchtextbox").val($(this).text());
                        $('#search_param').val('All categories');
                        $('#Search_button').html("All categories" + '<svg version="1.1" class="searchArrow" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 16.8 21" xml:space="preserve"><path id="Master_arrow_small" d="M2.2,10.4L6.8,15V0H10v15l4.6-4.6l2.2,2.2L8.4,21L0,12.6L2.2,10.4z" /></svg>');
                        if (localStorage.getItem('eviSearchRoute')) {
                            $('#btnSearchNew').trigger('click');
                            if (localStorage.getItem('SearchTerm') != '') {
                                $('#searchtextbox').val(localStorage.getItem('SearchTerm'));
                                $('#mobsearchtxtbox').val(localStorage.getItem('SearchTerm'));
                            }
                        }
                        else {
                            $("[data-innerroutename='landscapesearchResult']").click();
                            if (localStorage.getItem('SearchTerm') != '') {
                                $('#searchtextbox').val(localStorage.getItem('SearchTerm'));
                                $('#mobsearchtxtbox').val(localStorage.getItem('SearchTerm'));
                            }
                        }

                    }

                });

                $("#searchItemMore" + videoNo).show();
                //select all child elements of hidehighLightSearchTerm class to highlight
                $(".highLightMoreDetail" + videoNo + " *").highlight($("#searchtextbox").val(), "searchword_highlight");
            }
        }
    },
     function (data, status, headers, config) {
         //_this.MessageViewModel.CreateErrorMessage(data);
         //_this.MessageViewModel.ShowOverLay();
     }, JSON.stringify(videoFilter));

}

function VideoSpeakerHTML(position, title, fname, lname, image) {

    var speaker = '<div class="speaker-container col-md-4">' +
                        '<img src=' + image + '>' +
                        '<div>' + fname + ' ' + lname + '</div>' +
                        "<a  class=\"text-color custom_pointer\" onClick=\"getVideoSpeakerDetails(" + position + ", \'" + name + "\')\"> View Bio</a>" +
                    '</div>';

    var speakershtml = '<div class="display-inline-block">' +
                                      '<div class="thumbnail float-left margin-right-5">' +
                                         '<img src=' + image + ' width="50" height="50" class="img-border max-width-max-height-50">' +
                                       '</div>' +
                                       ' <div class="padding-top-5 spkr-info float-left padding-right-20">' +
                                          '<div class="no-padding spkr-carousel">' +
                                              '<span class="spkr-fname">' + title + ' </span><span class="spkr-fname word-wrap">' + fname + ' </span><span class="spkr-lname word-wrap">' + lname + '</span>' +
                                          '</div>' +
                                          '<div class="spkr-bio">' +
                                              "<a  class=\"text-color custom_pointer\" onClick=\"getVideoSpeakerDetails(" + position + ", \'" + name + "\')\"> View Bio</a>" +
                                '</div>' +
                                '</div>' +
                                '</div>';

    return speaker;
}

function VideoKeywordHTML(keywordname, keywordId) {
    // $("#searchtextbox").val($(this).text())
    var keyword = '<span style="cursor:pointer;" data-hasIndex="true" class="keyword-search" id="keywordid_' + keywordId + '">' + keywordname + '</span>';
    var keywordHtml = '<span><button data-hasIndex="true" class="btn badge badge-right-margin keyword-search" id="keywordid_' + keywordId + '">' + keywordname + '</button></span>'
    return keyword;
}

function getVideoSpeakerDetails(position, name) {
    var _this = this;

    if (CurrentSearchVideoDetail.Speakers != null) {

        $.each(CurrentSearchVideoDetail.Speakers, function (index, speaker) {

            if (index == position) {
                var SpeakerImage = '';
                if (speaker.PictureUrl.indexOf("$") != -1) {
                    SpeakerImage = speaker.PictureUrl.slice(0, speaker.PictureUrl.lastIndexOf("$"));
                }
                else {
                    SpeakerImage = CurrentSearchVideoDetail.SpeakerImageSource + speaker.PictureUrl;
                }

                $('#speaker_image').attr("src", SpeakerImage);
                if (speaker.Title != '') {
                    $('#spkr_name').text(speaker.Title + " " + speaker.FirstName + " " + speaker.LastName);
                } else {
                    $('#spkr_name').text(speaker.FirstName + " " + speaker.LastName);
                }
                $('#spkr_jobtitle').text(speaker.JobTitle);
                $('#spkr_company_name').text(speaker.Organization);
                $('#spkr_affiliations').text(speaker.Affiliation);
                $('#spkr_biography').html(speaker.Biography)
                $("#viewBioPrompt").modal({
                    backdrop: 'static',
                    keyboard: false
                });
                $("#viewBioPrompt").modal('show');
                return false;
            }

        });

    }

}


function PageCount(totalCount, perPageSize) {
    if ((totalCount % perPageSize) > 0) {
        $('#hdnTotalCount').val((totalCount / perPageSize) + 1);
    }
    else {
        $('#hdnTotalCount').val((totalCount / perPageSize));
    }

}

$.fn.highlight = function (str, className) {


    var regex = new RegExp("^[a-zA-Z0-9 ]+$");
    if (regex.test(str)) {

        var regex = new RegExp(str, "gi");
        return this.each(function () {
            $(this).contents().filter(function () {
                return this.nodeType == 3 && regex.test(this.nodeValue);
            }).replaceWith(function () {

                var parentElement = this.parentElement;

                return (this.nodeValue || "").replace(regex, function (match) {
                    if ($(parentElement).hasClass("searchword_highlight")) {
                        return match;
                    }
                    else { return "<span class=\"" + className + "\">" + match + "</span>"; }
                });
            });
        });

    }
};

function toJSDate(date, time) {

    var dateTime = date.split(" ");//dateTime[0] = date, dateTime[1] = time

    var toDate = dateTime[0].split("-");
    var toTime = time.split(":");

    //(year, month, day, hours, minutes, seconds, milliseconds)
    //subtract 1 from month because Jan is 0 and Dec is 11
    return new Date(toDate[2], (toDate[1] - 1), toDate[0], toTime[0], toTime[1], 0, 0);

}
var UserManagementRepository = {

    getCorporateUserDetails: function (context, logonid, currentRouteSetting, routeProvider, routeCurrentContext) {
        var _this = this;
        $('.btnNav').show();
        Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserManagementCorporateAdmin.svc/GetCorporateAdminDtls',
            function (data, status, headers, config) {

                //console.log(data);
                if (ResultStatus.Successful == data.LoginStatus) {
                    if (ResultStatus.Successful == data.Status && data.ResultObject) {
                        //alert("ResultStatus.Successful");
                        //var sHTML = "<table cellspacing='0' border='1' cellpadding='1'>";
                        var sHTML = "";//"<tbody>";
                        var TotalUser = 0;
                        var AcctName = '';
                        var lblAccountMsg = '';
                        var AccountType = data.ResultObject.AccountTypeId;
                        lblAccountMsg = (AccountType == 2) ? 'Users for Corporate - ' : 'Users for Institution - ';
                        if (AccountType == 3) {
                            $('#chkSearchAdmin').prop('checked', true);
                            $('#chkSearchAdmin').attr('disabled', 'disabled');
                            $('#chkIsAdmin').prop('checked', true);
                            $('#chkIsAdmin').attr('disabled', 'disabled');
                            $('.btnPrePage').hide();
                            $('.btnNxtPage').hide();
                            $('#spanPager').hide();
                        }
                        var UserList = data.ResultObject.CorporateAdminUsers;
                        if (!IsNullOrEmpty(UserList)) {
                            TotalUser = UserList.length;

                            for (var varUsr = 0; varUsr < TotalUser; varUsr++) {
                                if (IsNullOrEmpty(AcctName)) { AcctName = UserList[varUsr].AccountName; }
                                var varhdnVal = {
                                    CorporateUserId: UserList[varUsr].CorporateUserId,
                                    FirstName: UserList[varUsr].FirstName,
                                    LastName: UserList[varUsr].LastName,
                                    UserName: UserList[varUsr].UserName,
                                    EmailAddress: UserList[varUsr].EmailAddress,
                                    UserIsActive: UserList[varUsr].UserIsActive,
                                    CorporateType: UserList[varUsr].CorporateType,
                                    AccountId: UserList[varUsr].AccountId,
                                    AccountName: UserList[varUsr].AccountName.replace(/'/g, '"'),
                                    CorporateUserTypeId: UserList[varUsr].CorporateUserTypeId,
                                    CorporateIpLoginId: UserList[varUsr].CorporateIpLoginId
                                };
                                sHTML += "<tr class='usrRow' id='usrRow" + varUsr + "' >";
                                sHTML += "<td class='chkSelContainer' ><input class='selRow' id='rPk" + UserList[varUsr].CorporateUserId + "' type='checkbox' /></td>";
                                sHTML += "<td class='btnEdit btnEdit_css hidden-phone custom_pointer' id='E" + UserList[varUsr].CorporateUserId + "'><u>" + UserList[varUsr].LastName + "</u></td>";
                                
                                var strIsAdminCtrl = "";
                                //if (UserList[varUsr].CorporateUserTypeId == '1') {
                                //    sHTML += "<td><input type='checkbox' value='1' checked='checked'/></td>";
                                //} else
                                if (UserList[varUsr].CorporateUserTypeId == '2') {
                                    strIsAdminCtrl = "<input type='checkbox' class='chkCorporate'   value='2' checked='checked' id='rAdmin" + UserList[varUsr].CorporateUserId + "'/>";
                                } else if (UserList[varUsr].CorporateUserTypeId == '3') {
                                    strIsAdminCtrl = "<input type='checkbox' class='chkCorporate' value='3' id='rAdmin" + UserList[varUsr].CorporateUserId + "'/>";
                                }

                                var strStatusMobileHtml = "";
                                if (UserList[varUsr].UserIsActive == '1') {
                                    strStatusMobileHtml += "<Select class='selActive show-phone show-phone_status' id='rStatus" + UserList[varUsr].CorporateUserId + "'><option selected='selected' value='A'>Active</option><option value='I'>Inactive</option></Select>";
                                } else {
                                    strStatusMobileHtml += "<Select class='selActive show-phone show-phone_status' id='rStatus" + UserList[varUsr].CorporateUserId + "'><option value='A'>Active</option><option selected='selected' value='I'>Inactive</option></Select>";
                                }

                                sHTML += "<td  class='mobile_UserDetails'><span class='btnEdit btnEdit_css hidden-phone custom_pointer' id='E" + UserList[varUsr].CorporateUserId + "'><u>" + UserList[varUsr].FirstName + "</u></span> <span class='show-phone btnEdit_css btnEdit custom_pointer' id='E" + UserList[varUsr].CorporateUserId + "'><u>" + UserList[varUsr].FirstName + "</u> <u>" + UserList[varUsr].LastName + "</u></span> <p class='show-phone'><span class='show-phone btnEdit_css btnEdit custom_pointer' id='E" + UserList[varUsr].CorporateUserId + "'><u>" + UserList[varUsr].EmailAddress + "</u></span></p> <span  class='show-phone' style='font-weight:800'><p> Corporate Admin - " + strIsAdminCtrl + "</p> </span> " + strStatusMobileHtml + "<p class='show-phone' style='margin-top:5px;'> <input type='button' class='show-phone btn btn-small dd_btn btn-default btnPwd btn_lowercase' id='R" + UserList[varUsr].CorporateUserId + "' value='Reset Password'/></p> </td>";
                                sHTML += "<td class='btnEdit btnEdit_css hidden-phone custom_pointer' id='E" + UserList[varUsr].CorporateUserId + "'><u>" + UserList[varUsr].EmailAddress + "</u></td>";
                                sHTML += "<td class='hidden-phone'>" + strIsAdminCtrl + "</td>";

                                if (UserList[varUsr].UserIsActive == '1') {
                                    sHTML += "<td class='hidden-phone'><Select class='selActive hidden-phone' id='rStatus" + UserList[varUsr].CorporateUserId + "'><option selected='selected' value='A'>Active</option><option value='I'>Inactive</option></Select></td>";
                                } else {
                                    sHTML += "<td class='hidden-phone'><Select class='selActive hidden-phone' id='rStatus" + UserList[varUsr].CorporateUserId + "'><option value='A'>Active</option><option selected='selected' value='I'>Inactive</option></Select></td>";
                                }
                               
                                //sHTML += "<td>" + UserList[varUsr].CorporateType + "</td>";
                                //sHTML += "<td>" + UserList[varUsr].AccountId + "</td>";
                                //sHTML += "<td>" + UserList[varUsr].AccountName + "</td>";
                                //sHTML += "<td>" + UserList[varUsr].AccountIsActive + "</td>";
                                //sHTML += "<td> <button class='btn btn-small active edit btnEdit' id='E" + UserList[varUsr].CorporateUserId + "'>Edit</button></td>";
                                //sHTML += "<td> <button class='btn btn-small active btnDelete' id='D" + UserList[varUsr].CorporateUserId + "'>Delete</button></td>";
                                sHTML += "<td class='hidden-phone'><input type='button' class='hidden-phone btn btn-small dd_btn btn-default btnPwd btn_lowercase Hidden_Phone_big_btn' id='R" + UserList[varUsr].CorporateUserId + "' value='Reset Password'/></td>";
                                //<button class='hidden-phone btn btn-small active btnPwd btn_lowercase Hidden_Phone_big_btn' id='R" + UserList[varUsr].CorporateUserId + "'>Reset Password</button>
                                sHTML += "<td class='hidden-sm hidden-xs' style='text-align:center;'> <p> " + UserList[varUsr].CorporateIpLoginId + "</p></td>";
                                sHTML += "<td class='mobile_delete' style='text-align:center;'><input type='Button' class='btnEdit btnEdit_css userMan_editBtn'  style='background: url(\"Images/Edit.png\") no-repeat center center;' id='E" + UserList[varUsr].CorporateUserId + "'/><input type='Button' class='btn btn-small btnDelete userMan_delBtn' style=' background: url(\"Images/Delete.png\") no-repeat center center;' id='D" + UserList[varUsr].CorporateUserId + "'/> <input type='hidden' id='U" + UserList[varUsr].CorporateUserId + "' value='" + JSON.stringify(varhdnVal) + "'/></td>";
                                //sHTML += "<td> <input type='hidden' id='U" + UserList[varUsr].CorporateUserId + "' value='" + JSON.stringify(varhdnVal) + "'/></td>";
                              
                                sHTML += "</tr>";
                            }
                            //sHTML += "</tbody>";
                            //sHTML += "</table>";
                            //console.log(sHTML);
                            //console.log($('#tblUsers :tbody').html());
                        }
                        $('#tblUsersBody').html('');
                        $('#tblUsersBody').append(sHTML);
                        $('#spnAcctName').html(lblAccountMsg + AcctName);
                        if (AccountType == 3) {
                            $('.chkCorporate').attr('disabled', true);
                        }
                        context.totalRows = TotalUser;
                        $('.btnNav').removeAttr('disabled');
                        if (TotalUser > 0) {
                            context.pgCurVal = 1;
                            pSize = context.pageSize
                            var noPage = Math.floor(TotalUser / pSize);
                            if ((TotalUser % pSize) > 0) {
                                noPage = noPage + 1;
                            }
                            context.totalPage = noPage;
                            if (noPage == 1) { $('.btnNav').attr('disabled', 'disabled'); }
                            else { $('.btnPrePage').attr('disabled', 'disabled'); }
                            _this.loadGrid(context.pgCurVal, context.pageSize, context.totalRows);
                            $('#spanPager').html(context.pgCurVal + ' of ' + context.totalPage);
                            context.BindPreviousPageClick();
                            context.BindNextPageClick();
                            $('.btnPrePage').val('Previous ' + context.pageSize);
                            $('.btnNxtPage').val('Next ' + context.pageSize);

                        }
                        else {
                            $('.btnNav').attr('disabled', 'disabled');
                            $('#spanPager').html('0 of 0');
                            context.pgCurVal = 0;
                            context.totalPage = 0;
                        }
                        context.Initilize();
                        //routeProvider.bindInnerRoutes();
                        routeProvider.bindRoutes();
                    }
                    _this.getTotalUserCount(_this, logonid);
                    _this.getTotalLicenceCount(_this, logonid);
                }
                else {
                    context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                    context.MessageViewModel.ShowOverLay();

                }
            },
            function (data, status, headers, config) {
                Spinner.Stop();
                context.MessageViewModel.CreateErrorMessage(data);
                context.MessageViewModel.ShowOverLay();

            }, JSON.stringify(logonid));
    },

    searchCorporateUserDetails: function (context, searchData) {
        var _this = this;
        $('.btnNav').show();
        $("#corpFirstName").val('');
        $("#corpLastName").val('');
        $("#corpEmail").val('');
        //$("#chkUsrStatus").prop('checked', false);
        $(".chkIsAdmin").prop('checked', false);
        $(".selUsrStatus").val('A');
        $("#curAcctId").val('');
        $("#curUserId").val('');
        //$("#curUserTypeId").val('');
        //$('#tblUsersBody').html('');
        $('#curTranMode').val('ADD');
        $('#spanLblAction').html('Add User');
        Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserManagementCorporateAdmin.svc/SearchCorporateAdminDtls',
            function (data, status, headers, config) {
                //console.log(data);
                if (ResultStatus.Successful == data.LoginStatus) {
                    if (ResultStatus.Successful == data.Status && data.ResultObject) {
                        //alert("ResultStatus.Successful");
                        //var sHTML = "<table cellspacing='0' border='1' cellpadding='1'>";
                        var sHTML = "";//"<tbody>";
                        var TotalUser = 0;
                        var AcctName = '';
                        var lblAccountMsg = '';
                        var AccountType = data.ResultObject.AccountTypeId;
                        lblAccountMsg = (AccountType == 2) ? 'Users for Corporate - ' : 'Users for Institution - ';
                        if (AccountType == 3) {
                            $('#chkSearchAdmin').prop('checked', true);
                            $('#chkSearchAdmin').attr('disabled', 'disabled');
                            $('#chkIsAdmin').prop('checked', true);
                            $('#chkIsAdmin').attr('disabled', 'disabled');
                            $('.btnPrePage').hide();
                            $('.btnNxtPage').hide();
                            $('#spanPager').hide();
                        }
                        var UserList = data.ResultObject.CorporateAdminUsers;

                        var activeUsersCount = 0;
                        for (var i = 0; i < UserList.length; i++) {
                            if (UserList[i].UserIsActive)
                                activeUsersCount++;
                        }

                        $('#cntUserActive').html(activeUsersCount);

                        if (!IsNullOrEmpty(UserList)) {
                            TotalUser = UserList.length;

                            for (var varUsr = 0; varUsr < TotalUser; varUsr++) {
                                if (IsNullOrEmpty(AcctName)) { AcctName = UserList[varUsr].AccountName; }
                                var varhdnVal = {
                                    CorporateUserId: UserList[varUsr].CorporateUserId,
                                    FirstName: UserList[varUsr].FirstName,
                                    LastName: UserList[varUsr].LastName,
                                    UserName: UserList[varUsr].UserName,
                                    EmailAddress: UserList[varUsr].EmailAddress,
                                    UserIsActive: UserList[varUsr].UserIsActive,
                                    CorporateType: UserList[varUsr].CorporateType,
                                    AccountId: UserList[varUsr].AccountId,
                                    AccountName: UserList[varUsr].AccountName.replace(/'/g, '"'),
                                    CorporateUserTypeId: UserList[varUsr].CorporateUserTypeId,
                                    CorporateIpLoginId: UserList[varUsr].CorporateIpLoginId
                                    //IsRegisterFromWebportal: UserList[varUsr].IsRegisterFromWebportal
                                };
                                sHTML += "<tr class='usrRow' id='usrRow" + varUsr + "' >";
                                sHTML += "<td class='chkSelContainer' ><input class='selRow' id='rPk" + UserList[varUsr].CorporateUserId + "' type='checkbox' /></td>";
                                sHTML += "<td class='btnEdit btnEdit_css hidden-phone custom_pointer' id='E" + UserList[varUsr].CorporateUserId + "'><u>" + UserList[varUsr].LastName + "</u></td>";

                                var strIsAdminCtrl = "";
                                //if (UserList[varUsr].CorporateUserTypeId == '1') {
                                //    sHTML += "<td><input type='checkbox' value='1' checked='checked'/></td>";
                                //} else
                                if (UserList[varUsr].CorporateUserTypeId == '2') {
                                    strIsAdminCtrl = "<input type='checkbox' class='chkCorporate' value='2'  checked='checked' id='rAdmin" + UserList[varUsr].CorporateUserId + "'/>";
                                } else if (UserList[varUsr].CorporateUserTypeId == '3') {
                                    strIsAdminCtrl = "<input type='checkbox' class='chkCorporate' value='3' id='rAdmin" + UserList[varUsr].CorporateUserId + "'/>";
                                }

                                var strStatusMobileHtml = "";
                                if (UserList[varUsr].UserIsActive == '1') {
                                    strStatusMobileHtml += "<Select class='selActive show-phone show-phone_status' id='rStatus" + UserList[varUsr].CorporateUserId + "'><option selected='selected' value='A'>Active</option><option value='I'>Inactive</option></Select>";
                                } else {
                                    strStatusMobileHtml += "<Select class='selActive show-phone show-phone_status' id='rStatus" + UserList[varUsr].CorporateUserId + "'><option value='A'>Active</option><option selected='selected' value='I'>Inactive</option></Select>";
                                }

                                //sHTML += "<td><span class='btnEdit btnEdit_css hidden-phone' id='E" + UserList[varUsr].CorporateUserId + "'>" + UserList[varUsr].FirstName + "</span><br/><span class='btnEdit btnEdit_css show-phone' id='E" + UserList[varUsr].CorporateUserId + "'>" + UserList[varUsr].FirstName + "</span> <span class='show-phone btnEdit_css btnEdit' id='E" + UserList[varUsr].CorporateUserId + "'>" + UserList[varUsr].LastName + "</span><br/><span  class='show-phone btnEdit_css btnEdit' id='E" + UserList[varUsr].CorporateUserId + "'>" + UserList[varUsr].EmailAddress + "</span> <br/><span  class='show-phone' style='font-weight:800'>Corporate Admin -" + strIsAdminCtrl + "</span><br/><br/> " + strStatusMobileHtml + "<br/><br/><button class='show-phone btn btn-small active btnPwd btn_lowercase' id='R" + UserList[varUsr].CorporateUserId + "'>Reset Password</button></td>";
                                sHTML += "<td><span class='btnEdit btnEdit_css hidden-phone custom_pointer' id='E" + UserList[varUsr].CorporateUserId + "'><u>" + UserList[varUsr].FirstName + "</u></span><br/><span class='btnEdit btnEdit_css show-phone custom_pointer' id='E" + UserList[varUsr].CorporateUserId + "'><u>" + UserList[varUsr].FirstName + "</u></span> <span class='show-phone btnEdit_css btnEdit custom_pointer' id='E" + UserList[varUsr].CorporateUserId + "'><u>" + UserList[varUsr].LastName + "</u></span> <span  class='show-phone btnEdit_css btnEdit custom_pointer' id='E" + UserList[varUsr].CorporateUserId + "'><u>" + UserList[varUsr].EmailAddress + "</u></span><span  class='show-phone' style='font-weight:800'> <p> Corporate Admin - " + strIsAdminCtrl + "</p> </span> " + strStatusMobileHtml + "<p class='show-phone' style='margin-top:5px;'> <input type='button' class='show-phone btn btn-small active btnPwd btn_lowercase' id='R" + UserList[varUsr].CorporateUserId + "' value='Reset Password'/></p> </td>";
                                sHTML += "<td class='btnEdit btnEdit_css hidden-phone custom_pointer' id='E" + UserList[varUsr].CorporateUserId + "'><u>" + UserList[varUsr].EmailAddress + "</u></td>";
                                sHTML += "<td class='hidden-phone'>" + strIsAdminCtrl + "</td>";

                                if (UserList[varUsr].UserIsActive == '1') {
                                    sHTML += "<td class='hidden-phone'><Select class='selActive hidden-phone' id='rStatus" + UserList[varUsr].CorporateUserId + "'><option selected='selected' value='A'>Active</option><option value='I'>Inactive</option></Select></td>";
                                } else {
                                    sHTML += "<td class='hidden-phone'><Select class='selActive hidden-phone' id='rStatus" + UserList[varUsr].CorporateUserId + "'><option value='A'>Active</option><option selected='selected' value='I'>Inactive</option></Select></td>";
                                }
                                //sHTML += "<td>" + UserList[varUsr].CorporateType + "</td>";
                                //sHTML += "<td>" + UserList[varUsr].AccountId + "</td>";
                                //sHTML += "<td>" + UserList[varUsr].AccountName + "</td>";
                                //sHTML += "<td>" + UserList[varUsr].AccountIsActive + "</td>";
                                //sHTML += "<td> <button class='btn btn-small active edit btnEdit' id='E" + UserList[varUsr].CorporateUserId + "'>Edit</button></td>";
                                //sHTML += "<td> <button class='btn btn-small active btnDelete' id='D" + UserList[varUsr].CorporateUserId + "'>Delete</button></td>";
                                sHTML += "<td class='hidden-phone'> <input type='button' class='hidden-phone btn btn-small active btnPwd btn_lowercase Hidden_Phone_big' id='R" + UserList[varUsr].CorporateUserId + "' value='Reset Password'></td>";
                                sHTML += "<td class='hidden-sm hidden-xs' style='text-align:center;'> <p> " + UserList[varUsr].CorporateIpLoginId + "</p></td>";
                                sHTML += "<td class='mobile_delete' style='text-align:center;'><input type='Button' class='btnEdit btnEdit_css userMan_editBtn'  style='background: url(\"Images/Edit.png\") no-repeat center center;' id='E" + UserList[varUsr].CorporateUserId + "'/><input type='Button' class='btn btn-small btnDelete userMan_delBtn' style=' background: url(\"Images/Delete.png\") no-repeat center center;' id='D" + UserList[varUsr].CorporateUserId + "'/><input type='hidden' id='U" + UserList[varUsr].CorporateUserId + "' value='" + JSON.stringify(varhdnVal) + "'/></td>";
                                // sHTML += "<td> <input type='hidden' id='U" + UserList[varUsr].CorporateUserId + "' value='" + JSON.stringify(varhdnVal) + "'/></td>";
                                sHTML += "</tr>";
                            }
                            //sHTML += "</tbody>";
                            //sHTML += "</table>";
                            //console.log(sHTML);
                            //console.log($('#tblUsers :tbody').html());
                        }
                        $('#spnAcctName').html(lblAccountMsg + AcctName);
                        context.totalRows = TotalUser;
                        if (AccountType == 3) {
                            $('.chkCorporate').attr('disabled', true);
                        }
                        $('.btnNav').removeAttr('disabled');
                        if (TotalUser > 0) {
                            $('#tblUsersBody').html('');
                            $('#tblUsersBody').append(sHTML);
                            context.pgCurVal = 1;
                            pSize = context.pageSize
                            var noPage = Math.floor(TotalUser / pSize);
                            if ((TotalUser % pSize) > 0) {
                                noPage = noPage + 1;
                            }
                            context.totalPage = noPage;
                            if (noPage == 1) { $('.btnNav').attr('disabled', 'disabled'); }
                            else { $('.btnPrePage').attr('disabled', 'disabled'); }
                            _this.loadGrid(context.pgCurVal, context.pageSize, context.totalRows);
                            $('#spanPager').html(context.pgCurVal + ' of ' + context.totalPage);
                            context.BindPreviousPageClick();
                            context.BindNextPageClick();
                            $('.btnPrePage').val('Previous ' + context.pageSize);
                            $('.btnNxtPage').val('Next ' + context.pageSize);
                        }
                        else {
                            $('.btnNav').attr('disabled', 'disabled');
                            $('#spanPager').html('0 of 0');
                            context.pgCurVal = 0;
                            context.totalPage = 0;
                            context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                            context.MessageViewModel.ShowOverLay();
                        }
                        context.Initilize();
                    }
                }
                else {
                    context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                    context.MessageViewModel.ShowOverLay();

                }
            },
            function (data, status, headers, config) {
                Spinner.Stop();
                context.MessageViewModel.CreateErrorMessage(data);
                context.MessageViewModel.ShowOverLay();

            }, JSON.stringify(searchData));
    },

    AddCorporateUser: function (objStatus, context) {
        var _this = this;
        Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserManagementCorporateAdmin.svc/AddConcurrentUser',
                    function (data, status, headers, config) {
                        //console.log(data);
                        if (ResultStatus.Successful == data.LoginStatus) {
                            if (ResultStatus.Successful == data.Status && (data.ResultObject == "1" || data.ResultObject == "2")) {
                                context.MessageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId");
                                context.MessageViewModel.ShowOverLay();
                                context.ResetControls();
                                context.GetCorporateAdminUsers(context.currentRouteSetting, context.routeProvider, context.routeCurrentContext);
                            }
                            else if (ResultStatus.Successful == data.Status && data.ResultObject == "2") {
                                context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                context.MessageViewModel.ShowOverLay();
                            }
                            else {
                                context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                context.MessageViewModel.ShowOverLay();
                            }
                            _this.getTotalUserCount(_this, BrowserStorage.getLogonId());
                            _this.getTotalLicenceCount(_this, BrowserStorage.getLogonId());
                        }
                        else {
                            context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                            context.MessageViewModel.ShowOverLay();
                        }
                    },
                    function (data, status, headers, config) {
                        Spinner.Stop();
                        context.MessageViewModel.CreateErrorMessage(data.Message, "overlayId", "okButtonId");
                        context.MessageViewModel.ShowOverLay();

                    }, JSON.stringify(objStatus));
    },

    UpdateCorporateUser: function (objStatus, context) {
        var _this = this;
        Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserManagementCorporateAdmin.svc/UpdateConcurrentUser',
                            function (data, status, headers, config) {                              
                                if (ResultStatus.Successful == data.LoginStatus) {
                                    if (ResultStatus.Successful == data.Status && (data.ResultObject == "1" || data.ResultObject == "2")) {
                                        context.MessageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId");
                                        context.MessageViewModel.ShowOverLay();
                                        context.ResetControls();
                                        context.GetCorporateAdminUsers(context.currentRouteSetting, context.routeProvider, context.routeCurrentContext);
                                    } else {
                                        context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                        context.MessageViewModel.ShowOverLay();
                                    }
                                    _this.getTotalUserCount(_this, BrowserStorage.getLogonId());
                                    _this.getTotalLicenceCount(_this, BrowserStorage.getLogonId());
                                }
                                else {
                                    context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                    context.MessageViewModel.ShowOverLay();

                                }
                            },
                            function (data, status, headers, config) {
                                Spinner.Stop();
                                context.MessageViewModel.CreateErrorMessage(data);
                                context.MessageViewModel.ShowOverLay();

                            }, JSON.stringify(objStatus));
    },

    DeleteCorporateUser: function (user, context) {
        var _this = this;

        var object = {
            Data: {

                "user": user

            }
        }
        Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserManagementCorporateAdmin.svc/DeleteCorporateUser',
                            function (data, status, headers, config) {
                               
                                if (ResultStatus.Successful == data.LoginStatus) {
                                    if (ResultStatus.Successful == data.Status && (data.ResultObject == true)) {
                                        context.MessageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId");
                                        context.MessageViewModel.ShowOverLay();
                                        context.ResetControls();
                                        context.GetCorporateAdminUsers(context.currentRouteSetting, context.routeProvider, context.routeCurrentContext);
                                    } else {
                                        context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                        context.MessageViewModel.ShowOverLay();
                                    }
                                    _this.getTotalUserCount(_this, BrowserStorage.getLogonId());
                                    _this.getTotalLicenceCount(_this, BrowserStorage.getLogonId());
                                }
                                else {
                                    context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                    context.MessageViewModel.ShowOverLay();

                                }
                            },
                            function (data, status, headers, config) {
                                Spinner.Stop();
                                context.MessageViewModel.CreateErrorMessage(data.Message);
                                context.MessageViewModel.ShowOverLay();

                            }, JSON.stringify(object.Data));
    },

    BulkUpdateCorporateUser: function (objUsers, context) {
        var _this = this;
        Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserManagementCorporateAdmin.svc/BulkUpdateConcurrentUser',
                            function (data, status, headers, config) {
                                //console.log(data);
                                if (ResultStatus.Successful == data.LoginStatus) {
                                    if (ResultStatus.Successful == data.Status && data.ResultObject == "1") {
                                        context.MessageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId");
                                        context.MessageViewModel.ShowOverLay();
                                        context.ResetControls();
                                        context.GetCorporateAdminUsers(context.currentRouteSetting, context.routeProvider, context.routeCurrentContext);
                                        $("#txtSearchName").val('');
                                        $("#txtSearctEmail").val('');
                                        $(".chkSearchAdmin").prop('checked', false);

                                    } else {
                                        context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                        context.MessageViewModel.ShowOverLay();
                                    }
                                    _this.getTotalUserCount(_this, BrowserStorage.getLogonId());
                                    _this.getTotalLicenceCount(_this, BrowserStorage.getLogonId());
                                }
                                else {
                                    context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                    context.MessageViewModel.ShowOverLay();

                                }
                            },
                            function (data, status, headers, config) {
                                Spinner.Stop();
                                context.MessageViewModel.CreateErrorMessage(data);
                                context.MessageViewModel.ShowOverLay();

                            }, JSON.stringify(objUsers));
    },

    UpdateConcurrentUserType: function (objUser, context) {
        Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserManagementCorporateAdmin.svc/UpdateConcurrentUserType',
                            function (data, status, headers, config) {
                                //console.log(data);
                                if (ResultStatus.Successful == data.LoginStatus) {
                                    if (ResultStatus.Successful == data.Status && data.ResultObject == "1") {
                                        context.MessageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId");
                                        context.MessageViewModel.ShowOverLay();
                                        context.ResetControls();
                                        context.GetCorporateAdminUsers(context.currentRouteSetting, context.routeProvider, context.routeCurrentContext);
                                    } else {
                                        context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                        context.MessageViewModel.ShowOverLay();
                                        context.GetCorporateAdminUsers(context.currentRouteSetting, context.routeProvider, context.routeCurrentContext);
                                    }
                                }
                                else {
                                    context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                    context.MessageViewModel.ShowOverLay();

                                }
                            },
                            function (data, status, headers, config) {
                                Spinner.Stop();
                                context.MessageViewModel.CreateErrorMessage(data);
                                context.MessageViewModel.ShowOverLay();

                            }, JSON.stringify(objUser));
    },

    loadGrid: function (pgNo, pgSize, totalRow) {
        $('.btnGroupActivate').attr('disabled', 'disabled');
        $('.usrRow').css('display', 'none');
        $('.usrRow').find('.chkSelContainer').removeClass('markSelect');
        //$('.usrRow').removeClass('usrRowSel');
        var rowStart = parseInt((pgNo - 1) * pgSize);
        var rowEnd = rowStart + pgSize;
        for (i = rowStart; i < rowEnd; i++) {
            var tmpid = '#usrRow' + i;
            $(tmpid).css({ "display": "table-row" });
            $(tmpid).find('.chkSelContainer').addClass('markSelect');
            //$(tmpid).addClass('usrRowSel');
        }

        if ($('.markSelect input:checked').length > 0) {
            $('.btnGroupActivate').removeAttr('disabled');
        }
    },

    fnPrePg: function (context) {
        var _this = this;
        var tmpPg = context.pgCurVal - 1;
        if (tmpPg >= 1) {
            context.pgCurVal = tmpPg;
            _this.loadGrid(tmpPg, context.pageSize, context.totalRows);
            $('#spanPager').html(context.pgCurVal + ' of ' + context.totalPage);
            $('.btnNav').removeAttr('disabled');
            if (context.pgCurVal == 1) { $('.btnPrePage').attr('disabled', 'disabled'); };
        }
    },

    fnNextPg: function (context) {
        var _this = this;
        var tmpPg = context.pgCurVal + 1;
        if (tmpPg <= context.totalPage) {
            context.pgCurVal = tmpPg;
            _this.loadGrid(tmpPg, context.pageSize, context.totalRows);
            $('#spanPager').html(context.pgCurVal + ' of ' + context.totalPage);
            $('.btnNav').removeAttr('disabled');
            if (context.pgCurVal == context.totalPage) { $('.btnNxtPage').attr('disabled', 'disabled'); };
        }
    },

    resetUserPassword: function (context, userName) {
        var _this = this;
        var object = {
            Data: {
                "user":
                    {
                        UserName: userName,
                        requestUrl: location.href.toLocaleLowerCase().split('view')[0].split("#")[0] //location.href.toLocaleLowerCase().split('view')[0]
                    }
            }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/checkUserExists',
            function (data, status, headers, config) {
                if (data.ResultObject && data.Status == ResultStatus.Successful) {
                    //console.log("Reset Successfull");

                    context.MessageViewModel.CreateInfoMessage(data.Message);
                    context.MessageViewModel.ShowOverLay();
                    context.ResetControls();
                    context.GetCorporateAdminUsers(context.currentRouteSetting, context.routeProvider, context.routeCurrentContext);
                    $('#UserTable').show();
                    $('.pnlAddButton').show();
                    $('.pnlEditButton').hide();
                    $('#pnlSearch').show();
                }
                else {
                    //console.log("Reset failed");
                    context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                    context.MessageViewModel.ShowOverLay();
                    //$('#Username').val("");
                }
            },
            function (data, status, headers, config) {
                context.MessageViewModel.CreateWarningMessage(data, "overlayId", "okButtonId", function () {
                    //$("#okButtonId").unbind();
                    //$("#okButtonId").bind("click", function (e) {
                    //    checkLoginStatus(data);
                    //});
                });
                context.MessageViewModel.ShowOverLay();
            },
            JSON.stringify(object.Data));
    },


    GetAccountDetails: function (context, logonid, currentRouteSetting, routeProvider, routeCurrentContext) {
        var _this = this;
        Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserManagementCorporateAdmin.svc/GetAccountDetails',
            function (data, status, headers, config) {
                //console.log(data);
                if (data.ResultObject != null) {
                    if (ResultStatus.Successful == data.LoginStatus) {

                        if (data.ResultObject.AccountName != null)
                            $('#txtAccountName').val(data.ResultObject.AccountName);
                        if (data.ResultObject.DarwinID != null)
                            $('#txtDarwinID').val(data.ResultObject.DarwinID);

                        var userLength = data.ResultObject.AccountConcurrentUsers.length;
                        for (var i = 0; i < userLength; i++) {
                            // alert(data.ResultObject.AccountConcurrentUsers.CorporateUserTypeId);                            
                            if (data.ResultObject.AccountConcurrentUsers[i].IsPrimaryContact == true) {
                                $('#txtContactName').val(data.ResultObject.AccountConcurrentUsers[i].FirstName);
                                $('#txtContactEmail').val(data.ResultObject.AccountConcurrentUsers[i].EmailAddress)
                                break;
                            }
                        }
                        if (data.ResultObject.AccountStatus != null) {
                            if (data.ResultObject.AccountStatus == true)
                                $('#txtAccountStatus').val('Active');
                            else
                                $('#txtAccountStatus').val('Inactive');
                        }
                        if (data.ResultObject.SubscriptionName != null)
                            $('#txtPackageName').val(data.ResultObject.SubscriptionName);

                        if (data.ResultObject.AccountSubscriptions.length > 0) {
                            if (data.ResultObject.AccountSubscriptions[0].SubscriptionStartDateTime != null) {
                                var d1 = data.ResultObject.AccountSubscriptions[0].SubscriptionStartDateTime.split(' ')[0];
                                $('#AvailabilityStartDate').val(d1);
                            }
                            if (data.ResultObject.AccountSubscriptions[0].SubscriptionEndDateTime != null) {
                                var d2 = data.ResultObject.AccountSubscriptions[0].SubscriptionEndDateTime.split(' ')[0];
                                $('#AvailabilityEndDate').val(d2);
                            }
                        }


                        if (data.ResultObject.AccountSubscriptions[0].HasLimitedLicense)
                            $('#chkConcurrent').prop('checked', true);
                        else
                            $('#chkUnlimited').prop('checked', true);

                        if (data.ResultObject.AccountSubscriptions.length > 0) {
                            $('#LicenseCount').val(data.ResultObject.AccountSubscriptions[0].LicenseCount);
                        }
                        //IP details
                        var IPLength = data.ResultObject.IPRanges.length;
                        if (IPLength > 0) {
                            $('#IPDivRow').show();
                            var content = '';
                            content = "<table class='table table-condensed table-striped table-bordered table-hover no-margin'>";
                            content += '<thead style="background:#D8D8D8"><tr><th>From</th><th>To</td></tr><thead>';
                            content += ' <tbody>'
                            for (var i = 0; i < IPLength; i++) {
                                content += '<tr><td>' + data.ResultObject.IPRanges[i].IPStartRange + '</td><td>' + data.ResultObject.IPRanges[i].IPEndRange + '</td></tr>';
                            }
                            content += '</tbody>'
                            content += "</table>";
                            $('#IPDiv').append(content);
                            $('#chkAccessTypeIP').prop('checked', true);
                        } else {
                            $('#IPDivRow').hide();
                            $('#chkAccessTypeLogin').prop('checked', true);
                        }

                    }
                    else {
                        context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                        context.MessageViewModel.ShowOverLay();

                    }

                    routeProvider.bindRoutes();
                }

            },
            function (data, status, headers, config) {
                Spinner.Stop();
                context.MessageViewModel.CreateErrorMessage(data);
                context.MessageViewModel.ShowOverLay();

            }, JSON.stringify(logonid));
    },

    getTotalUserCount: function (context, logonid) {
        var _this = this;
        Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserManagementCorporateAdmin.svc/GetUserCount',
            function (data, status, headers, config) {
                //console.log(data);
                if (ResultStatus.Successful == data.LoginStatus) {
                    if (ResultStatus.Successful == data.Status && data.ResultObject) {
                        $('#cntUserActive').html(data.ResultObject);
                    }
                }
                else {
                    context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                    context.MessageViewModel.ShowOverLay();

                }
            },
            function (data, status, headers, config) {
                Spinner.Stop();
                context.MessageViewModel.CreateErrorMessage(data);
                context.MessageViewModel.ShowOverLay();

            }, JSON.stringify(logonid));
    },

    getTotalLicenceCount: function (context, logonid) {
        var _this = this;
        Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserManagementCorporateAdmin.svc/GetLicenceCount',
            function (data, status, headers, config) {
                //console.log(data);
                if (ResultStatus.Successful == data.LoginStatus) {
                    if (ResultStatus.Successful == data.Status && data.ResultObject) {
                        111
                        //console.log(data.ResultObject);
                        $('#divLicence').html('');
                        var arrResult = data.ResultObject.split('|');
                        if (arrResult[0] == '1') {
                            $('#divLicence').html("Total Licences " + arrResult[1]);
                        }
                        else {

                        }
                    }
                }
                else {
                    context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                    context.MessageViewModel.ShowOverLay();

                }
            },
            function (data, status, headers, config) {
                Spinner.Stop();
                context.MessageViewModel.CreateErrorMessage(data);
                context.MessageViewModel.ShowOverLay();

            }, JSON.stringify(logonid));
    }

}
var Add_typenew = [];
var entityMap = {
	"&": "&amp;",
	"<": "&lt;",
	">": "&gt;",
	'"': '&quot;',
	"'": '&#39;',
	"/": '&#x2F;'
};

var displayDeclaration = true;
var isUserAcceptedWarningForCountry = false;

var PaymentGatewayRepository = {
	MessageViewModel: new MessageViewModel(),

	GetAddressList: function (context) {
		var _this = this;
		var resposne = '';
		var object = {
			Data:
			{
				"personReq": "",
				logonId: IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")
			}
		};
		Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserService.svc/GetPersonAddressList',
			function (data, status, headers, config) {
				if (data.LoginStatus == ResultStatus.Successful) {
					if (data.ResultObject != null) {
						//Get Address type from adress type dropdown
						var Add_type = [];
						$('#Add_type option').each(function () {
							Add_type.push($(this).attr('value'));
						});
						//to Remove first element.
						Add_type.shift();

						$("#IET_PERSON_ID").val(data.ResultObject.PersonId);
						$("#IET_PERSONTIMESTAMP").val(data.ResultObject.PersonTimeStamp);
						var result = data.ResultObject.AddressList;
						var table = '<table class="table table-striped table-hover table-users" id="Table_Address">';
						var thead = '<thead style="background: #E6E6E6;">' +
							'<tr>' +
							'<th class="hidden-phone" style="width:190px">Correspondence Address</th>' +
							'<th class="hidden-phone">Type</th>' +
							//'<th class="hidden-phone">Correspondence Address</th>' +
							'<th class="show-phone"></th>' +
							'<th>Billing Address</th>' +
							'<th class="hidden-phone" id="thCity">City</th>' +
							'<th class="hidden-phone">State</th>' +
							'<th class="hidden-phone">Country</th>' +
							'<th class="hidden-phone">Post code</th>' +
							'<th>Edit</th>' +
							'<th style="display:none">AddressType</th>' +
							'<th style="display:none">Address1</th>' +
							'<th style="display:none">Address2</th>' +
							'<th style="display:none">Address3</th>' +
							'<th style="display:none">Address4</th>' +
							'<th style="display:none">StateCode</th>' +
							'<th style="display:none">PostCode</th>' +
							'</tr>' +
							'</thead>';
						table += thead;
						var tbody = '<tbody id="tbodyAddr" >';
						for (i = 0; i < result.length; i++) {
							var address = result[i];
							Add_typenew.push(address.AddressType);
							var strRdoType = "";
							if (address.IsCorrespondenceAddress == true) { strRdoType = '<input class="no-margin" type="radio" name="rdoAddressType" value="' + address.AddressType + '" checked="true" />'; }
							else { strRdoType = '<input class="no-margin" type="radio" name="rdoAddressType" value="' + address.AddressType + '" />'; }
							var straddr = ($.trim(address.Address1) == "") ? "" : $.trim(address.Address1) + ",";
							straddr += (($.trim(address.Address2) == "") ? "" : $.trim(address.Address2) + ",");
							straddr += (($.trim(address.Address3) == "") ? "" : $.trim(address.Address3) + ",");
							straddr += (($.trim(address.Address4) == "") ? "" : $.trim(address.Address4) + ".");
							straddr = (($.trim(straddr) == "") ? "" : straddr.slice(0, -1));

							address.State = address.State == null ? "" : address.State;
							address.Country = address.Country == null ? "" : address.Country;
							var tr = '<tr>' +
								'<td>' + strRdoType + '</td>' +
								'<td class="hidden-phone">' + address.AddressType + '</td>' +
								'<td>' + straddr + '.' +
								' <p class="show-phone"><span>' + address.Address3 + '</span><span>' + address.City + '</span><br/><span>' + address.State + '</span><br/><span>' + address.Country + '</span><br/><span>' + address.StateCode + '</span>,<span>' + address.CountryCode + '</span></p>' +
								//'<p class="show-phone"><strong>Correspondence Address</strong> ' + strRdoType + '</p>' +
								'</td>' +
								'<td class="hidden-phone">' + address.City + '</td>' +
								//'<td class="hidden-phone">' + address.StateCode + '</td>' +
								//'<td class="hidden-phone">' + address.CountryCode + '</td>' +

								'<td class="hidden-phone">' + address.State + '</td>' +
								'<td class="hidden-phone">' + address.Country + '</td>' +
								'<td class="hidden-phone">' + address.Postcode + '</td>' +
								// '<td class="hidden-phone"><span class="label label-success">' + address.IsCorrespondenceAddress + '</span></td>' +
								'<td>' + '<button type="button" class="btn btn-small active edit btnEdit" onclick="GetAddressOnBtn(this);">Edit</button></td>' +
								//hide these  fields from user & used  during edit time
								'<td style="display:none">' + address.IsCorrespondenceAddress + '</td>' +
								'<td style="display:none">' + address.Address1 + '</td>' +
								'<td style="display:none">' + address.Address2 + '</td>' +
								'<td style="display:none">' + address.Address3 + '</td>' +
								'<td style="display:none">' + address.Address4 + '</td>' +
								'<td style="display:none">' + address.StateCode + '</td>' +
								'<td style="display:none">' + address.CountryCode + '</td>' +
								'</tr>';

							tbody += tr;
						}
						table += tbody;
						table += '</tbody>' +
							'</table>';
						// Check Address type  present in addresslist
						var CheckAddType = containsAll(Add_type, Add_typenew);
						if (CheckAddType == true) {
							$("#Add_newAdd").attr('disabled', 'disabled');
						}
						$("#Table_Address").html(table);
					}
					else {
						var messageViewModel = new MessageViewModel();
						messageViewModel.CreateErrorMessage(data.Message);
						messageViewModel.ShowOverLay();
					}
				}
				else {
					sessionStorage.setItem("RedirectLocation", Application.Address.BaseURL);//To do: From location
					sessionStorage.setItem("RedirectFrom", Application.SearchResult.BaseURL);
					location.href = "view/" + Application.Login.BaseURL;
				}

				// TODO: Display error message (data.Message) if data.Status is failed
				// TODO: populate grid with data.ResultObject
				// TODO: set PersonTimestamp in the form level hiddenfield, this need to be sent while creating/updating address record
			},
			function (data, status, headers, config) {
				var messageViewModel = new MessageViewModel();
				messageViewModel.CreateErrorMessage(data.Message);
				messageViewModel.ShowOverLay();
			}, JSON.stringify(object.Data));
	},

	CreateNewOrderAndGetAddress: function (currentRouteSetting, routeProvider, routeCurrentContext) {
		var _this = this;

		if (IsNullOrEmpty(sessionStorage.getItem("OrderId"))) {
			var object = {
				Data: {
					"logonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
					"ProductId": IsNullOrEmpty(sessionStorage.getItem("ProductId")) ? "" : sessionStorage.getItem("ProductId"),
					"Type": IsNullOrEmpty(sessionStorage.getItem("Type")) ? "" : sessionStorage.getItem("Type")
				}
			};

			Repository.LoadDataJSON(WebService.BaseURL + 'Transactions/WebPortalTransaction.svc/CreateNewOrder',
				function (data, status, headers, config) {
					if (ResultStatus.Successful == data.LoginStatus) {
						if (data.Status == ResultStatus.Successful) {
							if (data.ResultObject != null) {
								sessionStorage.setItem("OrderId", data.ResultObject.OrderId);
								sessionStorage.setItem("OrderCode", data.ResultObject.OrderCode);

								_this.GetAddressList(currentRouteSetting, routeProvider, routeCurrentContext);
								_this.bindbackAddress(currentRouteSetting, routeProvider, routeCurrentContext);
								_this.BindCountry();
							}
						}
						else if (data.Status == ResultStatus.Failed) {
							var IndividualUserType = data.ResultObject != null ? data.ResultObject.IndividualUserType : "";
							if (!parseBool(localStorage.getItem("IsIndividualUser")) || (IndividualUserType.toLowerCase() != "registered" && sessionStorage.getItem("Type") == 'channel')) {
								BrowserStorage.setRedireceLocation(Application.BaseURL);
								routeProvider.config(Application.Home.BaseURL);
							}
							else {
								if (BrowserStorage.getRedireceFrom() == Application.buySubscription.BaseURL) {
									routeProvider.config(sessionStorage.getItem("CallerPage"));
								}
								else {
									routeProvider.config(Application.Home.BaseURL);
								}
							}
							_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
							_this.MessageViewModel.ShowOverLay();
						}
					}
					else {
						//BrowserStorage.setRedireceLocation(Application.buySubscription.BaseURL);
						//BrowserStorage.setRedireceFrom(Application.SearchResult.BaseURL);
						BrowserStorage.setRedireceLocation(window.location.href);
						BrowserStorage.setRedireceFrom(window.location.href);
						location.href = "view/" + Application.Login.BaseURL;
					}
				},
				function (data, status, headers, config) {
					Spinner.Stop();
					_this.MessageViewModel.CreateErrorMessage(data.Message);
					_this.MessageViewModel.ShowOverLay();
				}, JSON.stringify(object.Data));
		}
		else {
			_this.GetAddressList(currentRouteSetting, routeProvider, routeCurrentContext);
			_this.bindbackAddress(currentRouteSetting, routeProvider, routeCurrentContext);
			_this.BindCountry();
		}
	},

	BindCountry: function (element) {
		Repository.LoadDataWithGet(WebService.BaseURL + 'UserManagement/UserService.svc/GetCountries',
			function (data, status, headers, config) {
				var i = 0;
				var StrCountry = "";
				var dropdownCountry = $("#Country");

				for (i = 0; i < data.length; i++) {
					StrCountry += '<option value="' + 'C$' + $.trim(data[i].Key) + '">' + $.trim(data[i].Value) + '</option>';
				}

				$(dropdownCountry).append(StrCountry);
				$("#countryDeclaration").append(StrCountry);

				$(dropdownCountry).change(function () {
					showHideLookupBtn();
					var CountryCode = $("#Country").val();
					CountryCode = CountryCode.split('$')[1];
					BindState(CountryCode, "");
				});
			},
			function (data, status, headers, config) {
				var messageViewModel = new MessageViewModel();
				messageViewModel.CreateErrorMessage(data.Message);
				messageViewModel.ShowOverLay();
			});
	},

	bindbackAddress: function (currentRouteSetting, routeProvider, routeCurrentContext) {
		var PurchaseType = IsNullOrEmpty(sessionStorage.getItem("Type")) ? "" : sessionStorage.getItem("Type")

		if (PurchaseType == "channel") {
			if (!IsNullOrEmpty(sessionStorage.getItem("CallerPage"))) {
				$('#backAddress').attr({
					'data-innerroutename': sessionStorage.getItem("CallerPage")
				});
			}
		}
		else {
			$('#backAddress').attr({
				'data-innerroutename': subscriptionFilter.lastRouteName,
				'data-displayvideodetails': subscriptionFilter.DisplayVideoDetails,
				'data-eventid': subscriptionFilter.EventId,
				'data-videono': subscriptionFilter.VideoNo
			});
		}
		RouteProvider.bindInnerRoutes();
	},

	checkIETServiceAccessibleForAddressList: function (currentRouteSetting, routeProvider, routeCurrentContext) {
		var _this = this;
		var object = {
			Data: { "keyId": "addresslist" }
		};
		Repository.LoadDataJSON(WebService.BaseURL + 'Utility/UtilityService.svc/GetGeneralParameters',
			function (data, status, headers, config) {
				if (data.Status == ResultStatus.Successful && data.ResultObject) {
					_this.CreateNewOrderAndGetAddress(currentRouteSetting, routeProvider, routeCurrentContext);
				}
				else {
					if (BrowserStorage.getRedireceFrom() == Application.Video.BaseURL) {
						routeProvider.config(Application.Video.BaseURL);
					}
					else if (BrowserStorage.getRedireceFrom() == Application.buySubscription.BaseURL) {
						routeProvider.config(Application.buySubscription.BaseURL);
					}
					_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
					_this.MessageViewModel.ShowOverLay();
				}
			},
			function (data, status, headers, config) {
				_this.MessageViewModel.CreateWarningMessage(data, "overlayId", "okButtonId", function () {
					$("#okButtonId").unbind();
					$("#okButtonId").bind("click", function (e) {
						checkLoginStatus(data);
					});
				});
				_this.MessageViewModel.ShowOverLay();
			}, JSON.stringify(object.Data));
	}
};

function GetAddressByPostalCode() {
	if ($.trim($("#PostalCode").val()) != "") {
		var resposne = '';
		var postcode = {
			Param: $.trim($("#PostalCode").val())
		};
		var object = {
			Data: {
				"postcode": postcode,
				logonId: IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")
			}
		};

		Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserService.svc/PostcodeLookUp',
			function (data) {
				//  alert('data = ' + data.ResultObject + ' & Message = ' + data.Message);

				if (data.ResultObject != null) {
					$('#lookup').modal('show');
					var lookuptable = '<table class="table table-striped table-hover table-users" id="Table_LookupAddress">';
					var thead = '<thead style="background: #E6E6E6;">' +
						'<tr>' +
						'<th>Address  <button style="float:right" class="close" data-dismiss="modal">×</button></th>' +
						'</tr>' +
						'</thead>';
					lookuptable += thead;
					var tbody = '<tbody id="tbodyLookupAddr"  style="height: 250px;overflow-y: scroll;display: block;" >';

					var row = ""
					for (i = 0; i < data.ResultObject.length; i++) {
						var tr = '<tr>' +
							'<td style="cursor:pointer" onclick="return GetAddressById(this)">' + data.ResultObject[i].Address + '</td>' +
							'<td style="display:none">' + data.ResultObject[i].Moniker + '</td>'
						'</tr>';
						row += tr;
					}
					lookuptable += tbody + row;
					lookuptable += '</tbody>' +
						'</table>';

					$("#divLookup").html(lookuptable);
				}
				else {
					$('#lookup').modal('show');
					$("#divLookup").html(data.Message + '<button style="float:right" class="close" data-dismiss="modal">×</button>');
				}
			},
			function (data) {
				var messageViewModel = new MessageViewModel();
				messageViewModel.CreateErrorMessage(data.Message);
				messageViewModel.ShowOverLay();
			}, JSON.stringify(object.Data));
	}
	else {
		$('#lookup').modal('hide');
	}
	return false;
}
function BindState(CountryCode, StateText) {
	var object = {
		Data: { "CountryCode": CountryCode }
	};

	Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserService.svc/GetIsPostAvailable',
		function (data, status, headers, config) {
			var i = 0;

			if (data.length > 0) {
				var IsPostAvailble = $.trim(data[0].Name);
				$("#PostalCode").removeClass("form-control no-margin netbanxform txtCtrlForValidation");
				if (IsPostAvailble == 'True') {
					$("#spanPostCode").removeClass("disp_non");
					$("#PostalCode").addClass("form-control no-margin netbanxform txtCtrlForValidation");
				}
				else if (IsPostAvailble == 'False') {
					$("#PostalCode").removeAttr('style');

					$("#spanPostCode").addClass("disp_non");

					$("#PostalCode").addClass("form-control no-margin netbanxform txtCtrlForValidation");
					$("#PostalCode").removeClass("txtCtrlForValidation");
				}
			}
		},
		function (data, status, headers, config) {
			var messageViewModel = new MessageViewModel();
			messageViewModel.CreateErrorMessage(data.Message);
			messageViewModel.ShowOverLay();
		}, JSON.stringify(object.Data));

	Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserService.svc/GetState',
		function (data, status, headers, config) {
			$("#State").html('');
			$("#State").append($("<option>").attr("value", "").text('Select a State'));
			var i = 0;

			for (i = 0; i < data.length; i++) {
				$("#State").append($("<option>").attr("value", 'C$' + $.trim(data[i].Key)).text($.trim(data[i].Value)));
			}
			if (StateText != "") {
				$("#State option:contains(" + $.trim(StateText) + ")").attr('selected', 'selected');
			}
		},
		function (data, status, headers, config) {
			var messageViewModel = new MessageViewModel();
			messageViewModel.CreateErrorMessage(data.Message);
			messageViewModel.ShowOverLay();
		}, JSON.stringify(object.Data));
}

function GetAddressOnBtn(event) {
	$("#scroll_Add").show();

	//To set mandotory fields to default color
	$(".txtCtrlForValidation,.txtCtrlForStateValidation").css('border', '1px solid #e7e7e7').css('padding', '2px 1px');

	var row = $(event).closest("tr");
	$('#Add_type').val(row.find('td:eq(1)').text());
	$('#City').val(row.find('td:eq(3)').text());
	$('#Country').val('C$' + row.find('td:eq(14)').text());
	if ($('#Country').val() != "") {
		BindState(row.find('td:eq(14)').text(), row.find('td:eq(4)').text());
	}
	$('#PostalCode').val(row.find('td:eq(6)').text());
	$('#IET_AddressType').val(row.find('td:eq(8)').text());
	$('#txtAddress1').val(row.find('td:eq(9)').text());
	$('#txtAddress2').val(row.find('td:eq(10)').text());
	$('#txtAddress3').val(row.find('td:eq(11)').text());
	$('#txtAddress4').val(row.find('td:eq(12)').text());
	showHideLookupBtn();
	$("#Add_type").attr("disabled", "disabled");
	$("#btnAdd").text('Update');
	return false;
}

function checkIETServiceAccessibleForAddressUpdate() {
	var object = {
		Data: { "keyId": "addressupdate" }
	};
	Repository.LoadDataJSON(WebService.BaseURL + 'Utility/UtilityService.svc/GetGeneralParameters',
		function (data, status, headers, config) {
			if (data.Status == ResultStatus.Successful && data.ResultObject) {
				UpdatePersonAddress();
			}
			else {
				_this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
				_this.MessageViewModel.ShowOverLay();
			}
		},
		function (data, status, headers, config) {
			_this.MessageViewModel.CreateWarningMessage(data, "overlayId", "okButtonId", function () {
				$("#okButtonId").unbind();
				$("#okButtonId").bind("click", function (e) {
					checkLoginStatus(data);
				});
			});
			_this.MessageViewModel.ShowOverLay();
		}, JSON.stringify(object.Data));
}

function checkIETServiceAccessibleForVATDeclaration() {
	var _this = this;
	var messageViewModel = new MessageViewModel();
	var object = {
		Data: { "keyId": "vat" }
	};
	Repository.LoadDataJSON(WebService.BaseURL + 'Utility/UtilityService.svc/GetGeneralParameters',
		function (data, status, headers, config) {
			if (data.Status == ResultStatus.Successful && data.ResultObject) {
				ConfirmDeclaration();
			}
			else {
				messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
				messageViewModel.ShowOverLay();
			}
		},
		function (data, status, headers, config) {
			_this.MessageViewModel.CreateWarningMessage(data, "overlayId", "okButtonId", function () {
				$("#okButtonId").unbind();
				$("#okButtonId").bind("click", function (e) {
					checkLoginStatus(data);
				});
			});
			_this.MessageViewModel.ShowOverLay();
		}, JSON.stringify(object.Data));
}

function UpdatePersonAddress() {
	var _this = this;
	var ret = ReguiredFeild($('.txtCtrlForValidation'));
	if (ret == false) {
		return false;
	}

	if ($.trim($('#Country option:selected').text()).toLowerCase() == 'united states' || $.trim($('#Country option:selected').text()).toLowerCase() == 'canada') {
		var ret = ReguiredFeild($('.txtCtrlForStateValidation'));
		if (ret == false) {
			return false;
		}
	}
	var Add_type = []
	Add_type.push($("#Add_type").val());

	var IsCorrespondenceAddress = $("#IET_AddressType").val();
	if ($("#btnAdd").text().toLowerCase() == 'save') {
		//Set IsCorrespondenceAddress as false for new address
		IsCorrespondenceAddress = false;
		if (containsAll(Add_type, Add_typenew) == true) {
			var messageViewModel = new MessageViewModel();
			messageViewModel.CreateInfoMessage("Please select different address type.", "overlayId", "okButtonId");
			messageViewModel.ShowOverLay();
			return false;
		}
	}
	var response = '';
	var CountryCode = $("#Country").val();
	CountryCode = CountryCode.split('$')[1];

	var StateCode = "";
	if ($("#State").val() != "") {
		StateCode = $("#State").val();
		StateCode = StateCode.split('$')[1];
	}

	var address = {
		AddressType: $("#Add_type").val(),
		Address1: escapeHtml($("#txtAddress1").val()),
		Address2: escapeHtml($("#txtAddress2").val()),
		Address3: escapeHtml($("#txtAddress3").val()),
		Address4: escapeHtml($("#txtAddress4").val()),
		City: escapeHtml($("#City").val()),
		StateCode: StateCode,
		CountryCode: CountryCode,
		Postcode: escapeHtml($("#PostalCode").val()),
		IsCorrespondenceAddress: IsCorrespondenceAddress
	};
	var addressList = [];
	addressList.push(address);
	var req = {
		PersonId: $("#IET_PERSON_ID").val(),   // TODO: Get from hidden field which was been set after login
		PersonTimeStamp: $("#IET_PERSONTIMESTAMP").val(), //$("#PersonTimeStamp").val(),    // TODO: Get from hidden field which was been set while loading address grid
		AddressList: addressList
	};
	var object = {
		Data: {
			"personReq": req,
			logonId: IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")
		}
	};
	Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserService.svc/UpdatePersonAddress',
		function (data, status, headers, config) {
			if (ResultStatus.Successful == data.LoginStatus) {
				if (ResultStatus.Successful == data.Status && data.ResultObject) {
					var messageViewModel = new MessageViewModel();
					messageViewModel.CreateSuccessMessage(data.Message, "overlayId", "okButtonId");
					messageViewModel.ShowOverLay();
					PaymentGatewayRepository.GetAddressList();
					$("#scroll_Add").hide();
				}
				else {
					var messageViewModel = new MessageViewModel();
					messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
					messageViewModel.ShowOverLay();
				}
			}
		},
		function (data, status, headers, config) {
			Spinner.Stop();
			var messageViewModel = new MessageViewModel();
			messageViewModel.CreateErrorMessage(data.Message);
			messageViewModel.ShowOverLay();
		}, JSON.stringify(object.Data));
}
function CloseAddressDetails() {
	$("#scroll_Add").hide();
	$('#Add_type').val("0");
	$('#txtAddress1').val("");
	$('#txtAddress2').val("");
	$('#City').val("");
	$('#txtAddress3').val("");
	$('#txtAddress4').val("");
	$("#btnAdd").text('SAVE');
	return false;
}

function GetAddressById(event) {
	var resposne = '';
	var row = $(event).closest("tr");
	var param = row.find('td:eq(1)').text();

	var postcode = {
		Param: param
	};
	var object = {
		Data:
		{
			"addressReq": postcode,
			logonId: IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")
		}
	};
	Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserService.svc/GetAddressOnAddressId',
		function (data, status, headers, config) {
			//console.log(data.ResultObject);
			if (data.ResultObject != null) {
				$("#lookup").hide();
				$('#lookup').modal('hide');
				$('#txtAddress1').val(data.ResultObject.Address1);
				$('#txtAddress2').val(data.ResultObject.Address2);
				$('#txtAddress3').val(data.ResultObject.Address3);
				$('#txtAddress4').val(data.ResultObject.Address4);
				$('#City').val(data.ResultObject.City);
				$("#Country option:contains(" + data.ResultObject.Country + ")").attr('selected', 'selected');
				if ($('#Country').val() != "") {
					var CountryCode = $("#Country").val();
					CountryCode = CountryCode.split('$')[1];
					BindState(CountryCode, data.ResultObject.State);
				}
				$('#PostalCode').val(data.ResultObject.Postcode);
			}
		},
		function (data, status, headers, config) {
			var messageViewModel = new MessageViewModel();
			messageViewModel.CreateErrorMessage(data.Message);
			messageViewModel.ShowOverLay();
		}, JSON.stringify(object.Data));
}
function showHideLookupBtn() {
	$("#btnlookup").hide();
	if ($.trim($('#Country option:selected').text()).toLowerCase() == 'united kingdom') {
		$("#btnlookup").show();
	}
}
function showAddressDetails() {
	$("#scroll_Add").show();
	//To set mandotory fields to default color
	$(".txtCtrlForValidation,.txtCtrlForStateValidation").css('border', '1px solid #e7e7e7').css('padding', '2px 1px');
	$("#Add_type").removeAttr('disabled');
	$('#Add_type').val("");
	$('#City').val("");
	$("#Country").val("");
	$("#State").html("");
	$('#PostalCode').val("");
	$('#txtAddress1').val("");
	$('#txtAddress2').val("");
	$('#txtAddress3').val("");
	$('#txtAddress4').val("");
	showHideLookupBtn();
	$("#btnAdd").text('Save');
}

function containsAll(source, dest) {
	for (var i = 0, len = source.length; i < len; i++) {
		if ($.inArray(source[i], dest) == -1) return false;
	}
	return true;
}

function CallAddressConfirmation() {
	//if (Configuration.ApplyNewVATConfigurationFor2015.toLowerCase() == "off") displayDeclaration = false;
	if (!Configuration.ApplyNewVATConfigurationFor2015) displayDeclaration = false;
	var rdoPackageSubscriptionslength = $("#Table_Address input[name=rdoAddressType]").length;
	if (rdoPackageSubscriptionslength == 0) {
		var messageViewModel = new MessageViewModel();
		messageViewModel.CreateWarningMessage("Please add an address to proceed.", "overlayId", "okButtonId");
		messageViewModel.ShowOverLay();
	}
	else {
		if (displayDeclaration) {
			var textToBeSelectedByDefault = 'Select Country';
			$("select option").filter(function () {
				//may want to use $.trim in here
				return $(this).text() == textToBeSelectedByDefault;
			}).prop('selected', true);
			// Open Declaration popup
			$('#declaration').modal('show');
		}
		else {
			var rdoPackageSubscriptionsVal = $("#Table_Address input[name=rdoAddressType]").is(":checked");
			if (rdoPackageSubscriptionsVal == true) {
				var row = $("#Table_Address input[name=rdoAddressType]:checked").closest('tr');
				if (row != null) {
					var response = '';
					var address = {
						AddressType: row.find('td:eq(1)').text(),
						Address1: escapeHtml(row.find('td:eq(9)').text()),
						Address2: escapeHtml(row.find('td:eq(10)').text()),
						Address3: escapeHtml(row.find('td:eq(11)').text()),
						Address4: escapeHtml(row.find('td:eq(12)').text()),
						City: escapeHtml(row.find('td:eq(3)').text()),
						StateCode: row.find('td:eq(13)').text(),
						CountryCode: row.find('td:eq(14)').text(),
						Postcode: escapeHtml(row.find('td:eq(6)').text()),
						IsCorrespondenceAddress: true
					};
					var addressList = [];
					addressList.push(address);
					var req = {
						PersonId: $("#IET_PERSON_ID").val(),
						PersonTimeStamp: $("#IET_PERSONTIMESTAMP").val(),
						AddressList: addressList
					};
					var declarationCountryCode1 = "";
					//if (Configuration.ApplyNewVATConfigurationFor2015.toLowerCase() == "on") {
					if (Configuration.ApplyNewVATConfigurationFor2015) {
						declarationCountryCode1 = $("#countryDeclaration").val();
						if (declarationCountryCode1 != "")
							declarationCountryCode1 = declarationCountryCode1.split('$')[1];
					}
					var object = {
						Data: {
							"personReq": req,
							logonId: IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
							orderId: IsNullOrEmpty(sessionStorage.getItem("OrderId")) ? "" : sessionStorage.getItem("OrderId"),
							declarationCountryCode: declarationCountryCode1,
							isUserAcceptedWarning: isUserAcceptedWarningForCountry
						}
					};
					Repository.LoadDataJSON(WebService.BaseURL + 'Transactions/WebPortalTransaction.svc/CheckCountryAndUpdatePersonAddress',
						function (data, status, headers, config) {
							if (ResultStatus.Successful == data.LoginStatus) {
								if (ResultStatus.Successful == data.Status && data.ResultObject) {
									//location.href = "?OrderConfirmation";
									$("#IET_PERSONTIMESTAMP").val(data.ResultObject.PersonTimeStamp);

									if (!IsNullOrEmpty(sessionStorage.getItem("ProductId"))) {
										var order = {
											"LogonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
											"OrderId": IsNullOrEmpty(sessionStorage.getItem("OrderId")) ? "" : sessionStorage.getItem("OrderId"),
											"OrderStatus": "InCheckout-PersonnelDetails"
										};

										var obj1 = {
											Data: {
												"orderDetails": order
											}
										};

										Repository.LoadDataJSON(WebService.BaseURL + 'Transactions/WebPortalTransaction.svc/UpdateOrderTransactionStatus',
											function (data, status, headers, config) {
											},
											function (data, status, headers, config) {
											}, JSON.stringify(obj1.Data));

										if (!IsNullOrEmpty(sessionStorage.getItem("OrderId"))) {
											$("[data-innerroutename='orderConfirmation']").click();
										}
									}
									else {
										var messageViewModel = new MessageViewModel();
										messageViewModel.CreateWarningMessage("Please select a subscription to proceed.", "overlayId", "okButtonId");
										messageViewModel.ShowOverLay();
									}
								}
								else {
									var messageViewModel = new MessageViewModel();
									messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
									messageViewModel.ShowOverLay();
								}
							}
						},
						function (data, status, headers, config) {
							Spinner.Stop();
							var messageViewModel = new MessageViewModel();
							messageViewModel.CreateErrorMessage(data.Message);
							messageViewModel.ShowOverLay();
						}, JSON.stringify(object.Data));
				}
			}
			else {
				var messageViewModel = new MessageViewModel();
				messageViewModel.CreateWarningMessage("Please select address to proceed", "overlayId", "okButtonId");
				messageViewModel.ShowOverLay();
			}
		}
	}
}

function escapeHtml(string) {
	return String(string).replace(/[&<>"'\/]/g, function (s) {
		return entityMap[s];
	});
}

function ConfirmDeclaration() {
	var _this = this;
	var ret = ReguiredFeild($('.txtCtrlForDeclarationValidation'));
	if (ret == false) {
		return false;
	}
	// the below if statement will never execute, but still added for precaution
	if ($("#countryDeclaration").val() == "") {
		alert("Please select country before proceeding.");
		return;
	}
	isUserAcceptedWarningForCountry = false;
	displayDeclaration = false;
	CallAddressConfirmation();
	// Call service method to confirm country validation
	//$('#declaration').modal('hide');
}

function CloseDeclaration() {
	$('#declaration').modal('hide');
}
//Model
this.PlayerDetail = {};
this.RelatedVideos = {};
this.CurrentVideoDetail = {};
this.SpeakerDetails = {};
var entryid = '';
var played = 0;
var EventAccessCodeType = 1;
var SpeakerAccessCodeType = 2;
var VideoAccessCodeType = 3;
this.CommentsEnable = false;
var CommentsPerPage = 4;
var DefaultCommentsDisplayPage = 3;
this.CommentPagingRender = false;
var VideoIsDisplayQA = false;
var VideoIsDisplayPolling = false;
var EmbdedViodeoplayed = 0;
var space = " ";
//Azure code added by Start 2018/04/19
var myPlayer = null;

//Azure code added by End 2018/04/19

var VideoRepository = {
    getCurrentVideo: function (currentRouteSetting, routeProvider, routeCurrentContext, videoFilter, videoContext) {
        var _this = this;
        played = 0;
        var object = {
            Data: { "videoFilter": videoFilter }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetCurrentVideoDetail',
            function (data, status, headers, config) {
                sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            var time = new Date();
                            var isAuthenticated = true;
                            localStorage.setItem("nextViewCommentCount", "0");
                            localStorage.setItem("LoginStatus", data.LoginStatus);
                            var videoDetail = data.ResultObject;
                            this.CurrentVideoDetail = {
                                VideoId: videoDetail.VideoId,
                                ChannelId: videoDetail.ChannelId,
                                ChannelCategoryTypeId: videoDetail.ChannelCategoryTypeId,
                                Title: videoDetail.VideoTitle,
                                Description: videoDetail.ShortDescription,
                                Abstract: videoDetail.Abstract,
                                DisplayImage: videoDetail.DisplayImage + "?" + time.getTime(),
                                ChannelName: videoDetail.ChannelName,
                                //EntryId: videoDetail.StreamUKId,
                                EncodedAssetId: videoDetail.EncodedAssetId,
                                SmoothStreamingURL: videoDetail.SmoothStreamingURL,
                                ShowOnPortal: videoDetail.ShowOnPortal,
                                DefaultChannel: videoDetail.channelName,
                                Permissions: videoDetail.PermissionDetail,
                                Attachment: videoDetail.Attachment,
                                ChannelList: videoDetail.ChannelList,//current video detail
                                Speakers: videoDetail.Speaker,
                                SpeakerImageSource: videoDetail.SpeakerImageSource,
                                DefaultSpeakerImage: videoDetail.DefaultSpeakerImage,
                                Keywordlist: videoDetail.Keywordlist,
                                HasLock: videoDetail.HasLock,
                                HasPromo: videoDetail.HasPromo,
                                PromoType: videoDetail.PromoType,
                                HasUserAccess: videoDetail.HasUserAccess,
                                ViewsCount: videoDetail.ViewsCount,
                                LikesCount: videoDetail.LikesCount,
                                DisLikesCount: videoDetail.DisLikesCount,
                                LastLikeDislikeActivity: videoDetail.LastLikeDislikeActivity,
                                Duration: videoDetail.Duration,
                                PremiumPrice: videoDetail.PremiumPrice,
                                CanPlay: videoDetail.CanPlay,
                                CanLikeDislike: videoDetail.CanLikeDislike,
                                AllowDownload: videoDetail.AllowDownload,
                                //relatedVideos: videoDetail.RelatedVideos,
                                AllowAttachmentDownload: videoDetail.AllowAttachmentDownload,
                                //Comments: videoDetail.Comments,
                                IsCommentsEnable: videoDetail.IsCommentsEnable,
                                PriceType: videoDetail.PriceType,
                                Duration: videoDetail.Duration,
                                SubscriptionType: videoDetail.SubscriptionType,
                                VideoDate: videoDetail.VideoDate,
                                //RelatedContent: videoDetail.RelatedContent,
                                IsLive: videoDetail.IsLive,
                                IsQnAEnabled: videoDetail.DisplayQAndA,
                                IsPollingEnabled: videoDetail.DisplayPolling,
                                SponseredItem: videoDetail.SponseredItem,
                                IndividualUserType: videoDetail.IndividualUserType.toLowerCase(),
                                IsDisplayCPD: videoDetail.DisplayCPD,
                                CPDLogo: videoDetail.CPDLogo,
                                IsPartofEvent: videoDetail.IsPartofEvent,
                                EventDetails: videoDetail.EventDetails,
                                IsSeries: videoDetail.IsSeries,
                                SeriesDetailsList: videoDetail.SeriesDetailsList,
                                VideoNo: videoDetail.VideoNo,
                                TranscriptList: videoDetail.objTranscriptList,
                                CPDLogoText: videoDetail.CPDLogoText,
                                DigitalLibrary: videoDetail.DigitalLibrary,
                                PremiumDiscountPercentage: videoDetail.PremiumDiscountPercentage,
                                PremiumDiscountAmount: videoDetail.PremiumDiscountAmount,
                                DiscountType: videoDetail.DiscountType,
                                EventDiscount: videoDetail.EventDiscount,
                                StreamingEnd: videoDetail.StreamingEnd,
                                // Rakesh : Set Transcript Parameters
                                IsSubTitleContentAvailable: videoDetail.IsSubTitleContentAvailable,
                                SubTitleJsonPath: videoDetail.SubTitleJsonPath,
                                lstSrtSubTitles: videoDetail.lstSrtSubTitles,
                                /// Author: Sanjana
                                /// Date: 19-07-2017
                                /// Decription: get and set video duration in 00:00:00 format
                                TimeDuration: videoDetail.TimeDuration,
                                CommentCounts: videoDetail.CommentCounts
                                //End
                            };

                            if (CurrentVideoDetail.HasPromo) {
                                CurrentVideoDetail.DisplayImage = videoDetail.DisplayImage;
                            }

                            if (!IsNullOrEmpty(CurrentVideoDetail.VideoId)) {
                                sessionStorage.setItem("VideoId", CurrentVideoDetail.VideoId);
                            }
                            if (!IsNullOrEmpty(CurrentVideoDetail.EventDetails) && !IsNullOrEmpty(CurrentVideoDetail.EventDetails.Id)) {
                                sessionStorage.setItem("EventId", CurrentVideoDetail.EventDetails.Id);
                            }
                            setMetaData(CurrentVideoDetail.Title, CurrentVideoDetail.Description);
                            //SEO-Title

                            $(".sponserdiv").html("");
                            if (CurrentVideoDetail.SponseredItem != null && CurrentVideoDetail.SponseredItem.SponserImagePath != null) {
                                var str = "<a href='#' onclick=OpenURL('" + CurrentVideoDetail.SponseredItem.SponserURL + "')><img src='" + CurrentVideoDetail.SponseredItem.SponserImagePath + "' class='right-video-banner-thumbnail-image'></a>";
                                $('.sponserdiv').append(str);
                            }
                            else {
                                $('#video-content').parent("div").removeClass('col-md-6 col-sm-6').addClass('col-md-9 col-sm-9');
                            }

                            $("#desktop-cpd-logo").attr("src", "");
                            $("#mobile-cpd-logo").attr("src", "");
                            if (CurrentVideoDetail.IsDisplayCPD && CurrentVideoDetail.CPDLogo != "") {
                                $("#desktop-cpd-logo").attr("src", CurrentVideoDetail.CPDLogo);
                                $("#desktop-cpd-logo").css("display", "block");
                                $("#mobile-cpd-logo").attr("src", CurrentVideoDetail.CPDLogo);
                                $("#mobile-cpd-logo").css("display", "block");
                                $("#desktop-cpd-logo").attr("data-content", CurrentVideoDetail.CPDLogoText);
                                $("#mobile-cpd-logo").attr("data-content", CurrentVideoDetail.CPDLogoText);
                            }
                            //Rakesh : Assign Comments
                            $('#spnCommentsCount').html(CurrentVideoDetail.CommentCounts);

                            //var KPlayerDetails = data.ResultObject.KalturaPlayerDetail;

                            $('#VideoDate').html(CurrentVideoDetail.VideoDate);
                            if (!CurrentVideoDetail.IsLive & !CurrentVideoDetail.HasLock) {
                                //Rakesh: Begin  Load IETTVTranscript.Js and load Transcript Content
                                $.getScript("Script/Transcript/IETTVTranscript.js", function () {
                                    if (CurrentVideoDetail.IsSubTitleContentAvailable) {
                                        IETTVTranscript.BindLanguagesDropdown(CurrentVideoDetail.lstSrtSubTitles);
                                        $('.transcript-icon').removeClass('hidden');
                                        // IETTVTranscript.LoadTranscripts(CurrentVideoDetail.SubTitleJsonPath);
                                    }
                                });
                            }

                            $('.myclips').addClass('disabledbutton');
                            $('.share-img-icon').addClass('disabledbutton');
                            $('.transcript-icon').addClass('hidden');
                            //Rakesh: End

                            /// Author: Sanjana
                            /// Date:02-07-2017
                            /// Decription: hide and show divs
                            if (CurrentVideoDetail.IsLive) {
                                $('.myclips').addClass('hidden');
                                $('.share-img-icon').addClass('hidden');
                            }
                            else {
                                if (!IsNullOrEmpty(sessionStorage.getItem("LogonId"))) {
                                    if (sessionStorage.getItem("IsIPLogin") == null || sessionStorage.getItem("IsIPLogin") == "false") {
                                        $('.myclips').removeClass('hidden');
                                    } else {
                                        $('.myclips').addClass('hidden');
                                    }
                                }
                                else {
                                    $('.myclips').addClass('hidden');
                                }
                            }

                            //End
                            if (CurrentVideoDetail.HasLock == true) {
                                if (!IsNullOrEmpty(videoFilter.AccessCode) && parseBool(sessionStorage.getItem("accessCodeFlag")) == false && parseBool(sessionStorage.getItem("accessCodeFlag")) != null) {
                                    var messageViewModel = new MessageViewModel();
                                    messageViewModel.CreateWarningMessage("Access code entered is invalid", "overlayId", "okButtonId")
                                    messageViewModel.ShowOverLay();

                                    sessionStorage.removeItem("accessCode");
                                    sessionStorage.removeItem("accessCodeType");
                                }
                                var videoType = '';
                                var premiumPriceDetailFirst = '';
                                var premiumPriceDetailSecond = '';
                                var premiumEventDetail = '';
                                var btnPurchaseEvent = '';
                                var btnPurchaseProduct = '';
                                var premiumhtml = '';

                                if (CurrentVideoDetail.PriceType != "Free") {
                                    //display embed for free video
                                    $(".embedmodal").css('display', 'none');
                                    //Message for institute & corporate user if they are trying to purchase product.
                                    if (parseBool(localStorage.getItem("IsIndividualUser")) == true || (sessionStorage.getItem("LogonId") == null || sessionStorage.getItem("LogonId") == "")) {
                                        if (CurrentVideoDetail.PriceType == 'Subscription') {
                                            if (CurrentVideoDetail.ChannelCategoryTypeId == 1) {
                                                videoType = ' This video is part of paid channel ' + CurrentVideoDetail.ChannelName + '. Please purchase the channel to gain access to the video.';
                                                btnPurchaseProduct = '<div><button type="button" class="btn btn-default premium_video_btn"   data-videoId="' + CurrentVideoDetail.VideoId + '" data-innerroutename="BuyChannel">Buy channel</button></div>';

                                                if (CurrentVideoDetail.EventDetails != null && CurrentVideoDetail.EventDetails.Price != '0') {
                                                    var PublishStartDatetime = CurrentVideoDetail.EventDetails.PublishStartDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishStartDate, CurrentVideoDetail.EventDetails.PublishStartTime) : "";
                                                    var CurrentDateTime = new Date();
                                                    var PublishEpiryDatetime = CurrentVideoDetail.EventDetails.PublishExpiryDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishExpiryDate, CurrentVideoDetail.EventDetails.PublishExpiryTime) : "";

                                                    if (data.LoginStatus == ResultStatus.Failed || !(CurrentVideoDetail.EventDetails.IsUserPurchasedPremiumEvent)) {
                                                        var eventHTML = GetEventDetails(PublishStartDatetime, CurrentDateTime, PublishEpiryDatetime, CurrentVideoDetail.EventDetails.IsHideRecord, CurrentVideoDetail.EventDetails.EventStatus, CurrentVideoDetail.EventDetails.eventVideoDetails, CurrentVideoDetail.EventDetails.Title, 'btnVisible', data.Message);

                                                        premiumEventDetail = eventHTML.premiumEventDetail;
                                                        btnPurchaseEvent = eventHTML.btnPurchaseEvent;

                                                        $("#spnEventName").text(CurrentVideoDetail.EventDetails.Title);
                                                        $("#tblEventvideoDetails").html(CurrentVideoDetail.EventDetails.eventVideoDetails);
                                                        $('#tblEventvideoDetails').paging({ limit: 5 });

                                                        if ($(window).width() < 500) {
                                                            $("#divVideoContainer").addClass('premiumVideoWithBuyEvent');
                                                            $(".paging-nav").addClass('paginationDiv');
                                                            $("#divEventDetails").addClass('divBuyEvent');
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        else if (CurrentVideoDetail.PriceType == 'Premium') {
                                            videoType = 'This is a premium video. You can purchase this video for only £' + CurrentVideoDetail.PremiumPrice + ' excluding tax.';
                                            if (CurrentVideoDetail.PremiumDiscountPercentage != '0' && CurrentVideoDetail.PremiumDiscountAmount != '0') {
                                                premiumPriceDetailFirst = 'This is a premium video. You have a ' + CurrentVideoDetail.PremiumDiscountPercentage + '% discount on this video.'
                                                premiumPriceDetailSecond = 'Your new purchase price for this video is only £' + CurrentVideoDetail.PremiumDiscountAmount + ' excluding tax.';
                                            }
                                            btnPurchaseProduct = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyVideoPrompt">Buy video</button></div>';
                                            if (CurrentVideoDetail.PremiumDiscountPercentage != '0' && CurrentVideoDetail.PremiumDiscountAmount != '0') {
                                                $("#spnPremiumPrice").text(CurrentVideoDetail.PremiumDiscountAmount);
                                            }
                                            else {
                                                $("#spnPremiumPrice").text(CurrentVideoDetail.PremiumPrice);
                                            }
                                            $(".btnCheckOutRedirect").attr({
                                                "data-lastRouteName": 'videoid',
                                                "data-innerroutename": 'address',
                                                "data-videono": CurrentVideoDetail.VideoNo
                                            });

                                            if (CurrentVideoDetail.EventDetails != null && CurrentVideoDetail.EventDetails.Price != '0') {
                                                var PublishStartDatetime = CurrentVideoDetail.EventDetails.PublishStartDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishStartDate, CurrentVideoDetail.EventDetails.PublishStartTime) : "";
                                                var CurrentDateTime = new Date();
                                                var PublishEpiryDatetime = CurrentVideoDetail.EventDetails.PublishExpiryDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishExpiryDate, CurrentVideoDetail.EventDetails.PublishExpiryTime) : "";

                                                if ((data.LoginStatus == ResultStatus.Failed && CurrentVideoDetail.EventDiscount > 0) ||
                                                    (!(CurrentVideoDetail.EventDetails.IsUserPurchasedPremiumEvent) && (CurrentVideoDetail.PremiumDiscountPercentage == 0 && (CurrentVideoDetail.DiscountType == 'No Discount')) && CurrentVideoDetail.EventDiscount > 0)) {
                                                    var eventHTML = GetEventDetails(PublishStartDatetime, CurrentDateTime, PublishEpiryDatetime, CurrentVideoDetail.EventDetails.IsHideRecord, CurrentVideoDetail.EventDetails.EventStatus, CurrentVideoDetail.EventDetails.eventVideoDetails, CurrentVideoDetail.EventDetails.Title, 'btnVisible', data.Message);

                                                    premiumEventDetail = eventHTML.premiumEventDetail;
                                                    btnPurchaseEvent = eventHTML.btnPurchaseEvent;

                                                    $("#spnEventName").text(CurrentVideoDetail.EventDetails.Title);
                                                    $("#tblEventvideoDetails").html(CurrentVideoDetail.EventDetails.eventVideoDetails);
                                                    $('#tblEventvideoDetails').paging({ limit: 5 });

                                                    if ($(window).width() < 500) {
                                                        $("#divVideoContainer").addClass('premiumVideoWithBuyEvent');
                                                        $(".paging-nav").addClass('paginationDiv');
                                                        $("#divEventDetails").addClass('divBuyEvent');
                                                    }
                                                }

                                                if (CurrentVideoDetail.EventDiscount < 100) {
                                                    $('#rdoEvent').attr('onclick', 'return false;');
                                                    $('#rdoEvent').addClass('disabledinput');
                                                    $('#rdoEventSpan').addClass('disabledEventSpan');
                                                }
                                            }
                                        }
                                        else if (CurrentVideoDetail.PriceType == 'Event Priced' && CurrentVideoDetail.EventDetails.Price != '0') {
                                            var PublishStartDatetime = CurrentVideoDetail.EventDetails.PublishStartDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishStartDate, CurrentVideoDetail.EventDetails.PublishStartTime) : "";
                                            var CurrentDateTime = new Date();
                                            var PublishEpiryDatetime = CurrentVideoDetail.EventDetails.PublishExpiryDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishExpiryDate, CurrentVideoDetail.EventDetails.PublishExpiryTime) : "";

                                            var eventHTML = GetEventDetails(PublishStartDatetime, CurrentDateTime, PublishEpiryDatetime, CurrentVideoDetail.EventDetails.IsHideRecord, CurrentVideoDetail.EventDetails.EventStatus, CurrentVideoDetail.EventDetails.eventVideoDetails, CurrentVideoDetail.EventDetails.Title, 'EventPriced', data.Message);
                                            videoType = eventHTML.videoType;
                                            btnPurchaseProduct = eventHTML.btnPurchaseProduct;
                                        }
                                    }
                                    else {
                                        if (CurrentVideoDetail.PriceType == 'Subscription') {
                                            
                                            //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                                            if (data.Message != null && data.Message != null) {
                                                var messageViewModel = new MessageViewModel();
                                                messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                                messageViewModel.ShowOverLay();}
                                            
                                            //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end
                                            videoType = ' This video is part of paid channel ' + CurrentVideoDetail.ChannelName + '. Kindly contact the IET Administrator to gain access to this channel.';
                                        }
                                        else if (CurrentVideoDetail.PriceType == 'Premium') {
                                          
                                            //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                                            if (data.Message != null && data.Message != null) {
                                                var messageViewModel = new MessageViewModel();
                                                messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                                messageViewModel.ShowOverLay();
                                            }
                                            
                                            //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end
                                            videoType = 'This is a premium video. Kindly contact the IET Administrator to gain access to this video.';
                                            if (CurrentVideoDetail.EventDetails != null && CurrentVideoDetail.EventDetails.Price != '0') {
                                                if ((data.LoginStatus == ResultStatus.Failed) || (!(CurrentVideoDetail.EventDetails.IsUserPurchasedPremiumEvent) && (CurrentVideoDetail.PremiumDiscountPercentage == 0 && (CurrentVideoDetail.DiscountType == 'No Discount' || CurrentVideoDetail.DiscountType == null)))) {
                                                    if (CurrentVideoDetail.EventDiscount < 100) {
                                                        $('#rdoEvent').attr('onclick', 'return false;');
                                                        $('#rdoEvent').addClass('disabledinput');
                                                        $('#rdoEventSpan').addClass('disabledEventSpan');
                                                    }
                                                }
                                            }
                                        }
                                        else if (CurrentVideoDetail.PriceType == 'Event Priced' && CurrentVideoDetail.EventDetails.Price != '0') {
                                            var PublishStartDatetime = CurrentVideoDetail.EventDetails.PublishStartDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishStartDate, CurrentVideoDetail.EventDetails.PublishStartTime) : "";
                                            var CurrentDateTime = new Date();
                                            var PublishEpiryDatetime = CurrentVideoDetail.EventDetails.PublishExpiryDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishExpiryDate, CurrentVideoDetail.EventDetails.PublishExpiryTime) : "";

                                            var eventHTML = GetEventDetails(PublishStartDatetime, CurrentDateTime, PublishEpiryDatetime, CurrentVideoDetail.EventDetails.IsHideRecord, CurrentVideoDetail.EventDetails.EventStatus, CurrentVideoDetail.EventDetails.eventVideoDetails, CurrentVideoDetail.EventDetails.Title, 'btnInvisible', data.Message);

                                            videoType = eventHTML.videoType;
                                        }
                                    }
                                    premiumhtml = '<div id="premium_video_text" class="premium_video_text premium_video_mobile_text col-md-10" style="text-align:center">'
                                    if (CurrentVideoDetail.ChannelCategoryTypeId == 1 || ((CurrentVideoDetail.ChannelCategoryTypeId == 2 || CurrentVideoDetail.ChannelCategoryTypeId == 3) && CurrentVideoDetail.PriceType == 'Premium')) {
                                        if (premiumPriceDetailFirst == '' && premiumPriceDetailSecond == '') {
                                            premiumhtml += '<p>' + videoType + ' </p>' + btnPurchaseProduct;
                                        }
                                        else {
                                            premiumhtml += '<p>' + premiumPriceDetailFirst + ' </p>' + '<p>' + premiumPriceDetailSecond + ' </p>' + btnPurchaseProduct;
                                        }

                                        if (premiumEventDetail != '') {
                                            premiumhtml += '<p class="margin-top-10">' + premiumEventDetail + '</p>' + btnPurchaseEvent;
                                        }
                                        if (CurrentVideoDetail.PriceType == 'Premium' || CurrentVideoDetail.PriceType == 'Subscription' || (CurrentVideoDetail.PriceType == 'Event Priced' && CurrentVideoDetail.EventDetails.Price != '0')) {
                                            if (data.LoginStatus == ResultStatus.Failed) {
                                                premiumhtml += '<div class="margin-top-10"> Already bought this video? To view please <a href="view/LoginNew.html">Log in</a></div>';
                                            }
                                        }
                                    }

                                    if (CurrentVideoDetail.EventDetails != null) {
                                        if (CurrentVideoDetail.EventDetails.MemberDiscount != '0' && CurrentVideoDetail.EventDetails.DiscountAmount > 0) {
                                            $("#spnPremiumEventPrice").text(CurrentVideoDetail.EventDetails.DiscountAmount);
                                        }
                                        else {
                                            $("#spnPremiumEventPrice").text(CurrentVideoDetail.EventDetails.Price);
                                        }

                                        $(".btnEventCheckOutRedirect").attr({
                                            "data-lastRouteName": 'videoid',
                                            "data-innerroutename": 'address',
                                            "data-eventid": CurrentVideoDetail.EventDetails.Id,
                                            "data-videono": CurrentVideoDetail.VideoNo
                                        });
                                    }
                                }
                                //else {
                                if (CurrentVideoDetail.IndividualUserType != "member" && CurrentVideoDetail.IndividualUserType != "student") {
                                    if ((CurrentVideoDetail.ChannelCategoryTypeId == 2 || CurrentVideoDetail.ChannelCategoryTypeId == 3) && CurrentVideoDetail.PriceType == 'Subscription') {
                                        premiumhtml += "<div class='margin-top-10'>This video is part of Members/Students channel. To view these, please  <a onclick=OpenURL('http://www.theiet.org/membership/join/index.cfm')>join the IET</a>. Already a Member? To view,  <a href='view/LoginNew.html'>please log in</a></div>"
                                    }
                                }
                                else {
                                    if (data.LoginStatus == ResultStatus.Successful) {
                                        if (CurrentVideoDetail.ChannelCategoryTypeId == 2 && CurrentVideoDetail.IndividualUserType == "member" && CurrentVideoDetail.PriceType == 'Subscription') {
                                            premiumhtml += "<div class='margin-top-10'> This video is part of Students channel. To view these, please <a onclick=OpenURL('http://www.theiet.org/membership/join/index.cfm')>join the IET</a>. Already a Student Member? To view, <a href='view/LoginNew.html'>please log in</a></div>"
                                        }
                                        if (CurrentVideoDetail.ChannelCategoryTypeId == 3 && CurrentVideoDetail.IndividualUserType == "student" && CurrentVideoDetail.PriceType == 'Subscription') {
                                            premiumhtml += "<div class='margin-top-10'> This video is part of Members channel. To view these, please <a onclick=OpenURL('http://www.theiet.org/membership/join/index.cfm')>join the IET</a>. Already a Member? To view, <a href='view/LoginNew.html'>please log in</a></div>"
                                        }
                                    }
                                }

                                if (CurrentVideoDetail.PriceType == 'Premium' || CurrentVideoDetail.PriceType == 'Subscription' || (CurrentVideoDetail.PriceType == 'Event Priced' && CurrentVideoDetail.EventDetails.Price != '0')) {
                                    premiumhtml += '<div style="margin-top:10px">If you have an Access Code, Please enter code <a href="" data-toggle="modal" data-target="#modal_SingleAccessCode">here</a></div>';
                                }

                                //console.log(premiumhtml);
                                $(".video-overlay-div").addClass('alpha30');
                                $(".video-overlay-text").html(premiumhtml);
                                //var premium_video_div_height = getDivHeight($("#premium_video_text").height());
                                //var height_premium_text = $(".videoBtns").height() / 2;
                                var premium_video_div_height = getDivHeight($("#premium_video_text").height());
                                var t = $(".videoBtns").height() / 2;
                                $("div#premium_video_text").css("margin-top", "-" + premium_video_div_height - t);

                                $('#lockBtn').addClass('cursor-default');
                                $(window).resize(function () {
                                    /* to adjust overlay text */

                                    //if ($('.video-overlay-div').width() < 450) {
                                    //    $("div#premium_video_text").css("margin-top", "-" + $('.video-overlay-div').height()/2);
                                    //}
                                    //else {
                                    var premium_video_div_height = getDivHeight($("#premium_video_text").height());
                                    var t = $(".videoBtns").height() / 2;
                                    $("div#premium_video_text").css("margin-top", "-" + premium_video_div_height - t);
                                    //}
                                });

                                // console.log('===' + premium_video_div_height);

                                //handleEventQnA();
                                routeProvider.bindRoutes();
                                videoContext.BindPlaybtnClick();
                            }
                            else {
                                if (!IsNullOrEmpty(videoFilter.AccessCode)) {
                                    sessionStorage.setItem("accessCodeFlag", true);

                                    if (IsNullOrEmpty(sessionStorage.getItem("LogonId")) == true) {
                                        if (parseInt(sessionStorage.getItem("accessCodeType")) == 1) {
                                            //localStorage.setItem("Welcome", sessionStorage.getItem("delegateName"));
                                        }
                                        else {
                                            if (data.ResultObject.AccessSpeaker != null) {
                                                localStorage.setItem("Welcome", data.ResultObject.AccessSpeaker.FirstName + " " + data.ResultObject.AccessSpeaker.LastName);
                                            }
                                        }
                                        //Additional login to check if user is login then only set the login options
                                        if (!IsNullOrEmpty(localStorage.getItem("LoginStatus")) && localStorage.getItem("LoginStatus") !== "-1") {
                                            var objLoginRepository = new LoginRepository();
                                            objLoginRepository.setMessageForSpeaker();
                                        }
                                    }
                                }
                            }
                            //var desc = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
                            //$("#videoDescription").html(AddReadMore(CurrentVideoDetail.Abstract));
                            //$("#videoDescription").html(desc);
                            $("#videoDescription").html(CurrentVideoDetail.Abstract);
                            //$("#videoDescription").html('<p>Phasellus lorem lacus, vestibulum a tristiquePhasellus lorem lacus, vestibulum a tristiquePhasellus lorem lacus, vestibulum a tristiquePhasellus lorem lacus, vestibulum a tristiquePhasellus lorem lacus, vestibulum a tristiquePhasellus lorem lacus, vestibulum a tristique</p> <p>ut, consectetur sit amet nisl. Maecenas nec metus vel libero aliquet accumsan. Nunc vel sem ac justo hendrerit sagittis.</p><p>Proin nec ultrices dui. Aliquam justo nibh, malesuada ac lacinia eget, tempor eget dolor. Mauris finibus magna at lacus gravida, vehicula iaculis ex efficitur. Integer eu sapien at leo rhoncus sodales. Proin tincidunt quam eu molestie semper. Donec elementum,</p> <p>ligula aliquam porttitor ultrices, sapien lorem cursus lorem, non molestie ligula neque ut velit. Aliquam laoreet, leo eget ultrices sagittis, felis mauris varius nulla, quis interdum est leo non est. Ut fermentum ante est, a feugiat nisi bibendum a. Etiam euismod ultrices hendrerit. Aenean et eros a urna placerat volutpat sed id lectus. Suspendisse ultricies ornare accumsan. Ut nulla enim, pharetra in hendrerit sed, fringilla ultricies purus. Ut tristique orci purus, vitae dapibus est malesuada aliquet.</p>');
                            // $('.morelink').click(toogleReadMoreLess);
                            $(".video-main-caption").html(truncateString(CurrentVideoDetail.Title, 58))
                            $(".div_Videotitle").text(truncateString(CurrentVideoDetail.Title, 58))
                            if (CurrentVideoDetail.HasPromo == false) {
                                $(".video-main-time").html(CurrentVideoDetail.Duration);
                            }

                            if (CurrentVideoDetail.IsPartofEvent) {
                                var PublishStartDatetime = CurrentVideoDetail.EventDetails.PublishStartDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishStartDate, CurrentVideoDetail.EventDetails.PublishStartTime) : "";
                                var CurrentDateTime = new Date();
                                var PublishEpiryDatetime = CurrentVideoDetail.EventDetails.PublishExpiryDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishExpiryDate, CurrentVideoDetail.EventDetails.PublishExpiryTime) : "";

                                if (CurrentVideoDetail.EventDetails.IsHideRecord == true) {
                                    $(".eventdetails").addClass("display-none");
                                }
                                else {
                                    if (CurrentVideoDetail.EventDetails.EventStatus == 1) {
                                        if (PublishStartDatetime != "" && PublishEpiryDatetime != "") {
                                            if (PublishEpiryDatetime > CurrentDateTime) {
                                                $(".eventdetails").removeClass("display-none");
                                                $("#eventname")
                                                    .attr({
                                                        "data-eventid": CurrentVideoDetail.EventDetails.Id
                                                        , "title": CurrentVideoDetail.EventDetails.Title
                                                        , "href": "?event=" + CurrentVideoDetail.EventDetails.Id
                                                    });
                                                $("#eventname").text(CurrentVideoDetail.EventDetails.Title);
                                            }
                                            else if (PublishEpiryDatetime < CurrentDateTime) {
                                                $(".eventdetails").addClass("display-none");
                                            }
                                        }
                                        else if (PublishStartDatetime != "" && PublishEpiryDatetime == "") {
                                            $(".eventdetails").removeClass("display-none");
                                            $("#eventname")
                                                .attr({
                                                    "data-eventid": CurrentVideoDetail.EventDetails.Id
                                                    , "title": CurrentVideoDetail.EventDetails.Title
                                                    , "href": "?event=" + CurrentVideoDetail.EventDetails.Id
                                                });
                                            $("#eventname").text(CurrentVideoDetail.EventDetails.Title);

                                            //else if (PublishStartDatetime > CurrentDateTime) {
                                            //    $(".eventdetails").removeClass("display-none");
                                            //    $("#eventname").removeAttr("href");
                                            //    $("#eventname").removeAttr("data-innerroutename");
                                            //    $("#eventname").css("text-decoration", "none");
                                            //    $("#eventname").css("cursor", "default");
                                            //    $("#eventname").text(CurrentVideoDetail.EventDetails.Title);
                                            //}
                                        }
                                    }
                                    else {
                                        $(".eventdetails").addClass("display-none");
                                    }
                                }
                            }

                            if (CurrentVideoDetail.IsSeries && CurrentVideoDetail.SeriesDetailsList.length > 0) {
                                $("#serieslist").removeClass("display-none");
                                seriesRouteName = 'series';
                                var seriesHTML = "";
                                for (i = 0; i < CurrentVideoDetail.SeriesDetailsList.length; i++) {
                                    var series = CurrentVideoDetail.SeriesDetailsList[i];

                                    if (seriesHTML.length > 0) {
                                        seriesHTML += ', ';
                                    }
                                    //seriesHTML += '<a class="font-size-12 text-color" data-hasindex="true" data-innerroutename=\"' + seriesRouteName + '\" data-seriesId=\'' + series.SeriesId + '\'style="cursor:pointer">' + series.SeriesName + '</a>';
                                    seriesHTML += '<a class="font-size-12 text-color disablehreflink" data-hasindex="true" data-innerroutename=\"' + seriesRouteName + '\" data-seriesId=\'' + series.SeriesId + '\' style="cursor: pointer" href="?series=' + series.SeriesId + '">' + series.SeriesName + '</a>';
                                }
                                $("#serieslist").append(seriesHTML);
                            }

                            var entryid = CurrentVideoDetail.EntryId;
                            var url = window.location.href;
                            var embedLink = url.substring(0, url.lastIndexOf('/') + 1) + "EmbedPlayer.aspx?videoid=" + videoFilter.VideoNo + "&guid=" + this.CurrentVideoDetail.VideoId;
                            var embedurl = '<iframe width="550" height="310" name="' + entryid + '" src="' + embedLink + '" allowfullscreen></iframe>';
                            var facebookTwitterLink = url.substring(0, url.lastIndexOf('/') + 1) + "EmbedPlayer.aspx?videoid=" + videoFilter.VideoNo + "&guid=" + this.CurrentVideoDetail.VideoId;
                            //SEO
                            var seoMetaData = {};
                            seoMetaData.embedLink = embedLink;
                            seoMetaData.videoDate = CurrentVideoDetail.VideoDate;
                            seoMetaData.thumbnailUrl = CurrentVideoDetail.DisplayImage;
                            //if (CurrentVideoDetail.Permissions[0].VideoThumbnailURL != "" && CurrentVideoDetail.Permissions[0].VideoThumbnailURL != null) {
                            //    seoMetaData.thumbnailUrl = CurrentVideoDetail.Permissions[0].VideoThumbnailURL;
                            //}
                            //else
                            //{
                            //    seoMetaData.thumbnailUrl = CurrentVideoDetail.Permissions[0].VideoThumbnailBannerURL;
                            //}
                            _this.setSeoVideoSchema(seoMetaData);
                            $("input[name='txtembed']").val(embedurl);
                            $("input[name='txtFacebookTwitter']").val(facebookTwitterLink);

                            //speaker
                            var speakersection = ''
                            if (CurrentVideoDetail.Speakers != null) {
                                $.each(CurrentVideoDetail.Speakers, function (index, speaker) {
                                    var SpeakerImage = '';
                                    if (speaker.PictureUrl.indexOf("$") != -1) {
                                        SpeakerImage = speaker.PictureUrl.slice(0, speaker.PictureUrl.lastIndexOf("$"));
                                    }
                                    else
                                        SpeakerImage = CurrentVideoDetail.SpeakerImageSource + speaker.PictureUrl;

                                    speakersection += SpeakerHTML(index, speaker.Title, speaker.FirstName, speaker.LastName, SpeakerImage);

                                    $(".carousel-inner").html(speakersection);
                                });
                            }

                            //keyword logic
                            var keywordsection = '';
                            var inspeckeywordsection = '';
                            if (CurrentVideoDetail.Keywordlist.length != 0) {
                                $.each(CurrentVideoDetail.Keywordlist, function (index, keyword) {
                                    if (keyword.KeywordType == "custom") {
                                        keywordsection += KeywordHTML(keyword.KeywordName, keyword.KeywordId);
                                    }
                                    else {
                                        inspeckeywordsection += KeywordHTML(keyword.KeywordName, keyword.KeywordId);
                                    }
                                });
                            }
                            if (keywordsection != '') {
                                $('.custom-keywords').html("Custom Keywords");
                            }
                            if (inspeckeywordsection != '') {
                                $('.inspec-keywords').html("Inspec Keywords");
                            }
                            $(".video-keywords-container").html(keywordsection);
                            $(".inspec-video-keywords-container").html(inspeckeywordsection);

                            //channel list
                            if (CurrentVideoDetail.ChannelList != null) {
                                var channelSectionHtml;
                                var channelSectionHtml_title;
                                channelSectionHtml_title = '<h1  class="title_video" style="padding-left:2px"><span itemprop="name"><strong>' + CurrentVideoDetail.Title + '</strong></span></h1>';
                                channelSectionHtml = '<div class="margin-right-15 float-left" style="padding-top: 4px"> This video is from: </div>';
                                $.each(CurrentVideoDetail.ChannelList, function (index, channel) {
                                    channelSectionHtml += ChannelHTMLVideo(channel.Name, channel.Id, channel.ChannelIconImage, channel.Duration, channel.SubscriptionType);
                                });
                            }

                            $("#videoChannel").html(channelSectionHtml);
                            $("#Video_Title").html(channelSectionHtml_title);
                            $('#backgroundImage').attr("src", CurrentVideoDetail.DisplayImage);
                            //$('#backgroundImage').attr("alt", CurrentVideoDetail.Title);
                            $('#outer_background_image').css("background-image", "url('" + CurrentVideoDetail.DisplayImage + "')");
                            //if (CurrentVideoDetail.Permissions[0].VideoThumbnailURL != "" && CurrentVideoDetail.Permissions[0].VideoThumbnailURL != null) {
                            //    $('#outer_background_image').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailURL + "')");
                            //    $('#backgroundImage').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailURL + "')");

                            //}
                            //else {
                            //    $('#outer_background_image').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailBannerURL + "')");
                            //    $('#backgroundImage').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailBannerURL + "')");
                            //}

                            if (!CurrentVideoDetail.HasLock) {
                                //player logic
                                //this.PlayerDetail = {
                                //    PartnerId: KPlayerDetails.PartnerId,
                                //    PlayerId: KPlayerDetails.PlayerId,
                                //    CacheStrng: KPlayerDetails.PlayerCacheString,
                                //    EntryId: CurrentVideoDetail.EntryId,
                                //    Ks: KPlayerDetails.PlayerSession
                                //};
                            }

                            $.ajax({
                                url: 'Script/jquery.countdown.js',
                                async: false,
                                dataType: "script",
                                success: function (jsonData) {
                                }
                            });

                            if (CurrentVideoDetail.HasPromo == true) {
                                if (data.ResultObject.PromoType.toLowerCase() != "video") {
                                    $("#playBtn").addClass('cursor-default');
                                }
                                _this.AllowDownload(false);
                                _this.CanLikeDislike1(false);
                                var PromoDetail = {
                                    HasCountdown: videoDetail.HasCountdownStatus,
                                    CountDateTime: videoDetail.CountdownDateTime
                                }

                                if (PromoDetail.HasCountdown == true) {
                                    //var currentDate = new date();
                                    //countlogic
                                    if (!IsNullOrEmpty(videoDetail.CountdownUTCDateTime) && !IsNullOrEmpty(videoDetail.FinalPublishDateTime)) {
                                        var currentDateTime = new Date();

                                        //Assign DateTime in UTC to Jquery Object
                                        var FinalPublishUTCDateObject = videoDetail.FinalPublishDateTime;
                                        var CountDownUTCDateObject = videoDetail.CountdownUTCDateTime;

                                        //This will give client time zone specific DateTime
                                        var utcFinalPublishDateTime = new Date(Date.UTC(FinalPublishUTCDateObject.YearPartOfDate, FinalPublishUTCDateObject.MonthPartOfDate - 1, FinalPublishUTCDateObject.DayPartOfDate, FinalPublishUTCDateObject.HourPartOfDate, FinalPublishUTCDateObject.MinutePartOfDate, FinalPublishUTCDateObject.SecondPartOfDate));
                                        var utcCountdownUTCDateTime = new Date(Date.UTC(CountDownUTCDateObject.YearPartOfDate, CountDownUTCDateObject.MonthPartOfDate - 1, CountDownUTCDateObject.DayPartOfDate, CountDownUTCDateObject.HourPartOfDate, CountDownUTCDateObject.MinutePartOfDate, CountDownUTCDateObject.SecondPartOfDate));

                                        var localDate = new Date()
                                        var offsetToUTC = localDate.getTimezoneOffset();

                                        var zoneDiff;

                                        if (offsetToUTC != 0) {
                                            zoneDiff = -(offsetToUTC / 60);
                                        }
                                        else {
                                            zoneDiff = 0;
                                        }

                                        if (currentDateTime > utcCountdownUTCDateTime && currentDateTime <= utcFinalPublishDateTime) {
                                            //This has to be universal time as the CountDown plugin auto calculates the CountDown datetime depending upon the browser's TimeZone
                                            //var CountDownClientDateObject = new Date(CountDownUTCDateObject.YearPartOfDate, CountDownUTCDateObject.MonthPartOfDate - 1, CountDownUTCDateObject.DayPartOfDate, CountDownUTCDateObject.HourPartOfDate, CountDownUTCDateObject.MinutePartOfDate, CountDownUTCDateObject.SecondPartOfDate);
                                            //var FinalPublishClientDateObject = new Date(FinalPublishUTCDateObject.YearPartOfDate, FinalPublishUTCDateObject.MonthPartOfDate - 1, FinalPublishUTCDateObject.DayPartOfDate, FinalPublishUTCDateObject.HourPartOfDate, FinalPublishUTCDateObject.MinutePartOfDate, FinalPublishUTCDateObject.SecondPartOfDate);

                                            if ($('#countDown').countdown != null) {
                                                $('#countDown').countdown({ until: utcFinalPublishDateTime, timezone: zoneDiff, compact: true, onExpiry: _this.ExecCountDownExpiry });
                                                $('#countDown').css("display", "block");
                                            }
                                        }
                                    }
                                }
                            }
                            //lock functionality
                            _this.CheckLock(CurrentVideoDetail.HasLock);
                            if (CurrentVideoDetail.HasPromo == false) {
                                _this.AllowDownload(CurrentVideoDetail.AllowDownload);
                                _this.CanLikeDislike1(CurrentVideoDetail.CanLikeDislike);
                            }
                            _this.RenderAttachment(CurrentVideoDetail.AllowAttachmentDownload);
                            _this.RenderTranscript(CurrentVideoDetail.AllowAttachmentDownload);
                            _this.RenderIETDigitalLibrary(CurrentVideoDetail.DigitalLibrary);
                            //_this.RenderComments(CurrentVideoDetail.Comments, CurrentVideoDetail.IsCommentsEnable, false);
                            //_this.CommentsEnableDisable(CurrentVideoDetail.IsCommentsEnable);
                            _this.ShowRelatedContent(CurrentVideoDetail.RelatedContent);
                            //below HideVideo function not required
                            // _this.HideVideo(false);
                            if (CurrentVideoDetail.HasUserAccess) {
                                //_this.RenderAttachment(true);
                                var lastactivity = videoDetail.LastLikeDislikeActivity;
                                //do not set HideLikeDislike and hidedownload
                                if (CurrentVideoDetail.CanLikeDislike) {
                                    _this.ToggleLikeDislike(lastactivity);
                                }
                            }

                            VideoRenderScript();
                            $('.modal-backdrop').remove();
                            routeProvider.bindInnerRoutes();
                            if (!WebService.DisableGA) {
                                storeurlDetailsInGA('Video Title - ' + CurrentVideoDetail.Title);
                            }
                            videoContext.BindPlaybtnClick();
                        }
                        else {
                            //not access logic

                            _this.CheckLock(CurrentVideoDetail.HasLock);
                            _this.AllowDownload(CurrentVideoDetail.AllowDownload);
                            _this.CanLikeDislike1(CurrentVideoDetail.CanLikeDislike);
                            _this.RenderAttachment(CurrentVideoDetail.AllowAttachmentDownload);
                            _this.RenderTranscript(CurrentVideoDetail.AllowAttachmentDownload);
                            _this.CommentsEnableDisable(CurrentVideoDetail.IsCommentsEnable)
                        }
                        //}

                        var KeyWordsString = [];

                        if (!IsNullOrEmpty(CurrentVideoDetail.Keywordlist)) {
                            if (CurrentVideoDetail.Keywordlist.length > 0) {
                                //if (CurrentVideoDetail.Keywordlist.length > 0) {
                                //    for (i = 0; i < CurrentVideoDetail.Keywordlist.length; i++) {
                                //        //KeyWordsString += CurrentVideoDetail.Keywordlist[i].KeywordName + ' OR ';
                                //        KeyWordsString.push(CurrentVideoDetail.Keywordlist[i].KeywordName);
                                //    }

                                //    var KeyWordsQuery = '["' + KeyWordsString.join('"] OR ["') + '"]';

                                //console.log(KeyWordsQuery);

                                var googleSearch = new GoogleSearch();
                                //googleSearch.SearchTerm = KeyWordsQuery;
                                googleSearch.Init(CurrentVideoDetail.VideoNo);
                                // }
                            }
                        }

                        if (!WebService.DisableChat) {
                            if (CurrentVideoDetail.IsLive) {
                                var qna = new QnA();
                                qna.submitMessage();
                                qna.Init('Video', true);

                                //var hub = qna.Chat;

                                qna.QnARepository.GetMessagesForGroup(qna.GroupName);
                                qna.QnARepository.GetAllAbusiveWords();
                            }
                            else {
                                //var qna = new QnA();
                                //qna.Init('Video', false);

                                //qna.QnARepository.GetMessagesForGroup(qna.GroupName);
                                ////$('.QnA-main').attr('disabled', 'disabled');
                                //$('#txtMessage').val('Q&A for the video is now closed');
                                //$('#txtMessage').attr('disabled', 'disabled');
                                //$('#btn_reply').removeClass('custom_pointer');
                            }

                            VideoIsDisplayQA = CurrentVideoDetail.IsQnAEnabled;
                        }

                        if (CurrentVideoDetail.IsLive) {
                            var poll = new Poll();
                            poll.Init('Video');

                            VideoIsDisplayPolling = CurrentVideoDetail.IsPollingEnabled;
                        }

                        //VideoIsDisplayQA = CurrentVideoDetail.IsQnAEnabled;
                        //VideoIsDisplayPolling = CurrentVideoDetail.IsPollingEnabled;

                        //console.log('Videorepo' + PollQuestionAvailable);

                        if (PollQuestionAvailable == 0) {
                            //This is to analyze the flow

                            VideoIsDisplayPolling = false;
                        }

                        if (VideoIsDisplayQA == 1) {
                            QnAVisibleVideo = 1;
                        }
                        else {
                            QnAVisibleVideo = 0;
                        }

                        if (VideoIsDisplayPolling == 1) {
                            PollVisibleVideo = 1;
                        }
                        else {
                            PollVisibleVideo = 0;
                        }

                        if (VideoIsDisplayQA == 1 && VideoIsDisplayPolling == 1) {
                            QnAVisibleVideo = 0;
                        }

                        //flag to check if QnA is available  for this event
                        QnAAvailableVideo = VideoIsDisplayQA;
                        //flag to check if QnA is visible

                        if (WebService.DisableChat) {
                            QnAAvailableVideo = false;
                        }

                        //flag to check if Poll is available for this event
                        PollAvailableVideo = VideoIsDisplayPolling;
                        //flag to check if Poll is visible

                        onVideoPageLoad();

                        PollQuestionAvailable = 0;

                        //Stop the loader and open up the UI before lazy loading the other contents
                        Spinner.Stop();

                        $('.overlay').hide();

                        videoFilter.VideoId = CurrentVideoDetail.VideoId;

                        _this.getRelatedVideos(currentRouteSetting, routeProvider, routeCurrentContext, videoFilter, videoContext);
                        _this.getComments(currentRouteSetting, routeProvider, routeCurrentContext, videoFilter, videoContext);
                        _this.getRelatedContent(currentRouteSetting, routeProvider, routeCurrentContext, videoFilter, videoContext);

                        var StreamingEnd = CurrentVideoDetail.StreamingEnd;

                        if (StreamingEnd == true) {
                            $("#playBtn").unbind();
                            $("#playBtn").attr("src", "Images/Disable.png");
                            $("#playBtn").css('cursor', 'default');
                            $("#btnVideoLike").attr("disabled", "disabled");
                            $("#btnVideoDisLike").attr("disabled", "disabled");
                        }
                        /// Author: Sanjana
                        /// Date: 23-08-2017
                        /// Decription: store clip start and end time in session and perform required action
                        //PS - 1252: IET - TV: Issue in myclips functionality start:Comment beow code
                        //if (videoFilter.ClipId > 0) {
                        //    $("#playBtn").css("display", "none");
                        //    VideoRepository.getCurrentVideoByClipId(currentRouteSetting, routeProvider, routeCurrentContext, videoFilter, _this);
                        //}
                        //PS - 1252: IET - TV: Issue in myclips functionality  end
                        $(document).ready(function () {
                            var eviSearchPagination = parseBool(localStorage.getItem("eviSearchRoute"));
                            if (eviSearchPagination && sessionStorage.getItem("searchTranscriptTerm") != "" && !CurrentVideoDetail.HasLock) {
                                if ($(window).width() < 992) {
                                    $('.transcript-toggle').trigger("click");
                                }
                                else {
                                    $('.transcript-increase').trigger("click");
                                }
                            }
                        });
                    }
                }
                else {
                    _this.showNotFoundMsg();
                    routeProvider.bindInnerRoutes();
                }
            }, function (data, status, headers, config) {
                var errMsg = IsNullOrEmpty(data.responseText) == true ? "" : $(data.responseText).find("Message")[0].innerHTML;

                if (errMsg.toLowerCase() == 'value was either too large or too small for an int64.' || errMsg.toLowerCase() == 'input string was not in a correct format.') {
                    _this.showNotFoundMsg();
                }
                else {
                    Spinner.Stop();
                    var messageViewModel = new MessageViewModel();
                    messageViewModel.CreateErrorMsgExceptStatus(errMsg);
                    messageViewModel.ShowOverLay();
                }
            }, JSON.stringify(videoFilter));
    },

    setSeoVideoSchema: function (seo) {
        var _this = this;
        //SEO
        $('meta[itemprop="embedURL"]').attr("content", seo.embedLink);
        //SEO
        $('meta[itemprop="thumbnailUrl"]').attr("content", seo.thumbnailUrl);
        //SEO
        $('link[itemprop="url"]').attr("href", seo.thumbnailUrl);
        //SEO
        $('meta[itemprop="uploadDate"]').attr("content", _this.SEOUploadDate(seo.videoDate));
    },
    SEOUploadDate: function (dt) {
        var _this = this;
        try {
            Date.prototype.isValid = function () {
                return this.getTime() === this.getTime();
            };
            var d = new Date(dt);
            if (d.isValid() === true) {
                return d.toISOString();
            }
            else {
                return new Date().toISOString();
            }
        }
        catch (e) {
            return new Date().toISOString();
        }
    },

    showNotFoundMsg: function () {
        var _this = this;
        // Below code will execute when video no does not exists.
        $('.video-details-menu').addClass('display-none');
        $('#LazyLoader').addClass('display-none');
        $('#LazyLoaderComments').addClass('display-none');
        $('#LazyLoaderRelatedContent').addClass('display-none');
        $("#videoDescription").html("Video not found!!");
        $("#videoDescription").css({ "font-size": "25px", "font-weight": "bold" })
        $('#backgroundImage').css("background-image", "url('Images/img_novideo.png')");
        $('#outer_background_image').css("background-image", "url('Images/img_novideo.png')");
        VideoRenderScript();
        $('.modal-backdrop').remove();
        _this.CheckLock(false);
        _this.AllowDownload(false);
        _this.CanLikeDislike1(false);
        _this.RenderAttachment(false);
        _this.RenderTranscript(false);
        _this.CommentsEnableDisable(false)
        $(".share-embed-qna-poll-icons-desktop-video").css('display', 'none');
        $(".share-embed-qna-poll-container-desktop").css('display', 'none');
        $("#related-content").hide();
        $("#related-videos").css('display', 'none');
        $(".comment-pagination").css('display', 'none');
        $("#ViewsCount").html("0 Play");
        $("#likevalue").html("0");
        $("#dislikevalue").html("0");
        $(".likevalue").html("0");
        $(".dislikevalue").html("0");
        $('.eventnotfound').hide();
        $('.IfVideoNotFound').hide();
        EviSearchMaintainToggleState();
    },

    getRelatedVideos: function (currentRouteSetting, routeProvider, routeCurrentContext, videoFilter, videoContext) {
        var _this = this;
        played = 0;
        var object = {
            Data: { "videoFilter": videoFilter }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetRelatedVideoForVideoLanding',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        var relatedVideosHTML = '';
                        relatedVideos = data.ResultObject;
                        if (relatedVideos != null && relatedVideos != '') {
                            //Rakesh :Related video Count
                            $('#spnRelatedVideos').html(relatedVideos.length);
                            $.each(relatedVideos, function (index, data) {
                                var time = new Date();
                                relatedVideosHTML += getRelatedVideoHTML(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.SubscriptionType, data.Duration, data.IsSeries, data.SeriesCount, data.SeriesCreatedYear);
                            });

                            $(document).ready($('#related-videos-dynamic').html(relatedVideosHTML));
                        }

                        $('#LazyLoader').addClass('display-none');
                        $('#related-videos-dynamic').removeClass('display-none');
                    }
                }
                routeProvider.bindInnerRoutes();
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(videoFilter))
    },

    getComments: function (currentRouteSetting, routeProvider, routeCurrentContext, videoFilter, videoContext) {
        var _this = this;
        played = 0;
        var object = {
            Data: { "videoFilter": videoFilter }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetCommentsForVideoLanding',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        _this.RenderComments(data.ResultObject, CurrentVideoDetail.IsCommentsEnable, false);
                        _this.CommentsEnableDisable(CurrentVideoDetail.IsCommentsEnable);

                        $('#LazyLoaderComments').addClass('display-none');
                        $('#comments-panel').removeClass('display-none');
                    }
                }
                routeProvider.bindInnerRoutes();
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(videoFilter))
    },

    getRelatedContent: function (currentRouteSetting, routeProvider, routeCurrentContext, videoFilter, videoContext) {
        var _this = this;
        played = 0;
        var object = {
            Data: { "videoFilter": videoFilter }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetRelatedContentForVideoLanding',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        _this.ShowRelatedContent(data.ResultObject);
                    }
                }
                routeProvider.bindInnerRoutes();
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(videoFilter))
    },

    CommentsEnableDisable: function (commentsIsEnable) {
        //  console.log(commentsIsEnable);
        if (commentsIsEnable == false) {
            $("#comments-panel :input").prop('disabled', true);
            $("#comments-panel :input").prop('title', 'Please login');
            //$("#comments-panel>a").css('pointer-events', 'none');
            //$("#comments-panel>a").css('cursor', 'default');
            // $("#comments-panel a").click(function () { return false });
            //$("#comments-panel").find('a') .prop('disabled', true);
        }
        else {
            $("#comments-panel :input").prop('disabled', false);
            $("#comments-panel :input").prop('title', '');
            // $("#comments-panel a").click(function () { return false });
            //$("#comments-panel > a").css('pointer-events', 'none');
            //$("#comments-panel > a").css('cursor', 'default');
            //  $("#comments-panel :a").prop('disabled', true);
            //  $("#comments-panel").find('a').prop('disabled', true);
        }
    },

    ExecCountDownExpiry: function () {
        $('#countDown').hide();
        window.location.reload(true);
    },

    DownloadVideo: function (currentRouteSetting, routeProvider, routeCurrentContext) {
        var _this = this;
        var video = CurrentVideoDetail;

        var Download = {
            Action: "Download",
            LogonId: BrowserStorage.getLogonId(),
            VideoID: video.VideoId,
            Type: "Video",
            VideoTitle: video.Title,
            Name: video.Title,
            ChannelID: video.ChannelId,
            EncodedAssetId: video.EncodedAssetId,
            SubscriptionType: video.PriceType,
            Duration: video.Duration,
            AccountId: localStorage.getItem('AccountId')
        };

        var object = {
            Data: { "download": Download }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetDownloadURL',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            var videodetail = data.ResultObject;
                            //window.location.href = videodetail;
                            //window.open(videodetail, '_blank');

                            $("#anchordwldlink").attr("href", videodetail);
                            $("#anchordwldlink")[0].click();
                        }
                    }
                }
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    /*code added for the download atytachemnt*/
    DownloadAttachment: function (currentRouteSetting, routeProvider, routeCurrentContext) {
        var _this = this;
        var video = CurrentVideoDetail;

        var Download = {
            Action: "AttachmentDownload",
            LogonId: BrowserStorage.getLogonId(),
            VideoID: video.VideoId,
            Type: "Attachment",
            VideoTitle: video.Title,
            //Name: video.Attachment,
            ChannelID: video.ChannelId,
            SubscriptionType: video.PriceType,
            Duration: video.Duration,
            EncodedAssetId: video.EncodedAssetId
        };

        var object = {
            Data: { "download": Download }
        };

        //console.log(Download);

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/DownloadAttachment',//DownloadLink',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            var videodetail = data.ResultObject;

                            window.location.href = videodetail;
                        }
                        else {
                        }
                    }
                }
                else {
                }
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    //NN
    GetSpeakerDetail: function (currentRouteSetting, routeProvider, routeCurrentContext, speakerid) {
        var _this = this;
        if (CurrentVideoDetail.Speakers != null) {
            $.each(CurrentVideoDetail.Speakers, function (index, speaker) {
                if (speaker.Id == speakerid) {
                    var SpeakerImage = '';
                    if (speaker.PictureUrl.indexOf("$") != -1) {
                        SpeakerImage = speaker.PictureUrl.slice(0, speaker.PictureUrl.lastIndexOf("$"));
                    }
                    else
                        SpeakerImage = CurrentVideoDetail.SpeakerImageSource + speaker.PictureUrl;

                    $('#speaker_image').attr("src", SpeakerImage);
                    $('#spkr_name').text(speaker.FirstName + " " + speaker.LastName);
                    $('#spkr_jobtitle').text(speaker.JobTitle);
                    $('#spkr_company_name').text(speaker.Organization);
                    $('#spkr_affiliations').text(speaker.Affiliation);
                    $('#spkr_biography').html(speaker.Biography)
                    $("#viewBioPrompt").modal({
                        backdrop: 'static',
                        keyboard: false
                    });
                    $("#viewBioPrompt").modal('show');
                    return false;
                }
            });
        }
    },

    PostComment: function (data) {
        $('#commentsubmit').attr('disabled', true);
        var resposne = '';
        var accessCodeUserName = '';
        if (data.Comment != undefined) {
            var commenttext = data.Comment.replace(/(['])/g, "''");
        }
        //var commenttext =data.Comment.replace(/'/g,/''/);
        var accessCodeType = sessionStorage.getItem("accessCodeType");
        if (accessCodeType == "2") {
            accessCodeUserName = localStorage.getItem("Welcome");
        }
        //else {
        //    accessCodeUserName = sessionStorage.getItem("delegateName");
        //}
        var req = {
            LogonId: data.LogonId,
            CommentText: data.Comment,
            VedioId: data.VideoID,
            AccessCode: sessionStorage.getItem("accessCode"),
            AccessCodeType: sessionStorage.getItem("accessCodeType"),
            AccessCodeUserName: accessCodeUserName
        };
        var object = {
            Data: { "req": req }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'CommentsManagment/CommentsManagment.svc/PostVerifiedComment',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status) {
                    var commentDetails = data.ResultObject;
                    VideoRepository.RenderComments(commentDetails, CommentsEnable, true);
                    $("#comment").val('');
                }
                else {
                    var messageViewModel = new MessageViewModel();
                    messageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId")
                    messageViewModel.ShowOverLay();
                }
                $('#commentsubmit').attr('disabled', false);
            },
            function (data, status, headers, config) {
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId")
                messageViewModel.ShowOverLay();

                $('#commentsubmit').attr('disabled', false);
            },
            JSON.stringify(object.Data));
    },

    RenderComments: function (commentDetails, commentsIsEnable, isPostComment) {
        var _this = this;
        var comments = ''
        var t = '';
        var showMoreLink = false;
        var anchorAction = '';
        var commentsTotalCount = 0;
        var nextViewCommentCount = 0;
        var icnt = 0;
        if (commentsIsEnable != undefined) {
            CommentsEnable = commentsIsEnable
        }
        var divVideoComments = $('.video-comments');
        $(divVideoComments).html('');
        $.each(commentDetails, function (index, data) {
            icnt = icnt + 1;
            var commentSelDate = "";
            if (data.CommentDate.indexOf('T') > 0) {
                //var commentdate = new Date(data.CommentDate);
                var commentdate = data.CommentDate.split('T')[0];
                var commenttime = data.CommentDate.split('T')[1];
                var commentHr = commenttime.split(':')[0];
                var commentMin = commenttime.split(':')[1];
                var commentdatepar = commentdate.split('-');
                //commentSelDate = commentdatepar[2] + '/' + commentdatepar[1] + '/' + commentdatepar[0];
                commentSelDate = commentdate + ' ' + commentHr + ':' + commentMin;
            }

            //var commentSelDate = data.CommentDate;
            commentsTotalCount = data.commentsTotalCount;
            var userName = "";
            if (data.AccountTypeId == "2" || data.AccountTypeId == "3") {
                userName = data.FirstName + ' ' + data.lastName + ' - ' + data.AccountName;
            }
            else if (data.AccountTypeId == "1") {
                userName = data.FirstName + ' ' + data.lastName;
            }
            else if (data.UserName != "") {
                userName = 'User from ' + data.AccountName;
            }
            else {
                userName = data.FirstName + ' ' + data.lastName;
            }

            if (data.show == 'yes') {
                if (commentsIsEnable == true) {
                    anchorAction = '<a class="font-size-11" onclick=SendCommentAbuseMail(' + data.ID + ',"' + data.VideoID + '"); ><span style="cursor:pointer" > Report abuse</span></a>';
                    //anchorAction = 'onclick=SendCommentAbuseMail(' + data.ID + ',"' + data.VideoID + '");'
                }
                else {
                    anchorAction = '<a class="font-size-11  btn disabled" style="text-decoration:none; padding:2px;" ><span style="cursor:none" > Report abuse</span></a>';
                }

                comments = '<div class="comment-heading col-md-12 no-padding "><div class="float-left no-padding">' +
                    '<span class="content-heading right-margin-10"> ' + userName + '</span> <span class="font-size-11 white-space right-margin-10 ">' + commentSelDate + '</span>' + anchorAction +
                    '<p id=divComments' + icnt + ' class="font-size-13"></p></div><div class="clearfix comment-bottom-line"></div>' +
                    '</div>';
            }
            else {
                comments = '<div class=" clearfix comment-heading col-md-12 no-padding  margin-bottom-10"><div class="float-left no-padding" >' +
                    '<span class=" font-bold right-margin-10 font_size_12">' + data.ReplacementTextForHiddenComment + ' </span> <span class="font-size-11 white-space right-margin-10 ">' + commentSelDate + '</span>' +
                    '</div></div><div class="clearfix comment-bottom-line"></div>';
            }

            showMoreLink = data.IsRecordsMoreThanMaxDefinedVal;
            //nextViewCommentCount = data.viewCount;
            //if (localStorage.getItem("nextViewCommentCount") == "null" || localStorage.getItem("nextViewCommentCount") == "" || localStorage.getItem("nextViewCommentCount") == null) {
            localStorage.setItem("nextViewCommentCount", data.viewCount);
            //}
            nextViewCommentCount = localStorage.getItem("nextViewCommentCount");

            $(divVideoComments).append(comments).find("#divComments" + icnt).text(data.CommentText);
        });
        var showLessLink = false;
        //if (sessionStorage.getItem("previousViewCommentCount") > sessionStorage.getItem("nextViewCommentCount") && sessionStorage.getItem("nextViewCommentCount") != 10) {
        //    isShowLessLink = true;
        //}

        if (commentDetails.length > CommentsPerPage) {
            showLessLink = true;
        }

        //Assign Updated Comments Count
        $('#spnCommentsCount').html(commentsTotalCount);

        var previousViewCommentCount = localStorage.getItem("nextViewCommentCount");
        localStorage.setItem("previousViewCommentCount", previousViewCommentCount);
        localStorage.setItem("nextViewCommentCount", nextViewCommentCount);

        if ($('#noOfComments').get(0) != undefined) {
            $('#noOfComments').get(0).innerHTML = commentsTotalCount;
        }

        $('.view-comment-link').css("display", "none");
        $('.view-less-comment-link').css("display", "none");

        //if (showMoreLink) {
        //    $('.view-comment-link').css("display", "block");
        //}
        //if (showLessLink) {
        //    $('.view-less-comment-link').css("display", "block");
        //}

        if (CurrentVideoDetail.Permissions != undefined) {
            if (CurrentVideoDetail.Permissions[3].PermissionStatus == true) {
                $('#comment').attr('disabled', true);
                $('#commentsubmit').attr('disabled', true);
                //$('.commentform').attr('disabled', true);
            }
        }

        $('#comment').unbind('keypress');
        $('#comment').bind('keypress', function (e) {
            var key = e.which;
            if (key == 13)  // the enter key code
            {
                e.preventDefault();
                postComments();
                //$("[data-innerroutename='postComments']").click();
            }
        });

        if (commentDetails.length > 0) {
            var currentPage = 1;
            if (nextViewCommentCount != 0)
                currentPage = nextViewCommentCount;
            var displayPages = commentsTotalCount / CommentsPerPage;
            if (commentsTotalCount == 1) {
                //$("#result").html("<p>" + commentsTotalCount + " result found, </p>");
                //$("#mobileresult").html("<p class=\"float-left\">" + commentsTotalCount + " result found, page " + currentPage + " of " + Math.ceil(displayPages) + " </p>")
                $("#mobileresult").html("<p class=\"float-left\">page " + currentPage + " of " + Math.ceil(displayPages) + " </p>")
            } else {
                //$("#result").html("<p>" + commentsTotalCount + " results found, </p>");
                //$("#mobileresult").html("<p class=\"float-left\">" + commentsTotalCount + " results found, page " + currentPage + " of " + Math.ceil(displayPages) + " </p>")
                $("#mobileresult").html("<p class=\"float-left\">page " + currentPage + " of " + Math.ceil(displayPages) + " </p>")
            }

            $("#comments_pageno").html("<p> page " + currentPage + " of " + Math.ceil(displayPages) + " </p>");
            //$(".pageno").html("<p> page " + $("#hdnCurrentPage").val() + " of " + Math.ceil(displayPages) + "</p>");

            //$(".pageNavigation").remove('li');
            //if ($(".pageNavigation").data('twbs-pagination')) {
            //    $(".pageNavigation").data('twbs-pagination', undefined);
            //}

            if (nextViewCommentCount == 0 && commentsTotalCount > CommentsPerPage) {
                localStorage.setItem("nextViewCommentCount", "1");

                $(".pageNavigation").twbsPagination({
                    totalPages: Math.ceil(displayPages),
                    start: 1,
                    visiblePages: DefaultCommentsDisplayPage,
                    onPageClick: function (event, page) {
                        //$("#hdnCurrentPage").val(page);
                        var s = new SearchResult();
                        videoId = CurrentVideoDetail.VideoId;
                        if (videoId === "undefined" || videoId === undefined || videoId == "") {
                            videoId = sessionStorage.getItem("VideoId");
                        }
                        var data = {
                            Id: BrowserStorage.getLogonId(),
                            VideoID: videoId,
                            IsShowHideRecord: false,
                            IsShowAllRecord: true,
                            Count: page,
                            commentViewType: true
                        };
                        //var v = new VideoRepository();

                        VideoRepository.GetComments(data);
                        //   s.PageSearch();
                    }
                });
            }

            if (isPostComment == true && commentsTotalCount > CommentsPerPage) {
                localStorage.setItem("nextViewCommentCount", "1");

                $(".pageNavigation").twbsPagination({
                    totalPages: Math.ceil(displayPages),
                    start: 1,
                    visiblePages: DefaultCommentsDisplayPage
                });
            }

            if (commentsTotalCount > CommentsPerPage) {
                $(".comment-pagination").css("display", "block");
            }
        }
        else {
            $("#result").html("No result found");
            $("#pageno").html("");
            $("#mobileresult").html("");
            $(".comment-pagination").css("display", "none");
        }
    },

    GetComments: function (data) {
        var resposne = '';
        var nextViewCommentCount = CommentsPerPage;
        if (data.commentViewType) {
            nextViewCommentCount = localStorage.getItem("nextViewCommentCount");
            //sessionStorage.setItem("previousViewCommentCount", 0);
        }
        else {
            nextViewCommentCount = localStorage.getItem("previousViewCommentCount");
            nextViewCommentCount = nextViewCommentCount - CommentsPerPage;
            localStorage.setItem("nextViewCommentCount", nextViewCommentCount)
        }

        nextViewCommentCount = data.Count;
        var req = {
            VideoID: data.VideoID,
            IsShowHideRecord: false,
            IsShowAllRecord: false,
            ViewCount: nextViewCommentCount,
            Count: -1
        };
        var object = {
            Data: { "req1": req }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'CommentsManagment/CommentsManagment.svc/GetCommentDetailsTest',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status) {
                    var commentDetails = data.ResultObject;
                    VideoRepository.RenderComments(commentDetails, CommentsEnable, false);
                }
                else {
                    var messageViewModel = new MessageViewModel();
                    messageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId")
                    messageViewModel.ShowOverLay();
                }
            },
            function (data, status, headers, config) {
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId")
                messageViewModel.ShowOverLay();
            },
            JSON.stringify(req));
    },

    PostCommentAbuseMail: function (id, videoId) {
        var resposne = '';
        //var req = {
        //    LogonId: data.LogonId,
        //    CommentText: data.Comment,
        //    VedioId: data.VideoID
        //};

        var req = {
            Id: id,
            LogonId: BrowserStorage.getLogonId(),
            VideoID: videoId,
            IsShowHideRecord: false,
            IsShowAllRecord: true,
            Count: -1,
            VideoTitle: CurrentVideoDetail.Title
        };

        var object = {
            Data: { "req": req }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'CommentsManagment/CommentsManagment.svc/PostCommentAbuseMail',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status) {
                    //var commentDetails = data.ResultObject;
                    var messageViewModel = new MessageViewModel();
                    messageViewModel.CreateInfoMessage('You have successfully reported this comment for abuse.', "overlayId", "okButtonId")
                    messageViewModel.ShowOverLay();
                }
                else {
                    var messageViewModel = new MessageViewModel();
                    messageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId")
                    messageViewModel.ShowOverLay();
                }
            },
            function (data, status, headers, config) {
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId")
                messageViewModel.ShowOverLay();
            },
            JSON.stringify(req));
    },

    getPlayerDetails: function (videoFilter) {
        var _this = this;

        var object = {
            Data: { "videoFilter": videoFilter }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetCurrentVideoDetailforEmbedPlayer',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            if (data.ResultObject.HasUserAccess == true) {
                                var time = new Date();
                                var videoDetail = data.ResultObject;
                                this.CurrentVideoDetail = {
                                    VideoId: videoDetail.VideoId,
                                    ChannelId: videoDetail.ChannelId,
                                    Title: videoDetail.VideoTitle,
                                    Description: videoDetail.ShortDescription,
                                    Abstract: videoDetail.Abstract,
                                    DisplayImage: videoDetail.DisplayImage + "?" + time.getTime(),
                                    ChannelName: videoDetail.ChannelName,
                                    //EntryId: videoDetail.StreamUKId,
                                    EncodedAssetId: videoDetail.EncodedAssetId,
                                    SmoothStreamingURL: videoDetail.SmoothStreamingURL,
                                    ShowOnPortal: videoDetail.ShowOnPortal,
                                    DefaultChannel: videoDetail.channelName,
                                    Permissions: videoDetail.PermissionDetail,
                                    Attachment: videoDetail.Attachment,
                                    ChannelList: videoDetail.ChannelList,//current video detail
                                    Speakers: videoDetail.Speaker,
                                    SpeakerImageSource: videoDetail.SpeakerImageSource,
                                    Keywordlist: videoDetail.Keywordlist,
                                    HasLock: videoDetail.HasLock,
                                    HasPromo: videoDetail.HasPromo,
                                    PromoType: videoDetail.PromoType,
                                    HasUserAccess: videoDetail.HasUserAccess,
                                    ViewsCount: videoDetail.ViewsCount,
                                    LikesCount: videoDetail.LikesCount,
                                    DisLikesCount: videoDetail.DisLikesCount,
                                    Duration: videoDetail.Duration,
                                    PremiumPrice: videoDetail.PremiumPrice,
                                    Comments: videoDetail.Comments,
                                    PriceType: videoDetail.PriceType,
                                    Duration: videoDetail.Duration,
                                    SubscriptionType: videoDetail.SubscriptionType,
                                    // Rakesh
                                    IsSubTitleContentAvailable: videoDetail.IsSubTitleContentAvailable,
                                    SubTitleJsonPath: videoDetail.SubTitleJsonPath,
                                    lstSrtSubTitles: videoDetail.lstSrtSubTitles,
                                    /// Author: Sanjana
                                    /// Date: 19-07-2017
                                    /// Decription: get and set video duration in 00:00:00 format
                                    TimeDuration: videoDetail.TimeDuration
                                    //End
                                };

                                //var KPlayerDetails = data.ResultObject.KalturaPlayerDetail;

                                //player logic
                                //this.PlayerDetail = {
                                //    PartnerId: KPlayerDetails.PartnerId,
                                //    PlayerId: KPlayerDetails.PlayerId,
                                //    CacheStrng: KPlayerDetails.PlayerCacheString,
                                //    EntryId: CurrentVideoDetail.EntryId,
                                //    Ks: KPlayerDetails.PlayerSession
                                //};
                                //console.log(this.PlayerDetail);
                                //console.log(this.CurrentVideoDetail);

                                _this.AttachScript();
                            }
                            else {
                                //promo details logic
                                //counter liogic
                            }
                        }
                    }
                }
                else {
                }
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(videoFilter));
    },

    //getRelatedVideos: function (currentRouteSetting, routeProvider, routeCurrentContext) {
    //    Repository.LoadDataWithGet(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetVideoVideoModel',
    //        function (data, status, headers, config) {
    //            if (ResultStatus.Successful == data.Status && data.ResultObject) {
    //                //Bind all subscriptions to view.
    //                if (data.ResultObject == null) {
    //                    $('#NoRecordFound').html(data.Message);
    //                    $('#Table_Video').hide();
    //                }
    //                else {
    //                    if (data.ResultObject.length != 0) {
    //                        /*Carousel Logic start */
    //                        var relatedVideosHTML = '';

    //                        var count = 0;

    //                        $.each(data.ResultObject.Popularlist, function (index, data) {
    //                            relatedVideosHTML += getRelatedVideoHTML(data.ImageUrl, data.VideoUrl, data.ChannelName, data.VideoTitle, data.SubscriptionType, data.Duration, data.IsEvent);
    //                        });

    //                        $(document).ready($('#related-videos').html(relatedVideosHTML));
    //                        //RenderPlayer();

    //                    }
    //                    else {
    //                        $('#VideoTable').html("No records found.");
    //                    }
    //                    $('#NoRecordFound').hide();
    //                }
    //            }
    //        }
    //        ,
    //        function (data, status, headers, config) {
    //            Spinner.Stop();
    //            var messageViewModel = new MessageViewModel();
    //            messageViewModel.CreateErrorMessage(data);
    //            messageViewModel.ShowOverLay();

    //        });
    //},

    ShowRelatedContent: function (RelatedContentData) {
        $("#dynamicRelatedContentMain").html("");
        if (RelatedContentData != null && RelatedContentData.RelatedContentRecord != null) {
            RelatedContentData.RelatedContentRecord.length == 0 ? $("#related-content").hide() : $("#related-content").show();

            var i = 0;
            $.each(RelatedContentData.RelatedContentRecord, function (index, data) {
                i += 1;
                var ImageType = data.Type == "Book" ? 'Images/book.png' : 'Images/journal.png';
                var strDiv = '<div class="col-lg-6 col-md-6 col-xs-12 col-sm-12 related-content-record-container">';
                strDiv += '<a href="' + data.DOI + '" target="_blank"><div class="related-content-icon" style="background-image:url(' + ImageType + ')"></div><a>';
                strDiv += '<div class="related-content-text">';
                strDiv += '<a href="' + data.DOI + '" target="_blank" class="text-color font-bold custom_pointer">' + data.Title + '</a>';
                strDiv += ' <div>' + data.Type + '</div>';
                strDiv += ' </div>';
                strDiv += ' </div>';

                if (i <= 4) {
                    $("#dynamicRelatedContentMain").append(strDiv);
                }
            });
        }

        $('#LazyLoaderRelatedContent').addClass('display-none');
        $('#dynamicRelatedContentMain').removeClass('display-none');
    },

    //step 1
    RenderVideoPanel: function (renderPlayer) {
        var _this = this;
        //if (renderPlayer) {
        $(".video-thumbnail-toggle-background").toggleClass("display-none");
        $("#player").removeClass('hidden');
        /// Author: Sanjana
        /// Date:02-07-2017
        /// Decription: highlight divs
        $('.myclips').removeClass('disabledbutton');
        $('.share-img-icon').removeClass('disabledbutton');
        $("#transcript-img").removeClass('selectedIcon');
        $(".myclips").removeClass('selectedIcon');
        $(".share-img-icon").removeClass('selectedIcon');
        //End
        //}
        //else {
        //    $(".video-thumbnail-toggle-background").toggleClass("display-none");
        //    $("#player").removeClass('hidden');
        //    $('.transcript-icon').removeClass('display-none');
        //    $('.share-img-icon').removeClass('display-none');
        //}
    },
    CheckPlayButtonEnable: function (StreamingEnd) {
        var _this = this;

        if (StreamingEnd == true) {
            $("#playBtn").css("display", "none");
            //$("#playBtn").attr("disabled", true);
            //$(".like-unlike-pannel").attr('disabled', true);
        }
        else {
            //$(".like-unlike-pannel").attr('disabled', false);
            //$("#playBtn").css("display", "none");
        }
    },

    //step2
    CheckLock: function (hasLock) {
        var _this = this;

        if (hasLock == true) {
            //   _this.HideDownload(true);
            //_this.HideVideo(true);
            $("#playBtn").css("display", "none");
            $("#lockBtn").css("display", "block");
        }
        else {
            $("#playBtn").css("display", "block");
            $("#lockBtn").css("display", "none");
            //_this.HideVideo(false);
        }
    }, AllowDownload: function (allowDownload) {
        var _this = this;

        if (allowDownload == false) {
            $('.download-video-button').attr('disabled', true);
            $('.download-btn-div').attr('disabled', true);
            $('.download-video-button').css('pointer-events', 'none');
        }
        else {
            $('.download-video-button').attr('disabled', false);
            $('.download-video-button').css('pointer-events', '');
            $('.download-btn-div').attr('disabled', false);
        }
    },
    CanLikeDislike1: function (canLikeDislike) {
        if (canLikeDislike == true) {
            $(".like-unlike-pannel").attr('disabled', false);
            $(".view-block").attr('disabled', false);
            $(".like").attr('disabled', false);
            $(".unlike").attr('disabled', false);
            $(".glyphicon-thumbs-down").css('pointer-events', '');
            $(".glyphicon-thumbs-up").css('pointer-events', '');
            $(".likevalue").html(CurrentVideoDetail.LikesCount);
            $(".dislikevalue").html(CurrentVideoDetail.DisLikesCount);

            if (CurrentVideoDetail.ViewsCount <= 1) {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Play");
            }
            else {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Plays");
            }
        }
        else {
            $(".like-unlike-pannel").attr('disabled', true);
            $(".view-block").attr('disabled', true);
            $(".like").attr('disabled', true);
            $(".unlike").attr('disabled', true);
            $('.button_style_none').attr('disabled', true);
            $(".glyphicon-thumbs-down").css('pointer-events', 'none');
            $(".glyphicon-thumbs-up").css('pointer-events', 'none');
            $(".likevalue").html(CurrentVideoDetail.LikesCount);
            $(".dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            if (CurrentVideoDetail.ViewsCount <= 1) {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Play");
            }
            else {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Plays");
            }
        }
    },

    CanPlay: function () {
        var _this = this;
        var canPlay = false;
        if (CurrentVideoDetail.HasLock == true || (CurrentVideoDetail.HasPromo == true && CurrentVideoDetail.PromoType != "video") || CurrentVideoDetail.ShowOnPortal == false) {
            canPlay = false;
        }
        else {
            canPlay = true;
        }
        return canPlay;
    },

    CanLikeDislike: function () {
        var _this = this;
        var canLike = false;
        if (CurrentVideoDetail.HasLock == true || CurrentVideoDetail.HasPromo == true || CurrentVideoDetail.ShowOnPortal == false) {
            canLike = false;
        }
        else {
            canLike = true;
        }
        return canLike;
    },

    RenderAttachment: function (allowed) {
        var _this = this;
        var attachmenthtml = '';
        if (CurrentVideoDetail.Attachment != null) {
            $.each(CurrentVideoDetail.Attachment, function (index, data) {
                if (data.IsActive) {
                    var classMoreAttachments = "";
                    var str = '';
                    if (index > 2) {
                        classMoreAttachments = "more-attachments display-none"
                    }
                    if (allowed == false) {
                        str = '<span  class="text-color font-bold" id="DownloadAttachment" > ' + data.AttachmentFileName + '</span>';
                    }
                    else {
                        // str = '<span><a class="text-color font-bold" id="DownloadAttachment" data-innerroutename="DownloadAttachment" target="_blank" href="#"  fileurl="' + data.AttachmentFileNameWithPath + '">' + data.AttachmentFileName + '</a></span>'
                        str = '<span><a class="text-color font-bold" id="DownloadAttachment" data-innerroutename="DownloadAttachment" target="_blank" style="cursor: pointer;"  fileurl="' + data.AttachmentFileNameWithPath + '">' + data.AttachmentFileName + '</a></span>'
                    }
                    attachmenthtml += '<div class="download_docs ' + classMoreAttachments + '"><img src="' + GetAttachmentImage(data.AttachmentType) + '" />' + str + '</div>';
                }
            });
        }
        $(".download_section").html(attachmenthtml);
        if (attachmenthtml != "") {
            //$('#video-content').removeClass('col-md-12 col-sm-12').addClass('col-md-7 col-sm-7');
            $('#video-attachment').removeClass('display-none');
        }
    },

    RenderTranscript: function (allowed) {
        var _this = this;
        var transcripthtml = '';

        if (CurrentVideoDetail.TranscriptList != null) {
            $.each(CurrentVideoDetail.TranscriptList, function (index, data) {
                var classMoreTranscripts = "";
                //var str = '';
                //var filename = '';
                //var ext = '';
                if (index > 2) {
                    classMoreTranscripts = "more-transcripts display-none"
                }
                //if (data.Text != '') {
                //    ext = data.FileName.split('.')[1];
                //    filename = data.Text + '.' + ext;
                //}
                //else {
                //    filename = data.FileName;
                //}
                if (allowed == false) {
                    str = '<span  class="text-color font-bold" id="DownloadTranscript" > ' + data.FileName + '</span>';
                }
                else {
                    str = '<span><a class="text-color font-bold" id="DownloadTranscript" data-innerroutename="DownloadAttachment" target="_blank"  style="cursor: pointer;"  fileurl="' + data.FilePath + '">' + data.FileName + '</a></span>';
                }
                transcripthtml += '<div class="download_docs ' + classMoreTranscripts + '"><img src="' + GetAttachmentImage(data.AttachmentType) + '" />' + str + '</div>';
            });
        }
        $(".transcript_section").html(transcripthtml);
        if (transcripthtml != "") {
            //$('#video-content').removeClass('col-md-12 col-sm-12').addClass('col-md-7 col-sm-7');
            $('#transcript-attachment').removeClass('display-none');
        }
    },

    RenderIETDigitalLibrary: function (digitalLibraryUrl) {
        var digitalLibraryHtml = '';
        var urltitle = '';
        if (digitalLibraryUrl != "") {
            urltitle = '<span class="text-color font-bold">' + digitalLibraryUrl + '</span>'
            digitalLibraryHtml += '<div class="download_docs"><img class="digital-library" src="Images/journal.png" /><a target="_blank" class="custom_pointer" href="' + digitalLibraryUrl + '">' + urltitle + '</a>';
        }
        $('.digital-library-container').html(digitalLibraryHtml);
        if (digitalLibraryHtml != "") {
            //$('#video-content').removeClass('col-md-12 col-sm-12').addClass('col-md-7 col-sm-7');
            $('#IET-digital-library').removeClass('display-none');
        }
    },

    HideVideo: function (defaultHide) {
        var _this = this;
        var hide = true;
        if (_this.CanPlay() == false) {
            hide = true;
        }
        else if (defaultHide == false) {
            var value = _this.HasPermission("HideRecord");
            if (value == false) {
                hide = false;
            }
        }
        if (hide == true) {
            //_this.RenderVideoPanel(false);
            _this.HideDownload(true);
            _this.HideLikeDislike(true);
        }
        else {
            //_this.RenderVideoPanel(true);
            _this.HideDownload(false);
            _this.HideLikeDislike(false);
        }
    },

    HideDownload: function (defaultHide) {
        var _this = this;
        var hide = true;

        if (defaultHide == false) {
            if (_this.CanLikeDislike() == false) {
                hide = true;
            }
            else {
                var value = this.HasPermission("AllowDownload");
                if (value == false) {
                    hide = false;
                }
                else {
                    hide = true;
                }
            }
        }

        if (hide == true) {
            $('.download-video-button').attr('disabled', true);
            $('.download-btn-div').attr('disabled', true);
            $('.download-video-button').css('pointer-events', 'none');
        }
        else {
            $('.download-video-button').attr('disabled', false);
            $('.download-video-button').css('pointer-events', '');
            $('.download-btn-div').attr('disabled', false);
        }
    },

    HideLikeDislike: function (defaultHide) {
        var _this = this;
        var hide = true;
        if (defaultHide == false) {
            if (_this.CanLikeDislike() == false) {
                hide = true;
            }
            else
                var value = this.HasPermission("ShowRating");
            if (value == false) {
                hide = false;
            }
            else {
                hide = true;
            }
        }
        if (hide == false) {
            $(".like-unlike-pannel").attr('disabled', false);
            $(".view-block").attr('disabled', false);
            $(".like").attr('disabled', false);
            $(".unlike").attr('disabled', false);
            $(".glyphicon-thumbs-down").css('pointer-events', '');
            $(".glyphicon-thumbs-up").css('pointer-events', '');
            $("#likevalue").html(CurrentVideoDetail.LikesCount);
            $("#dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            if (CurrentVideoDetail.ViewsCount <= 1) {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Play");
            }
            else {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Plays");
            }
        }
        else {
            $(".like-unlike-pannel").attr('disabled', true);
            $(".view-block").attr('disabled', true);
            $(".like").attr('disabled', true);
            $(".unlike").attr('disabled', true);
            $(".glyphicon-thumbs-down").css('pointer-events', 'none');
            $(".glyphicon-thumbs-up").css('pointer-events', 'none');
            $("#likevalue").html(CurrentVideoDetail.LikesCount);
            $("#dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            if (CurrentVideoDetail.ViewsCount <= 1) {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Play");
            }
            else {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Plays");
            }
        }
    },

    HasPermission: function (key) {
        var permission = CurrentVideoDetail.Permissions;
        var value = null;
        if (permission != null) {
            $.each(permission, function (k, v) {
                // key == "cars" and value == 27, etc.
                if (v != null) {
                    if (v.PermissionType == key) {
                        value = v.PermissionStatus;
                        //console.log(key + " " + value);
                        return;
                    }
                }
            });
        }
        if (value == null) {
            value = false;
        }

        return value;
    },
    RenderPlayer: function () {
        //alert(video.PartnerId);
        // var partnerid=video.PartnerId;
        var _this = this;
        if (_this.CanPlay() == false) {
            return;
        }
        $("#player").show();

        _this.RenderVideoPanel(true);

        var video = CurrentVideoDetail;
        //var player = PlayerDetail;
        var isClip = false;
        var starttime;
        var endtime;
        var endSeconds;
        var currentSeconds;

        var myOptions = {
            //Need to be relooked
            techOrder: ["azureHtml5JS", "flashSS", "html5FairPlayHLS", "silverlightSS", "html5"],
            "nativeControlsForTouch": false,
            controls: true,
            autoplay: true,
            width: "100%",
            height: "100%",
            "logo": { "enabled": false },
            plugins: {
                ga: {
                    //'eventLabel' : 'EventLabelForTracking', //default is URL source
                    'debug': false, //default is false
                    'eventsToTrack': ['playerConfig', 'loaded', 'playTime', 'percentsPlayed', 'start', 'error', 'buffering', 'bitrate'], // default is ['playerConfig', 'loaded', 'playTime', 'percentsPlayed', 'start', 'end', 'play', 'pause', 'error', 'buffering', 'fullscreen', 'seek', 'bitrate']
                    'percentsPlayedInterval': 20 //default is 20
                }
            }
        }
        myPlayer = null;
        myPlayer = amp("azuremediaplayer", myOptions, function () {
            //'this' refers to the player instance in the ready function
            if (CurrentVideoDetail.IsSubTitleContentAvailable & !CurrentVideoDetail.IsLive & !CurrentVideoDetail.HasLock) {
                IETTVTranscript.Transcript_Highlight_Listener("azuremediaplayer");
                //$("#transcript-img").show();
                $('.transcript-icon').removeClass('hidden');
            }
            starttime = sessionStorage.getItem("Clip_StartTime");
            endtime = sessionStorage.getItem("Clip_EndTime");
            if (starttime != null && endtime != null) {
                isClip = true;
                currentSeconds = converttimetoseconds(starttime);
                endSeconds = converttimetoseconds(endtime);
            }
            else {
                starttime = $.url().param('st');
                endtime = $.url().param('et');                
                if (starttime != undefined && endtime != undefined) {
                    isClip = true;
                    currentSeconds = converttimetoseconds(starttime);
                    endSeconds = converttimetoseconds(endtime);
                }
            }
            //if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
            if (/Android/i.test(navigator.userAgent)) {
                    myPlayer.play();
            }
        });

        myPlayer.addEventListener(amp.eventName.play, function () {
            playerVideoPlayedHandler();
        });
        myPlayer.addEventListener(amp.eventName.ended, function () {
            playerVideoStoppedHandler();
        });
        //allows to display english subtitles when replaying video
        myPlayer.addEventListener(amp.eventName.loadeddata, function () {
            _this.setTrack("en", "subtitles");
        });

        var seekDone = false;
        myPlayer.addEventListener(amp.eventName.playing, function () {
            if (isClip == true) {
                if (!seekDone) {
                    myPlayer.currentTime(currentSeconds);
                    seekDone = true;
                }
            }
        });

        myPlayer.addEventListener(amp.eventName.timeupdate, function () {
            if (Math.floor(myPlayer.currentTime()) == endSeconds) {
                var duration = myPlayer.duration().toString().split('.')[1];
                var currentTime = endSeconds + "." + duration;
                if (myPlayer.duration().toString() != currentTime) {
                    myPlayer.pause();
                    myPlayer.currentTime(endSeconds + 1);
                }
            }
        });
        var subtitleObject = [];
        $.each(CurrentVideoDetail.lstSrtSubTitles, function (index, value) {
            var time = new Date();
            if (value != '' && value != null) {
                subtitleObject.push({
                    "src": $.url().data.attr.source.split('?')[0] + value.SubtitlePath + "?" + time.getTime(),
                    "srclang": value.LanguageAbbreviation,
                    "label": value.Language,
                    "kind": "subtitles",
                    "default": value.Language == "English" ? true : false
                })
            }
        });
        myPlayer.src([
            {
                "src": CurrentVideoDetail.SmoothStreamingURL,
                "type": "application/vnd.ms-sstr+xml"
            }
        ],
            subtitleObject)
    },
    setTrack: function (language, kind) {
        for (var i = 0; i < myPlayer.textTracks_.length; i++) {
            if (myPlayer.textTracks_.tracks_[i].language == language && myPlayer.textTracks_.tracks_[i].kind == kind) {
                myPlayer.textTracks_.tracks_[i].mode = "showing";
            }
            if (myPlayer.textTracks_.tracks_[i].kind == "captions") {
                myPlayer.textTracks_.tracks_[i].mode = "disabled";
            }
        }
    },

    AttachScript: function () {
        $("#player").show();
        var _this = this;
        var video = CurrentVideoDetail;
        var isClip = false;
        var starttime;
        var endtime;
        var endSeconds;
        var currentSeconds;

        var myOptions = {
            //Need to be relooked
            techOrder: ["azureHtml5JS", "flashSS", "html5FairPlayHLS", "silverlightSS", "html5"],
            "nativeControlsForTouch": false,
            controls: true,
            autoplay: false,
            width: "100%",
            height: "100%",
            "logo": { "enabled": false },
            plugins: {
                ga: {
                    //'eventLabel' : 'EventLabelForTracking', //default is URL source
                    'debug': false, //default is false
                    'eventsToTrack': ['playerConfig', 'loaded', 'playTime', 'percentsPlayed', 'start', 'error', 'buffering', 'bitrate'], // default is ['playerConfig', 'loaded', 'playTime', 'percentsPlayed', 'start', 'end', 'play', 'pause', 'error', 'buffering', 'fullscreen', 'seek', 'bitrate']
                    'percentsPlayedInterval': 20 //default is 20
                }
            }
        }
        myPlayer = null;
        myPlayer = amp("azuremediaplayer", myOptions, function () {
            ////'this' refers to the player instance in the ready function
            //$.getScript("Script/Transcript/IETTVTranscript.js", function () {
            //    if (CurrentVideoDetail.IsSubTitleContentAvailable & !CurrentVideoDetail.IsLive & !CurrentVideoDetail.HasLock) {
            //        IETTVTranscript.Transcript_Highlight_Listener("azuremediaplayer");
            //        //$("#transcript-img").show();
            //        $('.transcript-icon').removeClass('hidden');
            //    }
            //});
            starttime = sessionStorage.getItem("Clip_StartTime");
            endtime = sessionStorage.getItem("Clip_EndTime");
            if (starttime != null && endtime != null) {
                isClip = true;
                currentSeconds = converttimetoseconds(starttime);
                endSeconds = converttimetoseconds(endtime);
            }
            else {
                starttime = $.url().param('st');
                endtime = $.url().param('et');
                if (starttime != undefined && endtime != undefined) {
                    isClip = true;
                    currentSeconds = converttimetoseconds(starttime);
                    endSeconds = converttimetoseconds(endtime);
                }
            }
            //if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
            if (/Android/i.test(navigator.userAgent)) {
                myPlayer.play();
            }
        });

        myPlayer.addEventListener(amp.eventName.play, function () {
            playerVideoPlayedHandler();
        });
        myPlayer.addEventListener(amp.eventName.ended, function () {
            playerVideoStoppedHandler();
        });

        //allows to display english subtitles when replaying video
        myPlayer.addEventListener(amp.eventName.loadeddata, function () {
            _this.setTrack("en", "subtitles");
        });

        var seekDone = false;
        myPlayer.addEventListener(amp.eventName.playing, function () {
            $("#player").show().css("visibility", "visible");
            if (isClip == true) {
            if (!seekDone) {
                    myPlayer.currentTime(currentSeconds);
                    seekDone = true;
                }
            }
        });

        myPlayer.addEventListener(amp.eventName.timeupdate, function () {
            //if (Math.floor(myPlayer.currentTime()) == endSeconds) {
            //    myPlayer.pause();
            //    var duration = myPlayer.duration().toString().split('.')[1];
            //    var currentTime = endSeconds + "." + duration;
            //    if (myPlayer.duration().toString() != currentTime) {
            //        myPlayer.currentTime(endSeconds + 1);
            //    }
            //    else {
            //        if ($('.vjs-play-progress')[0] != undefined && $('.vjs-slider-handle')[0] != undefined) {
            //            $('.vjs-play-progress')[0].style["width"] = "100%";
            //            $('.vjs-slider-handle')[0].style["width"] = "100%";
            //        }
            //    }
            //}
            if (Math.floor(myPlayer.currentTime()) == endSeconds) {
                var duration = myPlayer.duration().toString().split('.')[1];
                var currentTime = endSeconds + "." + duration;
                if (myPlayer.duration().toString() != currentTime) {
                    myPlayer.pause();
                    myPlayer.currentTime(endSeconds + 1);
                }
            }
        });
        var subtitleObject = [];
        if (CurrentVideoDetail.lstSrtSubTitles != undefined) {
            $.each(CurrentVideoDetail.lstSrtSubTitles, function (index, value) {
                var time = new Date();
                if (value != '' && value != null) {
                    var urlPortal = $.url().data.attr.source.split('?')[0];
                    subtitleObject.push({
                        "src": urlPortal.substring(0, urlPortal.length - 17) + value.SubtitlePath + "?" + time.getTime(),
                        "srclang": value.LanguageAbbreviation,
                        "label": value.Language,
                        "kind": "subtitles",
                        "default": value.Language == "English" ? true : false
                    })
                }
            });
        }
        myPlayer.src([
            {
                "src": CurrentVideoDetail.SmoothStreamingURL,
                "type": "application/vnd.ms-sstr+xml"
            }
        ],
            subtitleObject)
    },
    //Azure Code added by End 2018/04/19

    SetCountDown: function (date) {
        var _this = this;

        var newYear = new Date();
        newYear = new Date(newYear.getFullYear() + 1, 1 - 1, 1);
        $('#countdownTimer').countdown({ until: newYear });
    },

    VideoViewActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        if (played >= 1) {
            return;
        }
        played++;
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoViewActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("Activity could not be logged");
                    }
                    else {
                        var like = data.ResultObject.Likes;
                        var dislike = data.ResultObject.DisLikes;
                        var view = parseInt(data.ResultObject.Views);
                        var LiveViews = parseInt(data.ResultObject.LiveViews);
                        var TotalCount = parseInt(view + LiveViews);
                        if (TotalCount <= 1) {
                            $("#ViewsCount").html(TotalCount + " Play");
                        }
                        else {
                            $("#ViewsCount").html(TotalCount + " Plays");
                        }

                        $(".dislikevalue").text(dislike);
                        $(".likevalue").text(like);

                        //console.log("Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    ViewTranscriptActivity: function (jsonData) {
        var _this = this;

        var object = {
            Data: { "videoActivity": jsonData }
        };

        //console.log(Download);

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/ViewTranscriptActivity',//DownloadLink',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("Activity could not be logged");
                    }
                    else {
                        //var like = data.ResultObject.Likes;
                        //var dislike = data.ResultObject.DisLikes;
                        //var view = parseInt(data.ResultObject.Views);
                        //var LiveViews = parseInt(data.ResultObject.LiveViews);
                        //var TotalCount = parseInt(view + LiveViews);
                        //if (TotalCount <= 1) {
                        //    $("#ViewsCount").html(TotalCount + " Play");
                        //}
                        //else {
                        //    $("#ViewsCount").html(TotalCount + " Plays");
                        //}

                        //$(".dislikevalue").text(dislike);
                        //$(".likevalue").text(like);

                        ////console.log("Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    LiveVideoViewActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        if (played >= 1) {
            return;
        }
        played++;
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/LiveVideoViewActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("Activity could not be logged");
                    }
                    else {
                        var like = data.ResultObject.Likes;
                        var dislike = data.ResultObject.DisLikes;
                        var video = CurrentVideoDetail;
                        var LiveViews = data.ResultObject.LiveViews;

                        if (LiveViews <= 1) {
                            $("#ViewsCount").html(LiveViews + " Play");
                        }
                        else {
                            $("#ViewsCount").html(LiveViews + " Plays");
                        }

                        $(".dislikevalue").text(dislike);
                        $(".likevalue").text(like);
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    VideoPauseActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoPauseActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("Pause Activity could not be logged");
                    }
                    else {
                        //console.log("Pause Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    VideoPlayActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/EmbedVideoPlayActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("Play Activity could not be logged");
                    }
                    else {
                        //console.log("Play Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                MessageViewModel.CreateErrorMessage(data);
                MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    VideoStopActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoStopActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        // console.log("Stop Activity could not be logged");
                    }
                    else {
                        //console.log("Stop Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                MessageViewModel.CreateErrorMessage(data);
                MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    VideoLikeActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoLikeActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("Like Activity could not be logged");
                    }
                    else {
                        var like = data.ResultObject.Likes;
                        var dislike = data.ResultObject.DisLikes;
                        var view = parseInt(data.ResultObject.Views);
                        var video = CurrentVideoDetail;
                        var LiveViews = parseInt(data.ResultObject.LiveViews);
                        //  var IsLive = video.IsLive;
                        var TotalCount = parseInt(view + LiveViews);
                        if (TotalCount <= 1) {
                            $("#ViewsCount").html(TotalCount + " Play");
                        }
                        else {
                            $("#ViewsCount").html(TotalCount + " Plays");
                        }

                        var lastactivity = data.ResultObject.LastActivity;
                        $(".dislikevalue").text(dislike);
                        $(".likevalue").text(like);

                        _this.ToggleLikeDislike("Like");
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    VideoDislikeActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        var object = {
            Data: { "videoActivity": jsonData }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoDislikeActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("DisLike Activity could not be logged");
                    }
                    else {
                        var like = data.ResultObject.Likes;
                        var dislike = data.ResultObject.DisLikes;
                        var view = parseInt(data.ResultObject.Views);
                        var lastactivity = data.ResultObject.LastActivity;
                        var video = CurrentVideoDetail;
                        var LiveViews = parseInt(data.ResultObject.LiveViews);
                        //  var IsLive = video.IsLive;
                        var TotalCount = parseInt(view + LiveViews);
                        if (TotalCount <= 1) {
                            $("#ViewsCount").html(TotalCount + " Play");
                        }
                        else {
                            $("#ViewsCount").html(TotalCount + " Plays");
                        }

                        $(".dislikevalue").text(dislike);
                        $(".likevalue").text(like);

                        _this.ToggleLikeDislike("Dislike");

                        //console.log("DisLike Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },
    DisposePlayer: function () {
        if (myPlayer) {
            myPlayer.dispose();
        }
    },
    PlayVideo: function () {
        var _this = this;
        toggleVideoSectionVisibility();
    },

    ToggleLikeDislike: function (lastactivity) {
        var _this = this;
        if (lastactivity != "" || lastactivity != null) {
            if (lastactivity == "Like") {
                //$(".like").attr('disabled', true);
                //  $(".unlike").attr('disabled', false);
                $(".unlike").css('pointer-events', '');
                $(".like").css('pointer-events', 'none');
                $(".glyphicon-thumbs-down").css('pointer-events', '');
                $(".glyphicon-thumbs-up").css('pointer-events', 'none');
            }
            else if (lastactivity == "Dislike") {
                $(".glyphicon-thumbs-down").css('pointer-events', 'none');
                $(".glyphicon-thumbs-up").css('pointer-events', '');
                // $(".like").attr('disabled', false);
                ///$(".unlike").attr('disabled', true);
                $(".unlike").css('pointer-events', 'none');
                $(".like").css('pointer-events', '');
            }
        }
    },

    /// Author: Sanjana
    /// Date: 26-07-2017
    /// Decription: function for handling clipping and add to my clips functionality

    AddToMyClips: function (object) {
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/AddToMyClips',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.LoginStatus) {
                    if (ResultStatus.Successful == data.Status && data.ResultObject != null) {
                        var messageViewModel = new MessageViewModel();
                        messageViewModel.CreateSuccessMessage(space +"Video added to my clips successfully", "overlayId", "okButtonId");
                        messageViewModel.ShowOverLay();
                    }
                }
            },
            function (data, status, headers, config) {
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    getCurrentVideoByClipId: function (currentRouteSetting, routeProvider, routeCurrentContext, videoFilter, videoContext) {
        var _this = this;
        played = 0;
        var object = {
            Data: {
                'clipId': videoFilter.ClipId
            }
        };
        if (CurrentVideoDetail.HasLock == true) {
            var messageViewModel = new MessageViewModel();
            messageViewModel.CreateInfoMessage("You don't have access to this video.", "overlayId", "okButtonId")
            messageViewModel.ShowOverLay();
            return false;
        } else {
            Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetMyClipById',
                function (data, status, headers, config) {
                    if (ResultStatus.Successful == data.Status && data.ResultObject) {
                        if (data.ResultObject != null) {
                            //store values of clipping in local storage
                            sessionStorage.setItem("Clip_Id", videoFilter.ClipId);
                            sessionStorage.setItem("Clip_StartTime", data.ResultObject.StartTime);
                            sessionStorage.setItem("Clip_EndTime", data.ResultObject.EndTime);
                            if (videoFilter.IsClipPlay == "true") {
                                sessionStorage.setItem("Clip_isClipPlay", true);
                            }
                            else {
                                sessionStorage.setItem("Clip_isClipPlay", false);
                            }
                        }
                    }
                }, function (data, status, headers, config) {
                    var messageViewModel = new MessageViewModel();
                    messageViewModel.CreateErrorMsgExceptStatus(errMsg);
                    messageViewModel.ShowOverLay();
                }, JSON.stringify(object.Data));
        }
    }
    /// Author: Sanjana End
};

function converttimetoseconds(time) {
    var p = time.split(':'), s = 0, m = 1;
    while (p.length > 0) {
        s += m * parseInt(p.pop(), 10);
        m *= 60;
    }
    var totalSeconds = Math.floor(s);
    return totalSeconds;
}
//    return videohtml;
//}
function getRelatedVideoHTML(videoid, videoNo, channelName, videoTitle, videoimage, hasLock, channelId, SubscriptionType, Duration, isSeries, seriesCount, seriesCreatedYear) {
    videoTitle = videoTitle.replace(/\"/g, "&quot;").replace(/\'/g, "&quot;");
    var accessbtn = '';

    if (channelId == null) {
        channelId = '';
    }
    if (channelName == null) {
        channelName = '';
    }
    var videoroute = '';
    var channelroute = '';
    //var channelHTMLCode = '';

    if (hasLock == false) {
        accessbtn = 'play.png';
    }
    else {
        accessbtn = 'lock.png';
    }
    var seriesOverlayData = "";
    if (videoid != "" && isSeries == false) {
        videoroute = 'data-innerroutename=\"videoid\" data-videoNo=\"' + videoNo + '\"  data-ChannelId=\"' + channelId + '\"  data-hasindex="true" data-videoId=\'' + videoid + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        channelroute = 'data-innerroutename="Channel" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\'';
        //  channelHTMLCode = '<div class=thumbnail-channel ' + channelroute + ' ><span>' + channelName + '</span></div>'
    }
    else if (isSeries == true) {
        //var OrgVideoTitle = videoTitle;
        //videoTitle = videoTitle + " (" + seriesCreatedYear + ")";
        videoroute = 'data-innerroutename=\"series\" data-ChannelId=\"' + channelId + '\"  data-hasindex="true" data-videoId=\'0\'  data-videoNo=\'0\'  data-seriesid=\'' + videoid + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        seriesOverlayData = '<div class="series_overlay_content"> <div class="series_overlay_count">' + seriesCount + '</div> <div class="series_overlay_video_text">Videos</div> </div>';
        channelName = seriesCreatedYear;
        channelroute = 'style="cursor: default;"';
    }

    var addtionaVideoHTML = '<div class="col-md-2 col-xs-6 related-videos_new">' +
        '<div class="bottom-margin-10 related-video-image-background">' +
        '<a href="?videoid=' + videoNo + '"  class="thumbnail-background thumbnail-desktop-list border1px disablehreflink" ' + videoroute + ' style="background-image:url(\'' + videoimage + '\')">' +
        '<img class="playBtn-small playBtn-small-btn-content" src="Images/' + accessbtn + '">' +
        '</a>' +
        seriesOverlayData +
        //'<div class="series_overlay_content">' +
        //  '<div class="series_overlay_count">28</div>' +
        //  '<div class="series_overlay_video_text">Videos</div>' +
        //  '</div>' +
        '</div>' +
        '<div class="col-md-11 no-padding">' +
        '<span>' +
        '<a href="?videoid=' + videoNo + '"  class="list-caption disablehreflink" ' + videoroute + '>' +
        truncateString(videoTitle, 34) +
        '</a>' +
        '</span>' +
        '</div>' +
        '<div class="col-md-11 no-padding">' +
        '<a href="?Channel=' + channelName + '"  class="list-channel disablehreflink" ' + channelroute + '>' +
        channelName +
        '</a>' +

        '</div>' +
        '</div>';

    return addtionaVideoHTML;
}

function SpeakerHTML(position, title, fname, lname, image) {
    var speakersectionhtml = "<div class='item active'>" +
        "<div class='col-md-6 no-padding col-sm-12 col-xs-12 user-block'>" +
        "<div class='thumbnail float-left margin-right-5'>" +
        "<img src='" + image + "' width='50' height='50' class='img-border'/>" +
        "</div>" +
        "<div class='padding-top-5 spkr-info padding-right-20'>" +
        "<div class='no-padding spkr-carousel'>" +
        "<span class='spkr-fname'>" + title + " </span><span class='spkr-fname word-wrap'>" + fname + " </span><span class='spkr-lname word-wrap'>" + lname + "</span>" +
        //"<span class='spkr-fname'>Noshank </span><span class='spkr-lname'>hgktlpanmgjtkloa</span>" +
        "</div>" +
        "<div class='spkr-bio'>" +
        "<a  class=\"text-color custom_pointer\" onClick=\"getSpeakerDetails(" + position + ", \'" + name + "\')\"> View Bio</a>" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</div>";

    return speakersectionhtml;
}

function KeywordHTML(keywordname, keywordId) {
    var keywordHtml = ' <button  data-innerroutename=\'searchResult\' data-hasIndex="true" class="btn badge badge-right-margin" id="keywordid_' + keywordId + '">' + keywordname + '</button>'
    return keywordHtml;
}
function ChannelHTMLVideo(channelName, channelId, channelIconImage) {
    var channelhtml = "";
    channelhtml += "<div>"
    if (channelIconImage.toLowerCase().indexOf("default") > 0 || channelIconImage == "") {


        channelhtml = '<div class="float-left channel-height-without-img no-padding" style="margin-top: 4px;">' +
            '<a  class="custom_pointer disablehreflink" data-innerroutename="Channel"  data-channelId=\'' + channelId + '\' data-name=\'' + channelName + '\' data-hasindex="true" href="?Channel=' + channelName.trim() + '">' +
            '<span class="right-margin-10 font-bold">' + channelName + ' </span>' +
            '</a></div>';
    }
    else {
        channelhtml = '<div class="float-left no-padding channel-height-img">' +
            '<a  class="custom_pointer disablehreflink" data-innerroutename="Channel"  data-channelId=\'' + channelId + '\' data-name=\'' + channelName + '\' data-hasindex="true" href="?Channel=' + channelName.trim() + '">' +
            '<img src="' + channelIconImage + '" class="channel-img-bottom-padding" height="25px" width="auto"><span class="right-margin-10 font-bold">' + channelName + ' </span>' +
            '</a></div>';
    }
    channelhtml += "</div>"
    return channelhtml;
}

function getSpeakerDetails(position, name) {
    var _this = this;
    if (CurrentVideoDetail.Speakers != null) {
        $.each(CurrentVideoDetail.Speakers, function (index, speaker) {
            if (index == position) {
                var SpeakerImage = '';
                if (speaker.PictureUrl.indexOf("$") != -1) {
                    SpeakerImage = speaker.PictureUrl.slice(0, speaker.PictureUrl.lastIndexOf("$"));
                }
                else {
                    SpeakerImage = CurrentVideoDetail.SpeakerImageSource + speaker.PictureUrl;
                }

                $('#speaker_image').attr("src", SpeakerImage);
                if (speaker.Title != '') {
                    $('#spkr_name').text(speaker.Title + " " + speaker.FirstName + " " + speaker.LastName);
                } else {
                    $('#spkr_name').text(speaker.FirstName + " " + speaker.LastName);
                }
                $('#spkr_jobtitle').text(speaker.JobTitle);
                $('#spkr_company_name').text(speaker.Organization);
                $('#spkr_affiliations').text(speaker.Affiliation);
                $('#spkr_biography').html(speaker.Biography)
                $("#viewBioPrompt").modal({
                    backdrop: 'static',
                    keyboard: false
                });
                $("#viewBioPrompt").modal('show');
                return false;
            }
        });
    }
}

function postComments() {
    var videoId = CurrentVideoDetail.VideoId;
    var comment = $("#comment").val();
    if (comment == "") {
        var messageViewModel = new MessageViewModel();
        messageViewModel.CreateInfoMessage("Please define the comment.", "overlayId", "okButtonId")
        messageViewModel.ShowOverLay();
        $('.overlay').addClass('display-block');
        return false;
    }

    var data = {
        VideoID: videoId,
        LogonId: BrowserStorage.getLogonId(),
        Comment: comment
    };
    $('#commentsubmit').attr('disabled', true);
    var resposne = '';
    var accessCodeUserName = '';
    var commenttext = data.Comment.replace(/(['])/g, "''");
    //var commenttext =data.Comment.replace(/'/g,/''/);
    var accessCodeType = sessionStorage.getItem("accessCodeType");
    if (accessCodeType == "2") {
        accessCodeUserName = localStorage.getItem("Welcome");
    }
    //else {
    //    accessCodeUserName = sessionStorage.getItem("delegateName");
    //}
    var req = {
        LogonId: data.LogonId,
        CommentText: data.Comment,
        VedioId: data.VideoID,
        AccessCode: sessionStorage.getItem("accessCode"),
        AccessCodeType: sessionStorage.getItem("accessCodeType"),
        AccessCodeUserName: accessCodeUserName
    };
    var object = {
        Data: { "req": req }
    };

    Repository.LoadDataJSON(WebService.BaseURL + 'CommentsManagment/CommentsManagment.svc/PostVerifiedComment',
        function (data, status, headers, config) {
            if (ResultStatus.Successful == data.Status) {
                var commentDetails = data.ResultObject;
                VideoRepository.RenderComments(commentDetails, CommentsEnable, true);
                $("#comment").val('');
            }
            else {
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId")
                messageViewModel.ShowOverLay();
                $("#comment").blur();
                //alert(data.Message);
                //alert("Error");
            }
            $('#commentsubmit').attr('disabled', false);
        },
        function (data, status, headers, config) {
            var messageViewModel = new MessageViewModel();
            messageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId")
            messageViewModel.ShowOverLay();
            //alert('error');
            $('#commentsubmit').attr('disabled', false);
        },
        JSON.stringify(object.Data));
}

function GetAttachmentImage(fileType) {

    var imageFile = '';
    if (fileType == "PPT") {
        imageFile = 'Images/temp/pp.png';
    }
    else if (fileType == "Pdf") {
        imageFile = 'Images/temp/pdf.png';
    }
    else if (fileType == "Word") {
        imageFile = 'Images/temp/msword.png';
    }
    else if (fileType == "Excel") {
        imageFile = 'Images/temp/pp2.png';
    }
    else {
        imageFile = 'Images/temp/Document icon_orange.png';
    }

    return imageFile;
}

//Stream Code Commented Start 2018/04/11
//var jsCallbackReady = function () {
//    myPlayer = document.getElementById('player');
//    //playerbtn = document.getElementById('playBtn');
//    //myPlayer.addJsListener("playerUpdatePlayhead", "playerUpdatePlayheadHandler");
//    myPlayer.addJsListener("playerPlayed", "playerVideoPlayedHandler");
//    myPlayer.addJsListener("playerPlayEnd", "playerVideoStoppedHandler");
//    //myPlayer.addJsListener("playerPaused", "playerVideoPausedHandler");

//    //myPlayer.addJsListener("adStart", "adStartHandler");
//    //myPlayer.addJsListener("adClick", "adClickHandler");
//    //myPlayer.addJsListener("adEnd", "adEndHandler");

//};
//Stream Code Commented End 2018/04/11

var playerVideoPausedHandler = function (playerid) {
   
    disableSpinner = true;
    var video = CurrentVideoDetail;
    var data =
    {
        Action: "Pause",
        VideoID: video.VideoId,
        VideoTitle: video.Title,
        ActionTime: GetCurrentDate(),
        LogonId: BrowserStorage.getLogonId(),
        IpAddress: "",
        UserName: "",
        Duration: video.Duration
    };
    VideoRepository.VideoPauseActivity(data);
};

function playerVideoStoppedHandler() {
    myPlayer.exitFullscreen();

    disableSpinner = true;
    $("#player").addClass('hidden');
    $(".video-thumbnail-toggle-background").removeClass("display-none");
    /// Author: Sanjana
    /// Date:02-07-2017
    /// Decription: hide and show divs
    $('.share-img-icon').addClass('disabledbutton');
    $('.myclips').addClass('disabledbutton');
    $('.share-img-icon').removeClass('selectedIcon');
    $('.myclips').removeClass('selectedIcon');
    //End
    //$('.video-main-container').addClass('position-rel');
    //$('meta[name=viewport]').attr('content', 'width=device-width, initial-scale=1,user-scalable=no');
    played = 0;
    var video = CurrentVideoDetail;
    var data =
    {
        Action: "Stop",
        VideoID: video.VideoId,
        VideoTitle: video.Title,
        ActionTime: GetCurrentDate(),
        LogonId: BrowserStorage.getLogonId(),
        IpAddress: "",
        UserName: "",
        Duration: video.Duration
    };
    VideoRepository.VideoStopActivity(data);
}

function playerVideoPlayedHandler() {
    var url = window.location.pathname;
    var Filename = getPageName(url);

    if (Filename == "EmbedPlayer" && EmbdedViodeoplayed == 0) {
        EmbdedViodeoplayed++;
        disableSpinner = true;
        var video = CurrentVideoDetail;
        var data =
        {
            Action: "View",
            VideoID: video.VideoId,
            VideoTitle: video.Title,
            ActionTime: GetCurrentDate(),
            ChannelName: "",
            SubscriptionType: video.PriceType,
            Duration: video.Duration
        };
        VideoRepository.VideoPlayActivity(data);
    }
}
function getPageName(url) {
    var index = url.lastIndexOf("/") + 1;
    var filenameWithExtension = url.substr(index);
    var filename = filenameWithExtension.split(".")[0]; // <-- added this line
    return filename;                                    // <-- added this line
}

function toggleVideoSectionVisibility() {
    VideoRepository.RenderPlayer();    
}

function toogleReadMoreLess() {
    var moretext = "Show more";
    var lesstext = "Show less";
    if ($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
    } else {
        $(this).addClass("less");
        $(this).html(lesstext);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
}

function AddReadMore(text) {
    var showChar = 300; // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Show more >";
    var lesstext = "Show less";
    var content = text;

    if (content.length > showChar) {
        var c = content.substr(0, showChar);
        var h = content.substr(showChar, content.length - showChar);

        var html = c + '<span class="moreellipses">' + ellipsestext + '&nbsp;</span><span class="morecontent"><span>' + h + '</span><a href="" class="morelink">' + moretext + '</a></span>';

        return html;
    }
    else {
        return text;
    }
}

function GetCurrentDate() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    //var hour = today.getHour();
    //var minute = today.getMinutes();
    //var seconds = today.getSeconds();

    if (dd < 10) {
        dd = '0' + dd
    }

    if (mm < 10) {
        mm = '0' + mm
    }

    today = mm + '/' + dd + '/' + yyyy;// + ' ' + hour + ":" + minute + ":" + seconds;

    return today;
}

//function to display premium video text
function getDivHeight(premium_text_height) {
    return premium_text_height / 2;
}

function VideoRenderScript() {
    VideoSpeakerRenderScript();
    /*To toggle view of video description area*/ /*located in commonScripts.js*/
    VideoViewMoreScript();
    windowResizeactions();
    $(window).resize(function () {
        /*located in commonScripts.js*/
        windowResizeactions();
    });
}

function VideoSpeakerRenderScript() {
    var run = true;
    /*Calling checkIsMobile in window resize*/

    /*This function is used to check window size if window  size is less than 992 we are considering it as mobile*/
    function checkIsMobile() {
        if ($(window).width() < 992) {
            returnValue = 1;
        } else {
            returnValue = 0;
        }
        return returnValue;
    }

    var $carouselSpeaker = $("#speaker-carousel .carousel");

    /*by default stop carousel cycle*/
    $carouselSpeaker.carousel('pause');
    // get right & left controls
    var $rightSpeakerControl = $carouselSpeaker.find(".right.carousel-control");
    var $leftSpeakerControl = $carouselSpeaker.find(".left.carousel-control");

    var totContentSpeaker = $('#speaker-carousel .carousel-inner').children('.item').size();
    /*Hiding left and right controll if carousel item is 3 or less*/
    if ($(window).width() < 992) {
        if (totContentSpeaker <= 1) {
            $leftSpeakerControl.css('display', 'none');
            $rightSpeakerControl.css('display', 'none');
        }
    }
    else {
        if (totContentSpeaker <= 2) {
            $leftSpeakerControl.css('display', 'none');
            $rightSpeakerControl.css('display', 'none');
        }
    }

    // hide the left control (first slide) on load
    $leftSpeakerControl.hide();

    /* hide and show left and right arrow when carousel slide */
    $carouselSpeaker.on('slid.bs.carousel', function () {
        // get active slide
        var $activeSpeaker = $carouselSpeaker.find(".item.active");

        // if the last slide,

        rightArrowHide();

        // if the first slide,
        if (!$activeSpeaker.prev().length) {
            // hide the left control
            $leftSpeakerControl.css('display', 'none');
            // if not,
        } else {
            // show it
            $leftSpeakerControl.css('display', 'block');
        }
    });

    /*this function is used to show /hide right arrow */
    function rightArrowHide() {
        var showSpeaker;
        if (checkIsMobile() == 1) {
            showSpeaker = $carouselSpeaker.find(".item.active").next().length;
        } else {
            showSpeaker = $carouselSpeaker.find(".item.active").next().next().length;
        }
        if (!showSpeaker) {
            // hide the right control
            $rightSpeakerControl.css('display', 'none');
            // if not,
        } else {
            // show the right control
            $rightSpeakerControl.css('display', 'block');
        }
    }
    var flag = 0;
    $('#speaker-carousel .carousel .item').removeClass('active');
    $('#speaker-carousel .carousel .item').each(function () {
        /*Making first item active*/
        if (flag == 0) {
            $(this).addClass('active');
            flag = 1;
        }
    });

    /*This is used to show three images in speaker carousal */
    run = false;
    var multiple = function () {
        /*removeing active class*/
        $('#speaker-carousel .carousel .item').removeClass('active');

        var flagItemActiveFirst = 0;
        $('#speaker-carousel .carousel .item').each(function () {
            /*Making first item active*/
            if (flagItemActiveFirst == 0) {
                $(this).addClass('active');
                flagItemActiveFirst = 1;
            }
            var next = $(this).next();

            if (!next.length) {
                next = $(this).siblings(':first');
            }
            next.children(':first-child').clone().appendTo($(this));

            //next = next.next();

            //if (!next.length) {
            //    next = $(this).siblings(':first');
            //}
            //next.children(':first-child').clone().appendTo($(this));
            run = true;
        });

        // hiding left controll in this function to work it in window resize
        $leftSpeakerControl.hide();

        /* calling show / hide right arrow */
        rightArrowHide();
    };

    /*This function is used to remove last two images from each slide to show only one image in mobile view*/
    var undo = function () {
        $('#speaker-carousel .carousel .item').each(function () {
            //  $(this).children().last().remove();
            run = false;
        });
    };

    //ensuring proper arrangement on load
    if ($(window).width() > 992) {
        multiple();
    }

    $(window).resize(function () {
        if (run == false && $(window).width() > 992) {
            $('#speaker-carousel .carousel .item').each(function () {
                $(this).children().slice(1).remove();
            });
            multiple();
        } else if (run == true && $(window).width() < 992) {
            $('#speaker-carousel .carousel .item').each(function () {
                $(this).children().slice(1).remove();
            });
            undo();
        }
        rightArrowHide();
    });
}

function StoreSpeakerAccessCode() {
    var AccessCode = ($('#AccessCode').val());

    sessionStorage.setItem("accessCode", AccessCode);

    sessionStorage.setItem("accessCodeType", SpeakerAccessCodeType);
    sessionStorage.setItem("accessCodeFlag", false);
}
function CopyToClipboard() {
    if ($('#embedcode').hasClass("DataTocopy")) {
        $("#embedcode").copymeVideo();
    } else if ($('#facebookcode').hasClass("DataTocopy")) {
        $("#facebookcode").copymeVideo()
    }

    var messageViewModel = new MessageViewModel();
    messageViewModel.CreateInfoMessage("Copied to clipboard successfully", "overlayId", "okButtonId");
    messageViewModel.ShowOverLay();
    $('#iframeEmbed').prop('checked', true);
    $('#facebookTwitterEmbed').prop('checked', false);
    $('#embedcode').addClass("DataTocopy");
}

function callDownloadVideo() {
    //$('#helptext').text(CurrentVideoDetail.Title + " is about to download.<br/> ")
    if (localStorage.getItem('AccountId') != 0) {
        if (!this.CurrentVideoDetail.HasLock) {
            $("#DownloadHelp").modal({
                backdrop: 'static',
                keyboard: false
            });

            $("#DownloadHelp").modal('show');
            $("#btnDownloadContinue").unbind();
            $("#btnDownloadContinue").bind("click", function (e) {
                $("#DownloadHelp").modal('hide');
                VideoRepository.DownloadVideo();
            });
        }
        else {
            var messageViewModel = new MessageViewModel();
            messageViewModel.CreateInfoMessage("Please subscribe to download the video.", "overlayId", "okButtonId");
            messageViewModel.ShowOverLay();
        }
    }
    else {
        var messageViewModel = new MessageViewModel();
        messageViewModel.CreateInfoMessage("Please login to download the video.", "overlayId", "okButtonId");
        messageViewModel.ShowOverLay();
    }
}

var access_CodeType = "";
var txtAccessCode = "";

function StoreAccessCode() {
    txtAccessCode = ($('#txtAccessCode').val().trim());
    var IsUserLoggedIn = "0";

    if (document.getElementById("rdoSpeaker").checked) {
        sessionStorage.setItem("accessCode", txtAccessCode);
        sessionStorage.setItem("accessCodeType", SpeakerAccessCodeType);
        sessionStorage.setItem("accessCodeFlag", false);
    }
    else if (document.getElementById("rdoEvent").checked) {
        sessionStorage.setItem("accessCode", txtAccessCode);
        sessionStorage.setItem("accessCodeType", EventAccessCodeType);
        sessionStorage.setItem("accessCodeFlag", false);
        SetVideoAccessCodeDetailsFromLocalStorage();
        location.href = window.location.href;       
    }
    else if (document.getElementById("rdoVideo").checked) {
        localStorage.setItem("accessCode", txtAccessCode);
        localStorage.setItem("accessCodeType", VideoAccessCodeType);
        localStorage.setItem("accessCodeFlag", false);
        SetVideoAccessCodeDetailsFromLocalStorage();
        location.href = window.location.href;        
    }
}
//This is the temp function
function SetVideoAccessCodeDetailsFromLocalStorage() {
    var accessCode = "";
    var accessCodeType = "";
    var accessCodeFlag = "";
    var routeSeriesVideoId = "videoid";

    if (!IsNullOrEmpty(localStorage.getItem("accessCode"))) {
        accessCode = localStorage.getItem("accessCode");
        sessionStorage.setItem("accessCode", accessCode);
    }

    if (!IsNullOrEmpty(localStorage.getItem("accessCodeType"))) {
        accessCodeType = localStorage.getItem("accessCodeType");
        sessionStorage.setItem("accessCodeType", accessCodeType);
    }

    if (!IsNullOrEmpty(localStorage.getItem("accessCodeFlag"))) {
        accessCodeFlag = localStorage.getItem("accessCodeFlag");
        sessionStorage.setItem("accessCodeFlag", accessCodeFlag);
    }
   
    if (!IsNullOrEmpty(sessionStorage.getItem("RedirectFrom"))) {
        var redirectFrom = sessionStorage.getItem("RedirectFrom")
        if (redirectFrom == routeSeriesVideoId) {
            sessionStorage.setItem("RedirectLocation", routeSeriesVideoId)
        }
    }
}
function SetRedirectLocationToVideoPage() {
    sessionStorage.setItem("RedirectLocation", window.location.href);
    sessionStorage.setItem("RedirectFrom", window.location.href);
    sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);
    location.href = "view/" + Application.Login.BaseURL;
}

function toJSDate(date, time) {
    var toDate = date.split("/");
    var toTime = time.split(":");

    //(year, month, day, hours, minutes, seconds, milliseconds)
    //subtract 1 from month because Jan is 0 and Dec is 11
    return new Date(toDate[2], (toDate[1] - 1), toDate[0], toTime[0], toTime[1], 0, 0);
}

function GetEventDetails(PublishStartDatetime, CurrentDateTime, PublishEpiryDatetime, IsHideRecord, EventStatus, eventVideoDetails, Title, messageParameter,dataMessage) {
    if (IsHideRecord == true) {
        var eventHTML = {
            premiumEventDetail: "",
            btnPurchaseEvent: ""
        }
        return eventHTML;
    }
    else {
        if (EventStatus == 1) {
            if (PublishStartDatetime != "" && PublishEpiryDatetime != "") {
                if (PublishEpiryDatetime >= CurrentDateTime) {
                    if (messageParameter == 'btnVisible') {
                        premiumEventDetail = 'This video is part of paid event ' + '<a href="#" data-toggle="modal" data-target="#premiumEventDetails">' + CurrentVideoDetail.EventDetails.Title + '</a>' + '. Please purchase the event to gain access to the video.';
                        btnPurchaseEvent = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                        var eventHTML = {
                            premiumEventDetail: premiumEventDetail,
                            btnPurchaseEvent: btnPurchaseEvent
                        }

                        return eventHTML;
                    }
                    else if (messageParameter == 'btnInvisible') {
                        //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                       
                        if (dataMessage != null && dataMessage != null) {
                            var messageViewModel = new MessageViewModel();
                            messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                            messageViewModel.ShowOverLay();
                        }
                    //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end
                        videoType = ' This video is part of paid event ' + CurrentVideoDetail.EventDetails.Title + '. Kindly contact the IET Administrator to gain access to this event.';
                        var eventHTML = {
                            videoType: videoType
                        }
                        return eventHTML;
                    }
                    else if (messageParameter == 'EventPriced') {
                        videoType = ' This video is part of paid event ' + CurrentVideoDetail.EventDetails.Title + '. Please purchase the event to gain access to the video.';
                        btnPurchaseProduct = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                        var eventHTML = {
                            videoType: videoType,
                            btnPurchaseProduct: btnPurchaseProduct
                        }
                        return eventHTML;
                    }
                }
                else if (PublishEpiryDatetime < CurrentDateTime) {
                    var eventHTML = {
                        premiumEventDetail: "",
                        videoType: "",
                        btnPurchaseProduct: ""
                    }
                    return eventHTML;
                }
            }
            else if (PublishStartDatetime != "" && PublishEpiryDatetime == "") {
                if (messageParameter == 'btnVisible') {
                    premiumEventDetail = 'This video is part of paid event ' + '<a href="#" data-toggle="modal" data-target="#premiumEventDetails">' + CurrentVideoDetail.EventDetails.Title + '</a>' + '. Please purchase the event to gain access to the video.';
                    btnPurchaseEvent = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                    var eventHTML = {
                        premiumEventDetail: premiumEventDetail,
                        btnPurchaseEvent: btnPurchaseEvent
                    }

                    return eventHTML;
                }
                else if (messageParameter == 'btnInvisible') {
                    //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                    
                    if (dataMessage != null && dataMessage != null) {
                        var messageViewModel = new MessageViewModel();
                        messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                        messageViewModel.ShowOverLay();
                    }
                    //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end
                    videoType = ' This video is part of paid event ' + CurrentVideoDetail.EventDetails.Title + '. Kindly contact the IET Administrator to gain access to this event.';
                    var eventHTML = {
                        videoType: videoType
                    }
                    return eventHTML;
                }
                else if (messageParameter == 'EventPriced') {
                    videoType = ' This video is part of paid event ' + CurrentVideoDetail.EventDetails.Title + '. Please purchase the event to gain access to the video.';
                    btnPurchaseProduct = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                    var eventHTML = {
                        videoType: videoType,
                        btnPurchaseProduct: btnPurchaseProduct
                    }
                    return eventHTML;
                }
            }
        }
        else {
            var eventHTML = {
                premiumEventDetail: "",
                videoType: "",
                btnPurchaseProduct: ""
            }
            return eventHTML;
        }
    }
}
var ChannelRepository = {
    getAllVideos: function (currentRouteSetting, routeProvider, routeCurrentContext, channel) {

        var _this = this;

        var object = {
            Data: { "channel": channel }
        };
              
        $('body,html').animate({ scrollTop: 0 }, 0);
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetChannelHomeVideoModel',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    //Bind all subscriptions to view.
                    if (data.ResultObject == null) {
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {

                        if (data.ResultObject.length != 0) {

                            
                            //$('#channelSliderBackground').css('background-image', 'url(' + data.ResultObject.BackgroundImage.replace(/\\/g, '/').replace('/', '') + ')');
                            if (data.ResultObject.BackgroundImage != "") {
                                $('#channelSliderBackground').css('background-image', 'none');
                                var backgroundImage = data.ResultObject.BackgroundImage.replace(/\\/g, '/').replace('/', '') + "?t=" + new Date().getTime();
                                $('#channelSliderBackground').css('background-image', 'url(' + backgroundImage + ')');
                            }
                            $('.channel-name-image').hide();
                            if (data.ResultObject.IconImage != "") {
                                var IconImage = data.ResultObject.IconImage.replace(/\\/g, '/').replace('/', '') + "?t=" + new Date().getTime();
                                $('.channel-name-image').attr('src', IconImage);
                                $('.channel-name-image').show();
                            }
                            
                            
                            _this.setChannelSliderBackgroundColor(data.ResultObject.Color, data.ResultObject.ButtonColor, data.ResultObject.ForegroundColor);
                            if (data.ResultObject.ButtonColor!==null && data.ResultObject.ButtonColor.split(",").length - 1 > 2) {
                                data.ResultObject.ButtonColor = data.ResultObject.ButtonColor.substring(0, data.ResultObject.ButtonColor.lastIndexOf(','));
                            }

                            if (data.ResultObject.ForegroundColor !== null && data.ResultObject.ForegroundColor.split(",").length - 1 > 2) {
                                data.ResultObject.ForegroundColor = data.ResultObject.ForegroundColor.substring(0, data.ResultObject.ForegroundColor.lastIndexOf(','));
                            }

                            var channelButtonColor = 'rgb(' + data.ResultObject.ButtonColor + ')';

                            //$(".channel-bullets-desktop div").css("background-color", 'rgb(' + data.ResultObject.ForegroundColor + ')');
                            
                            //$(".channel-bullets-mobile div").css("background-color", 'rgb(' + data.ResultObject.ForegroundColor + ')');                            
                            $(".channel-name").css("color", 'rgb(' + data.ResultObject.ForegroundColor + ')');
                            $("#MostPopular,#forthcoming,#Latest").css("color", 'rgb(' + data.ResultObject.ForegroundColor + ')');
                            
                            var channelName = data.ResultObject.ChannelName;
                            $('.channel-name').text(channelName);
                            $(".bg-channel").css("background-color", data.ResultObject.color);
                            channel.Id = data.ResultObject.Id;
                            channel.color = data.ResultObject.color;
                            var carousellist = data.ResultObject.Carousellist;
                            var popularlist = data.ResultObject.Popularlist;
                            var Latest = data.ResultObject.Latest;
                            var ForthComming = data.ResultObject.Forthcominglist;
                            var IsPrivateChannel = data.ResultObject.IsPrivateChannel;
                            //SEO-Title
                           setMetaData(channelName, channelName);
                            //SEO-Title

                            //  RenderFeedChannel();
                            /*Carousel Logic start */
                            var videoCarousel1 = '';
                            var videoCarousel2 = '';
                            var videoCarousel3 = '';

                            /*Carousel Logic start */
                            var mobilevideoCarousel1 = '';
                            var mobilevideoCarousel2 = '';
                            var mobilevideoCarousel3 = '';
                          

                            var topPosition = 0;
                            var leftPosition = 0;
                            /*Below are position constant*/
                            var topPosition0 = 0;
                            var leftPosition0 = 0;
                            var topPosition260 = 260;
                            var leftPosition346 = 320;
                            var leftPosition692 = 640;

                            var leftPosition10 = 10;
                            var leftPosition399 = 399;
                            var topPosition520 = 520;

                            var count = 0;
                            var videoimage = ''
                            var mobilecount = 0;
                            //desktop logic
                            if (carousellist != null) {
                                $.each(carousellist, function (index, data) {
                                    count = count + 1;
                                    /*set top and left position value */
                                    if (count % 3 == 1) {
                                        topPosition = topPosition0
                                        leftPosition = leftPosition0
                                    }
                                    else if (count % 3 == 2) {
                                        topPosition = topPosition0
                                        leftPosition = leftPosition346
                                    }
                                    else {
                                        topPosition = topPosition0
                                        leftPosition = leftPosition692
                                    }
                                    var time = new Date();
                                    if (count <= 3) {
                                        //As issue in Build 
                                        // $('.channel-heading-desktop').text(data.ChannelName);
                                        //videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                        videoCarousel1 += channelVideoCarousel(leftPosition, topPosition, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, channel.Id, data.IsJisc, data.Duration, data.SubscriptionType, channelButtonColor);
                                    }
                                    else if (count >= 4 && count <= 6) {
                                        //videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                        videoCarousel2 += channelVideoCarousel(leftPosition, topPosition, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, channel.Id, data.IsJisc, data.Duration, data.SubscriptionType, channelButtonColor);
                                    }
                                    else if (count >= 7 && count <= 9) {
                                        // videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                        videoCarousel3 += channelVideoCarousel(leftPosition, topPosition, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, channel.Id, data.IsJisc, data.Duration, data.SubscriptionType, channelButtonColor);
                                    }

                                });
                            }

                            if (IsPrivateChannel) {
                                var isPrivateChannelhtml = '<div class="Channel_overlay_div"><div class="channel_overlay-text">Sorry, you don’t have access to this video as it’s part of a private collection.If you are authorised to see this video, please log in.</div></div>';
                                //$(".slide-container").addClass('alpha30');
                                $("#channelSliderBackground").prepend(isPrivateChannelhtml);
                            }

                            $(document).ready($('#firstslide').html(videoCarousel1));
                            $(document).ready($('#secondslide').html(videoCarousel2));
                            $(document).ready($('#thirdslide').html(videoCarousel3));                         
                          
                            RenderDesktopScriptChannel();

                           
                            //mobile logic

                            var position = '';
                            if (carousellist != null) {
                                $.each(carousellist, function (index, data) {
                                    mobilecount = mobilecount + 1;
                                    /*set top and left position value */
                                    if (mobilecount % 3 == 1) {
                                        leftPosition = leftPosition10
                                        topPosition = topPosition0

                                    }
                                    else if (mobilecount % 3 == 2) {
                                        leftPosition = leftPosition10
                                        topPosition = topPosition520
                                    }
                                    else {
                                        leftPosition = leftPosition399
                                        topPosition = topPosition520
                                    }
                                    var time = new Date();
                                    if (mobilecount <= 3) {
                                        if (mobilecount == 1) {
                                            position = 'top';
                                        }
                                        else {
                                            position = 'bottom';
                                        }
                                        // videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                        mobilevideoCarousel1 += ChannelVideoCarouselMobile(leftPosition, topPosition, position, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, channel.Id, data.IsJisc, data.Duration, data.SubscriptionType, channelButtonColor);
                                    }
                                    else if (mobilecount >= 4 && mobilecount <= 6) {
                                        if (mobilecount == 4) {
                                            position = 'top';
                                        }
                                        else {
                                            position = 'bottom';
                                        }
                                        //videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                        mobilevideoCarousel2 += ChannelVideoCarouselMobile(leftPosition, topPosition, position, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, channel.Id, data.IsJisc, data.Duration, data.SubscriptionType, channelButtonColor);
                                    }
                                    else {
                                        if (mobilecount == 7) {
                                            position = 'top';
                                        }
                                        else {
                                            position = 'bottom';
                                        }
                                        // videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                        mobilevideoCarousel3 += ChannelVideoCarouselMobile(leftPosition, topPosition, position, data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.ShortDescription, data.DisplayImage + "?" + time.getTime(), data.HasLock, channel.Id, data.IsJisc, data.Duration, data.SubscriptionType, channelButtonColor);
                                    }


                                });
                            }

                            $(document).ready($('#mobilefirstslide').html(mobilevideoCarousel1));
                            $(document).ready($('#mobilesecondslide').html(mobilevideoCarousel2));
                            $(document).ready($('#mobilethirdslide').html(mobilevideoCarousel3));
                           
                            
                            RenderMobileScriptChannel();
                            
                            /*Carousel Logic end */
                            /*popular logic start*/
                            var addtionaVideoHTML = '';
                            var viewAllHTML = ' ' +
                                            '<div class="clearfix bottom-border below-carousel-conent-border-bottom"></div><div class="font-bold"><button class="ViewAll"><a >View all</a><button></div>';
                            addtionaVideoHTML = '<span class="font-bold fs-18">Most Viewed</span>' +
                                        '<hr>';
                            var time = new Date();
                            if (popularlist != null) {
                                $.each(popularlist, function (index, data) {
                                    // videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    addtionaVideoHTML += getchannelAddtionaVideoHTML(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage + "?" + time.getTime(), data.HasLock, channel.Id, data.IsJisc, data.SubscriptionType, data.Duration, channelButtonColor);
                                });
                            }
                            var count = 0;
                            if (data.ResultObject != null) {
                                count = data.ResultObject.PopularlistCount;
                            }
                            addtionaVideoHTML += GetchannelViewAllHTML('Popular',channel.Id,channel.Name,count);

                            $(document).ready($('#MostPopular').html(addtionaVideoHTML));

                            /*popular logic end*/

                            
                            /*forthcoming video logic start*/
                            addtionaVideoHTML = '';
                            addtionaVideoHTML = '<span class="font-bold fs-18">Coming up</span>' +
                                        '<hr>';
                            
                            if (ForthComming != null) {
                                $.each(ForthComming, function (index, data) {
                                    //videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    addtionaVideoHTML += getchannelAddtionaVideoHTML(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage + "?" + time.getTime(), data.HasLock, channel.Id, data.IsJisc, data.SubscriptionType, data.Duration, channelButtonColor);
                                });
                            }
                            if (data.ResultObject != null) {
                                count = data.ResultObject.ForthcominglistCount;
                            }
                            addtionaVideoHTML += GetchannelViewAllHTML('Forthcoming', channel.Id, channel.Name,count);

                            $(document).ready($('#forthcoming').html(addtionaVideoHTML));


                            /*Latest video logic start*/
                            addtionaVideoHTML = '';
                            addtionaVideoHTML = '<span class="font-bold fs-18">Latest</span>' +
                                        '<hr>';
                            if (Latest != null) {
                                $.each(Latest, function (index, data) {
                                    //videoimage = SetVideoImage(data.StreamThumbnailUrl, data.UKStreamID, thumbnailurl, data.FileName, defaultimage);
                                    addtionaVideoHTML += getchannelAddtionaVideoHTML(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage + "?" + time.getTime(), data.HasLock, channel.Id, data.IsJisc, data.SubscriptionType, data.Duration, channelButtonColor);
                                });
                            }
                            if (data.ResultObject != null) {
                                count = data.ResultObject.LatestlistCount;
                            }
                            addtionaVideoHTML += GetchannelViewAllHTML('Latest', channel.Id, channel.Name,count);

                            $(document).ready($('#Latest').html(addtionaVideoHTML));

                      
                        }
                        else {
                            $('#VideoTable').html("No records found.");
                        }
                        $('#NoRecordFound').hide();

                        routeProvider.bindInnerRoutes();
                        if (!WebService.DisableGA) {
                           storeurlDetailsInGA('Channel Title - ' + channel.Name);
                        }
                        BrowserStorage.setRedireceLocation(Application.Channel.BaseURL);
                    }
                }
            }
            ,
            function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();

            }, JSON.stringify(object.Data));
    },

    setChannelSliderBackgroundColor: function (backgroundColor, buttonColor,foregroundcolor) {
        //setting default value for backgroundColor
        if (backgroundColor !== null && backgroundColor.split(",").length - 1 > 2) {
            backgroundColor = backgroundColor.substring(0, backgroundColor.lastIndexOf(','));                       
        }

        if (buttonColor !== null && buttonColor.split(",").length - 1 > 2) {
            buttonColor = buttonColor.substring(0, buttonColor.lastIndexOf(','));
        }

        if (foregroundcolor !== null && foregroundcolor.split(",").length - 1 > 2) {
            foregroundcolor = foregroundcolor.substring(0, foregroundcolor.lastIndexOf(','));
        }

        backgroundColor = typeof backgroundColor !== 'undefined' ? backgroundColor != '0,0,0' ? backgroundColor : "234,234,234" : "157,117,153";
        buttonColor = typeof buttonColor !== 'undefined' ? buttonColor : "53,53,53";
        //buttonColor = typeof buttonColor !== 'undefined' ? buttonColor != '0,0,0' ? buttonColor : "53,53,53" : "53,53,53";

        //backgroundColor = typeof backgroundColor !== 'undefined' ? backgroundColor : "157,117,153";
        //buttonColor = typeof buttonColor !== 'undefined' ? buttonColor : "53,53,53";
        
        //SETTING CHANNEL BACKGROUND COLOR
        //$("#channelSliderBackground").css("background-color", "rgb(" + backgroundColor + ")");
        //SETTING CHANNEL SLIDER ARROWS
        //  $(".channel-carousel-arrow").css("background-color", "rgba(" + backgroundColor + ",1)");


        //SETTING FADER COLORS FOR MOZILLA
        $('.channelFaderLeft').css({ background: "-moz-linear-gradient(left,  rgba(" + backgroundColor + ",1) 10%, rgba(" + backgroundColor + ",0) 90%" });
        $('.channelFaderRight').css({ background: "-moz-linear-gradient(left,  rgba(" + backgroundColor + ",0) 10%, rgba(" + backgroundColor + ",1) 90%" });
        //$('.channelFaderLeft').css({ background: '-webkit-linear-gradient(left,  rgba(' + backgroundColor + ',1) 0%, rgba(' + backgroundColor + ',0) 100%' });
        //$('.channelFaderLeft').css({ background: "-webkit-gradient(linear, left top, right top, color-stop(0%,rgba(" + backgroundColor + ",1)), color-stop(100%,rgba(" + backgroundColor + ",0)))" });
        //$('.channelFaderLeft').css({ background: "-o-linear-gradient(left,  rgba(" + backgroundColor + ",1) 0%,rgba(" + backgroundColor + ",0) 100%)" });
        //$('.channelFaderLeft').css({ background: "-ms-linear-gradient(left,  rgba(" + backgroundColor + ",1) 0%,rgba(" + backgroundColor + ",0) 100%)" });
        //$('.channelFaderLeft').css({ background: "linear-gradient(to right,  rgba(" + backgroundColor + ",1) 0%,rgba(" + backgroundColor + ",0) 100%)" });
        //$('.channelFaderLeft').css({ background: '-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorStr=rbga(' + backgroundColor + ',1) , EndColorStr=rbga(' + backgroundColor + ',1))"' })
        //.css({background: ""})
        //.css({background: ""})
        //.css({background: ""})

        $('.channelFaderLeft').append('<svg height="100%" width="100%"><linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="10%" style="stop-color:rgb(' + backgroundColor + ');stop-opacity:1" /><stop offset="90%" style="stop-color:rgb(' + backgroundColor + ');stop-opacity:0" /></linearGradient><rect x="0" y="0" width="100%" height="100%"  fill="url(#grad1)" /></svg>');
        $('.channelFaderRight').append('<svg height="100%" width="100%"><linearGradient id="grad2" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="10%" style="stop-color:rgb(' + backgroundColor + ');stop-opacity:0" /><stop offset="90%" style="stop-color:rgb(' + backgroundColor + ');stop-opacity:1" /></linearGradient><rect x="0" y="0" width="100%" height="100%"  fill="url(#grad2)" /></svg>');


        /* IE9 SVG, needs conditional override of 'filter' to 'none' */
        //background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iIzFlNTc5OSIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiM3ZGI5ZTgiIHN0b3Atb3BhY2l0eT0iMCIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
        //background: -moz-linear-gradient(left,  rgba(30,87,153,1) 0%, rgba(125,185,232,0) 100%); /* FF3.6+ */
        //background: -webkit-gradient(linear, left top, right top, color-stop(0%,rgba(30,87,153,1)), color-stop(100%,rgba(125,185,232,0))); /* Chrome,Safari4+ */
        //background: -webkit-linear-gradient(left,  rgba(30,87,153,1) 0%,rgba(125,185,232,0) 100%); /* Chrome10+,Safari5.1+ */
        //background: -o-linear-gradient(left,  rgba(30,87,153,1) 0%,rgba(125,185,232,0) 100%); /* Opera 11.10+ */
        //background: -ms-linear-gradient(left,  rgba(30,87,153,1) 0%,rgba(125,185,232,0) 100%); /* IE10+ */
        //background: linear-gradient(to right,  rgba(30,87,153,1) 0%,rgba(125,185,232,0) 100%); /* W3C */
        //filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#007db9e8',GradientType=1 ); /* IE6-8 */

        //$("<style>").prop("type", "text/css").html("\.channel-bullets-desktop .av {\background-color:rgb('"+ buttonColor +"');\}").appendTo("head");
        $("<style>").prop("type", "text/css").html("\.channel-bullets-desktop div {background-color:rgb(" + foregroundcolor + ") !important;\}").appendTo("head");
        $("<style>").prop("type", "text/css").html("\.channel-bullets-mobile div {background-color:rgb(" + foregroundcolor + ") !important;\}").appendTo("head");
        $("<style>").prop("type", "text/css").html("\.channel-bullets-desktop .av {background-color:rgb(" + buttonColor + ") !important;\}").appendTo("head");
        $("<style>").prop("type", "text/css").html("\.channel-bullets-mobile .av {background-color:rgb(" + buttonColor + ") !important;\}").appendTo("head");
        //$(".channel-bullets-desktop div").css("background-color", convertHex(LightenDarkenColor(rgb2hex("rgb(" + buttonColor + ")"), -120), 100));
        //$('.channel-bullets-desktop .av').css('background-color', buttonColor);
        //$("<style>").prop("type", "text/css").html("\.content-bg-color {background-color:rgba(" + backgroundColor + ",0.7) !important;\}").appendTo("head");
        //$('.channel-carousel-arrow').css('background-color', 'rgb(' + buttonColor + ')');
        $(".content-bg-color").css("background-color", 'rgb(' + backgroundColor + ')');
    }
};

function GetchannelViewAllHTML(searchdata, channelId, channelName, count) {
    var viewallHTML = "";
    if (count > 3) {
        viewallHTML = '<div class="clearfix bottom-border below-carousel-conent-border-bottom"></div><div class="font-bold"><button class="ViewAll" data-innerroutename=\"' + searchdata + '\" data-videotype=' + searchdata + ' data-ChannelId=\'' + channelId + '\' data-hasindex="true"><a  class="custom_pointer">View all</a></button></div>';//Fix for PS-1335:View all button not working in IE11 : Added routing data attributes to button and removed from anchor
    } else {
        viewallHTML = '<div class="clearfix bottom-border below-carousel-conent-border-bottom"></div><div class="font-bold" style="display: none;"><button class="ViewAll" data-innerroutename=\"' + searchdata + '\" data-videotype=' + searchdata + ' data-ChannelId=\'' + channelId + '\' data-hasindex="true"><a  class="custom_pointer">View all</a></button></div>';//Fix for PS-1335:View all button not working in IE11-Added routing data attributes to button and removed from anchor
    }
    sessionStorage.setItem("ChannelName", channelName);
   
    return viewallHTML;
}
/*generate thumbnail logic */
function channelVideoCarousel(leftPosition, topPosition, videoid, videoNo, channelName, videoTitle, shortDescription, videoimage, hasLock, channelId, IsJisc, Duration, SubscriptionType, channelColor) {
    videoTitle = videoTitle.replace(/\"/g, "&quot;").replace(/\'/g, "&#39;");
    var accessbtn = '';
    var videoroute = '';
    if (Duration == null) {
        Duration = ' ';
    }

    if (hasLock == false) {
        accessbtn = '<svg xmlns = "http://www.w3.org/2000/svg" class="playBtn"  width = "37.93" height = "37.93" viewBox = "0 0 37.93 37.93" > <g id="Group_854" data-name="Group 854" transform="translate(0 0)"><g id="Group_853" data-name="Group 853"><g id="Fields_Input_Colour_White" data-name="Fields / Input / Colour White"><rect id="Fields_Input_Colour_White_background" data-name="Fields / Input / Colour White background" width="37.93" height="37.93" fill="rgba(0,0,0,0)" /><rect id="Fields_Input_Colour_White-2" data-name="Fields / Input / Colour White" width="37.93" height="37.93" fill="' + channelColor + '" style="fill:' + channelColor + '"/></g><path id="Polygon_1" data-name="Polygon 1" d="M6.392,0l6.392,11.25H0Z" style="transform: rotate(90deg) translate(13px, -25px)" transform="translate(24.897 12.732) rotate(90)" fill="#fff" /></g></g></svg >';
    }
    else {
        accessbtn = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="playBtn" x="0px" y="0px" viewBox="0 0 37.9 37.9" style="enable-background:new 0 0 37.9 37.9;" xml:space="preserve"><style type="text/css">.st0{fill:' + channelColor + '}.st1{fill:#FFFFFF;}</style><g id="Group_854" transform="translate(0 0)"><g id="Group_853"><g id="Fields_Input_Colour_White"><rect id="Fields_Input_Colour_White_background" y="0" width="37.9" height="37.9"/><rect id="Fields_Input_Colour_White-2" y="0" class="st0" width="37.9" height="37.9"/></g></g></g><path id="Path_111" class="st1" d="M23.5,17.6h-1.1V15c-0.1-1.9-1.7-3.3-3.6-3.2c-1.7,0.1-3.1,1.5-3.2,3.2v2.6h-1.1c-0.4,0-0.7,0.3-0.7,0.7v7c0,0.4,0.3,0.7,0.7,0.7h9c0.4,0,0.7-0.3,0.7-0.7v-7C24.2,17.9,23.9,17.6,23.5,17.6L23.5,17.6z M17.1,15 L17.1,15c0.1-1,1-1.8,2-1.7c0.9,0.1,1.6,0.8,1.7,1.7l0,0v2.6h-3.7V15z M19.6,22.5v2h-1.2v-2c-0.7-0.3-1.1-1.2-0.7-2c0.3-0.7,1.2-1.1,2-0.7c0.7,0.3,1.1,1.2,0.7,2C20.2,22.1,19.9,22.3,19.6,22.5L19.6,22.5z"/></svg>';
    }

    if (videoid != "" && IsJisc==false) {
        videoroute = 'data-innerroutename=\"videoid\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-videoNo=\"' + videoNo + '\" data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';

    } else if (videoid != "" && IsJisc == true) {
        videoroute = 'data-innerroutename=\"JiscVideoChannel\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-videoNo=\"' + videoNo + '\" data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
    }

    var videoCarousel = '<div class="thumbnail-container-div custom_pointer" ' + videoroute +
                                    'style="left:' + leftPosition + 'px; top:' + topPosition + 'px;" ' +
                                   '>' +
                                        '<a href="?videoid=' + videoNo + '"  class="mainwrapper disablehreflink">' +
                                             '<div class="box">' +
                                                 '<div class="thumbnail-desktop-carousel" style="background-image:url(\'' + videoimage + '\')"></div>' +
                                                    '<div class="caption">' +
                                                    ' <div class="video_caption">' + shortDescription + '</div>' +
                                                    '<span class="caption-timer">' + Duration + '</span>' +
                                                     //'<span class="caption-SubscriptionType" style="display: none;">' + SubscriptionType + '</span>' +
                                                    '</div>' +
                                              //  '<img src="Images/play.png" class="playBtn"/>' +
                                            '</div>' +
                                        '</a>' +
                                        '<div class="thumbnail-caption"><a href="?videoid=' + videoNo + '"  class="caption-VideoTitle carouselVideoTextColor disablehreflink">' + truncateString(videoTitle, 105) + '</a></div>' +
                                    //'<div class=thumbnail-channel><span>' + channelName + '</span></div>' +

                                     //'<img src="Images/' + accessbtn + '" class="playBtn"/> ' +
                                        accessbtn +
                                    '</div>';
    return videoCarousel;
}
function RenderDesktopScriptChannel() {

    var options = {
        $BulletNavigatorOptions: { //[Optional] Options to specify and enable navigator or not
            $Class: $JssorBulletNavigator$, //[Required] Class to create navigator instance
            $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
            $AutoCenter: 1, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
            $SpacingX: 10 //[Optional] Horizontal space between each item in pixel, default value is 0

        },

        $ArrowNavigatorOptions: { //[Optional] Options to specify and enable arrow navigator or not
            $Class: $JssorArrowNavigator$, //[Requried] Class to create arrow navigator instance
            $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
            $AutoCenter: 2, //[Optional] Auto center arrows in parent container, 0 No, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
            $Steps: 1 //[Optional] Steps to go for each navigation request, default value is 1
        },
        $SlideWidth: 1200,
        $SlideSpacing: 20, 					                //Space between each slide in pixels
        $DisplayPieces: 2,                              //Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1
        $ParkingPosition: 168
    };



    var jssor_slider1 = new $JssorSlider$("sliderChannel_Desktop", options);

    //responsive code begin
    //you can remove responsive code if you don't want the slider scales while window resizes
    function ScaleSlider() {
        var parentWidth = jssor_slider1.$Elmt.parentNode.clientWidth;
        if (parentWidth) {
            var sliderWidth = parentWidth;

            //keep the slider width no more than 1200
            sliderWidth = Math.min(sliderWidth, 1280);

            jssor_slider1.$SetScaleWidth(sliderWidth);
        } else
            window.setTimeout(ScaleSlider, 30);
    }

    ScaleSlider();

    if (!navigator.userAgent.match(/(iPhone|iPod|iPad|BlackBerry|IEMobile)/)) {
        $(window).bind('resize', ScaleSlider);
    }
    if (navigator.userAgent.match(/(iPhone|iPod|iPad)/)) {
        $(window).bind("orientationchange", ScaleSlider);
    }
}

function RenderMobileScriptChannel() {      
        var optionsMobile = {
            $BulletNavigatorOptions: { //[Optional] Options to specify and enable navigator or not
                $Class: $JssorBulletNavigator$, //[Required] Class to create navigator instance
                $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always
                $AutoCenter: 1, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
                $SpacingX: 25 //[Optional] Horizontal space between each item in pixel, default value is 0

            }
        };



        var jssor_slider1 = new $JssorSlider$("sliderChannel_Mobile", optionsMobile);

        //responsive code begin
        //you can remove responsive code if you don't want the slider scales while window resizes
        function ScaleSlider() {
            var parentWidth = jssor_slider1.$Elmt.parentNode.clientWidth;
            if (parentWidth) {
                var sliderWidth = parentWidth;

                //keep the slider width no more than 800
                sliderWidth = Math.min(sliderWidth, 768);

                jssor_slider1.$SetScaleWidth(sliderWidth);
            } else
                window.setTimeout(ScaleSlider, 30);
        }

        ScaleSlider();

        if (!navigator.userAgent.match(/(iPhone|iPod|iPad|BlackBerry|IEMobile)/)) {
            $(window).bind('resize', ScaleSlider);
        }
        if (navigator.userAgent.match(/(iPhone|iPod|iPad)/)) {
            $(window).bind("orientationchange", ScaleSlider);
        }
    //Scale slider while window load/resize/orientationchange.
        $(window).bind("load", ScaleSlider);
        $(window).bind("resize", ScaleSlider);
        $(window).bind("orientationchange", ScaleSlider);
}
/*generate thumbnail logic */
function getchannelAddtionaVideoHTML(videoid, videoNo, channelName, videoTitle, videoimage, hasLock, channelId, IsJisc, SubscriptionType, Duration,channelColor) {
    videoTitle = videoTitle.replace(/\"/g, "&quot;").replace(/\'/g, "&#39;");
    var accessbtn = '';
    if (hasLock == false) {
        accessbtn = '<svg xmlns = "http://www.w3.org/2000/svg" class="playBtn-small"  width = "37.93" height = "37.93" viewBox = "0 0 37.93 37.93" > <g id="Group_854" data-name="Group 854" transform="translate(0 0)"><g id="Group_853" data-name="Group 853"><g id="Fields_Input_Colour_White" data-name="Fields / Input / Colour White"><rect id="Fields_Input_Colour_White_background" data-name="Fields / Input / Colour White background" width="37.93" height="37.93" fill="rgba(0,0,0,0)" /><rect id="Fields_Input_Colour_White-2" data-name="Fields / Input / Colour White" width="37.93" height="37.93" fill="' + channelColor + '"/></g><path id="Polygon_1" data-name="Polygon 1" d="M6.392,0l6.392,11.25H0Z" style="transform: rotate(90deg) translate(13px, -25px)" transform="translate(24.897 12.732) rotate(90)" fill="#fff" /></g></g></svg >';
    }
    else {
        accessbtn = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="playBtn-small" x="0px" y="0px" viewBox="0 0 37.9 37.9" style="enable-background:new 0 0 37.9 37.9;" xml:space="preserve"><style type="text/css">.st0{fill:' + channelColor + ';}.st1{fill:#FFFFFF;}</style><g id="Group_854" transform="translate(0 0)"><g id="Group_853"><g id="Fields_Input_Colour_White"><rect id="Fields_Input_Colour_White_background" y="0" width="37.9" height="37.9"/><rect id="Fields_Input_Colour_White-2" y="0" class="st0" width="37.9" height="37.9"/></g></g></g><path id="Path_111" class="st1" d="M23.5,17.6h-1.1V15c-0.1-1.9-1.7-3.3-3.6-3.2c-1.7,0.1-3.1,1.5-3.2,3.2v2.6h-1.1c-0.4,0-0.7,0.3-0.7,0.7v7c0,0.4,0.3,0.7,0.7,0.7h9c0.4,0,0.7-0.3,0.7-0.7v-7C24.2,17.9,23.9,17.6,23.5,17.6L23.5,17.6z M17.1,15 L17.1,15c0.1-1,1-1.8,2-1.7c0.9,0.1,1.6,0.8,1.7,1.7l0,0v2.6h-3.7V15z M19.6,22.5v2h-1.2v-2c-0.7-0.3-1.1-1.2-0.7-2c0.3-0.7,1.2-1.1,2-0.7c0.7,0.3,1.1,1.2,0.7,2C20.2,22.1,19.9,22.3,19.6,22.5L19.6,22.5z"/></svg>';
    }
    var routName = (IsJisc == true) ? 'JiscVideoChannel' : 'videoid';

    var addtionaVideoHTML = '<div class="float-left bottom-margin-20 video-thumbnail-container channel-sm-video-thumb" cursor="pointer" data-innerroutename=\"' + routName + '\" data-videoNo=\"' + videoNo + '\" data-ChannelId=\'' + channelId + '\'  data-videoId=\'' + videoid + '\' data-hasindex="true" data-isJisc=\'' + IsJisc +  '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'>' +
                        '<a href="?videoid=' + videoNo + '"  class="thumbnail-background thumbnail-desktop-list disablehreflink" style="background-image:url(\'' + videoimage + '\')">' +
                        //'<img class="playBtn-small" src="Images/' + accessbtn + '">' +
                        accessbtn +
                    '</a>' +
                    '<div class="text-margin">' +
                        '<a href="?videoid=' + videoNo + '"  class="list-caption disablehreflink" >' + truncateString(videoTitle, 30) + '</a><br>' +//four lines 68
                       // '<div class="list-caption" >' + channelName + '</div>' +
                    '</div>' +
                '</div>';
    //'<div class="clearfix"></div>'

    return addtionaVideoHTML;
}


//function truncateString(str, length) {    
//    return str.length > length ? jQuery.trim(str).substr(0, length)
//                           + "..." : str
//}

function RenderFeedChannel() {

    var feed = new google.feeds.Feed("http://feeds.feedburner.com/tedtalks_video");

    feed.setNumEntries(3);
    feed.load(function (result) {
        if (!result.error) {
            var container = document.getElementById("Videofeed");
            container.innerHTML = '<h3>Video feed</h3>' +
                                     '<hr>';
            var count = result.feed.entries.length;
            for (var i = 0; i < result.feed.entries.length; i++) {
                var addtionaVideoHTML = ''
                var entry = result.feed.entries[i];

                //var entry = result.feed.entries[i];
                var bmfx = entry.mediaGroups[0].contents[0].thumbnails[0].url;
                //var li = document.createElement("div");
                //li.innerHTML = '<h3><a href="' + entry.link + '">' + entry.title + '</a> <cite>by ' + entry.mediaGroup + '</cite></h3>';
                addtionaVideoHTML = '<a class="float-left bottom-margin-20 video-thumbnail-container" target="_blank"  href="' + entry.link + '">' +
                  '<div class="thumbnail-background thumbnail-desktop-list" style="background-image:url(\'' + bmfx + '\')">' +
                 '<img class="playBtn-small" src="Images/play.png">' +
                '</div>' +
                 '<div class="text-margin">' +
                         '<div class="list-caption">' + truncateString(entry.title, 25) + '</div><br>' +
                         '<div class="list-channel" >' + entry.author + " : " + entry.categories[0] + '</div>' +
                         '</div>' +
                     '</a>';

                
                //var channelName = entry.author + " : " + entry.categories[0];
                //addtionaVideoHTML = getAddtionaVideoHTML(entry.link, channelName, truncateString(entry.title, 30), "", bmfx);
                container.innerHTML += addtionaVideoHTML;


            }
            var viewAllHTML = ' ' +
                                        '<div class="clearfix bottom-border below-carousel-conent-border-bottom"></div>';//<div class="font-bold"><a href="#">View all</a></div>';
            container.innerHTML += viewAllHTML;
        }
    });    
}


function ChannelVideoCarouselMobile(leftPosition, topPosition, position, videoid, videoNo, channelName, videoTitle, shortDescription, videoimage, hasLock, channelId, IsJisc, Duration, SubscriptionType, channelColor) {
    videoTitle = videoTitle.replace(/\"/g, "&quot;").replace(/\'/g, "&#39;");
    var accessbtn = '';
    var videoroute = '';
    if (Duration == null) {
        Duration = ' ';
    }

    if (hasLock == false) {
        accessbtn = '<svg xmlns = "http://www.w3.org/2000/svg" class="playBtn-mobile-' + position + '" width = "37.93" height = "37.93" viewBox = "0 0 37.93 37.93" > <g id="Group_854" data-name="Group 854" transform="translate(0 0)"><g id="Group_853" data-name="Group 853"><g id="Fields_Input_Colour_White" data-name="Fields / Input / Colour White"><rect id="Fields_Input_Colour_White_background" data-name="Fields / Input / Colour White background" width="37.93" height="37.93" fill="rgba(0,0,0,0)" /><rect id="Fields_Input_Colour_White-2" data-name="Fields / Input / Colour White" width="37.93" height="37.93" fill="' + channelColor + '" style="fill:' + channelColor + '"/></g><path id="Polygon_1" data-name="Polygon 1" d="M6.392,0l6.392,11.25H0Z" style="transform: rotate(90deg) translate(13px, -25px)" transform="translate(24.897 12.732) rotate(90)" fill="#fff" /></g></g></svg >';
    }
    else {
        accessbtn = '<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="playBtn-mobile-' + position + '" x="0px" y="0px" viewBox="0 0 37.9 37.9" style="enable-background:new 0 0 37.9 37.9;" xml:space="preserve"><style type="text/css">.st0{fill:' + channelColor + '}.st1{fill:#FFFFFF;}</style><g id="Group_854" transform="translate(0 0)"><g id="Group_853"><g id="Fields_Input_Colour_White"><rect id="Fields_Input_Colour_White_background" y="0" width="37.9" height="37.9"/><rect id="Fields_Input_Colour_White-2" y="0" class="st0" width="37.9" height="37.9"/></g></g></g><path id="Path_111" class="st1" d="M23.5,17.6h-1.1V15c-0.1-1.9-1.7-3.3-3.6-3.2c-1.7,0.1-3.1,1.5-3.2,3.2v2.6h-1.1c-0.4,0-0.7,0.3-0.7,0.7v7c0,0.4,0.3,0.7,0.7,0.7h9c0.4,0,0.7-0.3,0.7-0.7v-7C24.2,17.9,23.9,17.6,23.5,17.6L23.5,17.6z M17.1,15 L17.1,15c0.1-1,1-1.8,2-1.7c0.9,0.1,1.6,0.8,1.7,1.7l0,0v2.6h-3.7V15z M19.6,22.5v2h-1.2v-2c-0.7-0.3-1.1-1.2-0.7-2c0.3-0.7,1.2-1.1,2-0.7c0.7,0.3,1.1,1.2,0.7,2C20.2,22.1,19.9,22.3,19.6,22.5L19.6,22.5z"/></svg>';
    }

    if (videoid != "" && IsJisc == false) {
        videoroute = 'data-innerroutename=\"videoid\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid +  '\' data-videoNo=\"' + videoNo + '\" data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        
    } else if (videoid != "" && IsJisc == true) {      
        videoroute = 'data-innerroutename=\"JiscVideoChannel\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-videoNo=\"' + videoNo + '\" data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
    }
    if (position == "bottom") {
        var MobileCarousel = '<div class="custom_pointer thumbnail-container-div-mobile-' + position + ' \"' + videoroute + '  style="left: ' + leftPosition + 'px; top: ' + topPosition + 'px;" >' +
                                      '<a href="?videoid=' + videoNo + '"  class="mainwrapper disablehreflink">' +
                                          '<div class="box">' +
                                              '<div class="thumbnail-mobile-carousel-' + position + '" style="background-image:url(\'' + videoimage + '\')"></div>' +        
                                          '</div>' +
                                      '</a>' +
                                      '<div class="thumbnail-caption-mobile"><a href="?videoid=' + videoNo + '"  class="carouselVideoTextColor disablehreflink">' + truncateString(videoTitle, 30) + '</a></div>' +
                                      //'<div class=thumbnail-channel-mobile>' + channelName + '</div>' +
                                      //'<img src="Images/' + accessbtn + '" class="playBtn-mobile-' + position + '"/> ' +
                                        accessbtn +
                                  '</div>';
    }
    else
    {
        var MobileCarousel = '<div class="custom_pointer thumbnail-container-div-mobile-' + position + ' \"' + videoroute + '  style="left: ' + leftPosition + 'px; top: ' + topPosition + 'px;" >' +
                                      '<a href="?videoid=' + videoNo + '"  class="mainwrapper disablehreflink">' +
                                          '<div class="box">' +
                                              '<div class="thumbnail-mobile-carousel-' + position + '" style="background-image:url(\'' + videoimage + '\')"></div>' +
                                                  '<div class="caption">' +
                                                      '<div class="video_caption new">' + shortDescription + '</div>' +
                                                            '<span class="caption-timer">' + Duration + '</span>' +
                                                             //'<span class="caption-SubscriptionType" style="display: none;">' + SubscriptionType + '</span>' +
                                                  '</div>' +
                                          '</div>' +
                                      '</a>' +
                                      '<div class="thumbnail-caption-mobile"><a href="?videoid=' + videoNo + '"  class="carouselVideoTextColor disablehreflink">' + truncateString(videoTitle, 30) + '</a></div>' +
                                      //'<div class=thumbnail-channel-mobile>' + channelName + '</div>' +
                                      //'<img src="Images/' + accessbtn + '" class="playBtn-mobile-' + position + '"/> ' +
                                      accessbtn +
                                  '</div>';
    }
    return MobileCarousel;
}

this.ChangePasswordRepository = {
    PerformAction: function (context, data) {

        var object = {
            Data: {
                logonId: BrowserStorage.getLogonId(),
                oldPassword: data.oldPassword,
                newPassword: data.newPassword
            }
        }
        var _this = this;
        Repository.LoadDataJSON(WebService.BaseURL + 'UserManagement/UserService.svc/ChangePassword',
            function (data, status, headers, config) {

                if (data.Status == 0) {
                    if (data.ResultObject == '1') {
                        context.MessageViewModel.CreateSuccessMessage(data.Message, "overlayId", "okButtonId");
                        context.MessageViewModel.ShowOverLay();

                        $('#okButtonId').click(function () {
                            if (BrowserStorage.getRedireceLocationwithIndex() != -1) {
                                location.href = "?" + BrowserStorage.getRedireceLocationwithIndex();
                            }
                            else
                                location.href = "?" + Application.Home.BaseURL;
                        });

                    } else {                       
                        context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                        context.MessageViewModel.ShowOverLay();
                    }
                }
                else {                    
                    context.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                    context.MessageViewModel.ShowOverLay();

                }
            },
            function (data, status, headers, config) {
                Spinner.Stop();
                //console.log(data);
                context.MessageViewModel.CreateErrorMessage(data);
                context.MessageViewModel.ShowOverLay();

            }, JSON.stringify(object.Data));
    }



}
//Model
this.PlayerDetail = {};
this.RelatedVideos = {};
this.CurrentVideoDetail = {};
this.SpeakerDetails = {};
var played = 0;
var isLiveVideoOn = false;
var videoNo = 0;
var EventIsDisplayQA = false;
var EventIsDisplayPolling = false;
var EventAccessCodeType = 1;
var SpeakerAccessCodeType = 2;
var VideoAccessCodeType = 3;
var PollQuestionAvailable = 0;
var EventModel = {};
var LoadEventOnPromo = 0;
var LiveVideoStatusId = 1;
var myPlayer = null;
var EventRepository = {
    getCurrentEventVideo: function (currentRouteSetting, routeProvider, routeCurrentContext, eventFilter, eventContext, DisplayVideoDetails) {
        var _this = this;
        var object = {
            Data: { "eventFilter": eventFilter }
        };

        var UrlWitheventpara = BrowserStorage.getRedireceLocation();
        var methodname = "";

        if (UrlWitheventpara == 'eventvideoid') {
            methodname = "getEventVideoDetail";
            //Rakesh:Added Login to handle Tabs visibility
            $('.EventData').hide();
            // $('.EventVideoData').show();
            var divEventBasicInfoConainer = $('#divEventBasicInfoContainer');
            divEventBasicInfoConainer.html('');
            divEventBasicInfoConainer.html($('#divEventBasicInfo').html());
            divEventBasicInfoConainer.show();
            $('.share-embed-qna-poll-icons-desktop-video').show();
        } else {
            methodname = "getEventVideos";
            //Rakesh:Added Login to handle Tabs visibility
            $('.EventData').show();
            $('.EventVideoData').hide();
            $('#divEventBasicInfoContainer').hide();
            $('.share-embed-qna-poll-icons-desktop-video').hide();
        }

        Repository.LoadDataJSON(WebService.BaseURL + 'EventManagement/EventService.svc/' + methodname + "",
            function (data, status, headers, config) {
                var UrlWitheventpara = _this.getUrlParameter();

                if (data.ResultObject == null || data.ResultObject == undefined) {
                    $("#videoDescription").html("Event not found!!").css({ "font-size": "25px", "font-weight": "bold" });
                    $("#EventDecription").html("Event not found!!").css({ "font-size": "25px", "font-weight": "bold" });
                    $('#backgroundImage').css("background-image", "url('Images/img_noevent.jpg')");
                    $('#outer_background_image').css("background-image", "url('Images/img_noevent.jpg')");
                    $('.eventnotfound').hide()
                    $('.IfEventNotFound').hide();
                    $(".embedmodal").css('display', 'none');
                    EviSearchMaintainToggleState();
                    return;
                }
                var PublishExpiryDateTime = data.ResultObject.EvenData.PublishExpiryDate != null ? toJSDate(data.ResultObject.EvenData.PublishExpiryDate, data.ResultObject.EvenData.PublishExpiryTime) : "";
                var CurrentDateTime = new Date();

                //initializing UI
                //   onEventPageLoad();
                if (ResultStatus.Successful == data.Status && data.ResultObject != null && data.ResultObject.EvenData.EventStatus == 1 && data.ResultObject.EvenData.IsHideRecord == false) {
                    if (PublishExpiryDateTime != "" && PublishExpiryDateTime < CurrentDateTime) {
                        $("#videoDescription").html("Event not found!!").css({ "font-size": "25px", "font-weight": "bold" });
                        $("#EventDecription").html("Event not found!!").css({ "font-size": "25px", "font-weight": "bold" });
                        $('#backgroundImage').css("background-image", "url('Images/img_noevent.jpg')");
                        $('#outer_background_image').css("background-image", "url('Images/img_noevent.jpg')");
                        $('.eventnotfound').hide()
                        $(".embedmodal").css('display', 'none');
                        $('.IfEventNotFound').hide();
                        var IsEviSearch = (localStorage.getItem("eviSearchToggle") != null && localStorage.getItem("eviSearchToggle") != undefined) ? localStorage.getItem("eviSearchToggle") : false;
                        $('#chkSearch').prop('checked', IsEviSearch);
                        $('#chkSearchMob').prop('checked', IsEviSearch);
                        $('#Search_button').attr('disabled', 'disabled');
                        $('#Mobile-btn').attr('disabled', 'disabled');
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            localStorage.setItem("LoginStatus", data.LoginStatus);
                            if (eventFilter.VideoStatusId == 1) {
                                //alert('tesy');
                                if (isLiveVideoOn == false) {
                                    isLiveVideoOn = true;
                                    videoNo = eventFilter.VideoNo;
                                }
                            }
                            else {
                                isLiveVideoOn = false;
                                videoNo = 0;
                            }

                            var videoDetail = data.ResultObject.PlayerViewModelresult.ResultObject;
                            var eventDetail = data.ResultObject.EvenData

                            this.EventModel = {
                                HasPromo: data.ResultObject.HasPromo,
                                CanPlay: data.ResultObject.CanPlay,
                                HasCountdown: data.ResultObject.HasCountdown,
                                PromoType: data.ResultObject.PromoType,
                                StreamUKId: data.ResultObject.StreamUKId
                            };

                            if (!IsNullOrEmpty(videoDetail)) {
                                var time = new Date();
                                this.CurrentVideoDetail = {
                                    VideoId: eventFilter.VideoId,
                                    ChannelId: videoDetail.ChannelId,
                                    Title: videoDetail.VideoTitle,
                                    VideoTitle: videoDetail.VideoTitle,
                                    Description: videoDetail.ShortDescription,
                                    Abstract: videoDetail.Abstract,
                                    DisplayImage: videoDetail.DisplayImage + "?" + time.getTime(),
                                    ChannelName: videoDetail.ChannelName,
                                    //EntryId: videoDetail.StreamUKId,
                                    //EntryId: videoDetail.StreamUKId,
                                    EncodedAssetId: videoDetail.EncodedAssetId,
                                    SmoothStreamingURL: videoDetail.SmoothStreamingURL,
                                    ShowOnPortal: videoDetail.ShowOnPortal,
                                    DefaultChannel: videoDetail.channelName,
                                    Permissions: videoDetail.PermissionDetail,
                                    Attachment: videoDetail.Attachment,
                                    ChannelList: videoDetail.ChannelList,//current video detail
                                    Speakers: videoDetail.Speaker,
                                    SpeakerImageSource: videoDetail.SpeakerImageSource,
                                    Keywordlist: videoDetail.Keywordlist,
                                    HasLock: videoDetail.HasLock,
                                    HasPromo: videoDetail.HasPromo,
                                    PromoType: videoDetail.PromoType,
                                    HasUserAccess: videoDetail.HasUserAccess,
                                    ViewsCount: videoDetail.ViewsCount,
                                    VideoDate: videoDetail.VideoDate,
                                    LikesCount: videoDetail.LikesCount,
                                    DisLikesCount: videoDetail.DisLikesCount,
                                    LastLikeDislikeActivity: videoDetail.LastLikeDislikeActivity,
                                    Duration: videoDetail.Duration,
                                    PremiumPrice: videoDetail.PremiumPrice,
                                    CanPlay: videoDetail.CanPlay,
                                    CanLikeDislike: videoDetail.CanLikeDislike,
                                    AllowDownload: videoDetail.AllowDownload,
                                    relatedVideos: videoDetail.RelatedVideos,
                                    AllowAttachmentDownload: videoDetail.AllowAttachmentDownload,
                                    Comments: videoDetail.Comments,
                                    IsCommentsEnable: videoDetail.IsCommentsEnable,
                                    IsLive: videoDetail.IsLive,
                                    RelatedContent: videoDetail.RelatedContent,
                                    VideoStatus: videoDetail.VideoStatus,
                                    //For TB-152 issue
                                    PriceType: videoDetail.PriceType,
                                    ChannelCategoryTypeId: videoDetail.ChannelCategoryTypeId,
                                    IndividualUserType: videoDetail.IndividualUserType.toLowerCase(),
                                    VideoNo: videoDetail.VideoNo,
                                    TranscriptList: videoDetail.objTranscriptList,
                                    DigitalLibrary: videoDetail.DigitalLibrary,
                                    PremiumDiscountPercentage: videoDetail.PremiumDiscountPercentage,
                                    PremiumDiscountAmount: videoDetail.PremiumDiscountAmount,
                                    SubscriptionType: videoDetail.SubscriptionType,
                                    Duration: videoDetail.Duration,
                                    EventDetails: videoDetail.EventDetails,
                                    DiscountType: videoDetail.DiscountType,
                                    EventDiscount: videoDetail.EventDiscount,
                                    // Rakesh : Set Transcript Parameters
                                    TimeDuration: videoDetail.TimeDuration,

                                    IsSubTitleContentAvailable: videoDetail.IsSubTitleContentAvailable,
                                    SubTitleJsonPath: videoDetail.SubTitleJsonPath,
                                    lstSrtSubTitles: videoDetail.lstSrtSubTitles
                                };
                            }
                            //Rakesh: Begin  Load IETTVTranscript.Js and load Transcript Content
                            if (!CurrentVideoDetail.IsLive & !CurrentVideoDetail.HasLock) {
                                $.getScript("Script/Transcript/IETTVTranscript.js", function () {
                                    if (CurrentVideoDetail.IsSubTitleContentAvailable) {
                                        IETTVTranscript.BindLanguagesDropdown(CurrentVideoDetail.lstSrtSubTitles);
                                        $('.transcript-icon').removeClass('hidden');
                                        // IETTVTranscript.LoadTranscripts(CurrentVideoDetail.SubTitleJsonPath);
                                    }
                                });
                            }

                            $('.myclips').addClass('disabledbutton');
                            $('.share-img-icon').addClass('disabledbutton');
                            $('.transcript-icon').addClass('hidden');

                            //Rakesh: End
                            /// Author: Sanjana
                            /// Date:02-07-2017
                            /// Decription: hide and show divs
                            if (CurrentVideoDetail.IsLive) {
                                $('.myclips').addClass('hidden');
                                $('.share-img-icon').addClass('hidden');
                            }
                            else {
                                if (!IsNullOrEmpty(sessionStorage.getItem("LogonId"))) {
                                    if (sessionStorage.getItem("IsIPLogin") == null || sessionStorage.getItem("IsIPLogin") == "false") {
                                        $('.myclips').removeClass('hidden');
                                    }
                                    else {
                                        $('.myclips').addClass('hidden');
                                    }
                                }
                                else {
                                    $('.myclips').addClass('hidden');
                                }
                            }
                            //End

                            sessionStorage.setItem("EventVideoTitle", CurrentVideoDetail.VideoTitle);
                            if (CurrentVideoDetail.Title != undefined) {
                                $(".div_Videotitle").text(truncateString(CurrentVideoDetail.Title, 58));
                            }
                            if (!IsNullOrEmpty(eventDetail.EventId)) {
                                sessionStorage.setItem("EventId", eventDetail.EventId);
                            }

                            if (CurrentVideoDetail.HasLock == true) {
                                $(".embedmodal").css('display', 'none');
                            }
                            if (!IsNullOrEmpty(CurrentVideoDetail.Title)) {
                                $(".div_Videotitle").text(truncateString(CurrentVideoDetail.Title, 58))
                            }
                            if (UrlWitheventpara == "event") {
                                $(".embedmodal").css('display', 'none');
                            }

                            $(".btnEventAccessCode").attr("data-DisplayVideoDetails", DisplayVideoDetails)

                            if (CurrentVideoDetail.PremiumDiscountPercentage != '0' && CurrentVideoDetail.PremiumDiscountAmount != '0') {
                                $("#spnPremiumPrice").text(CurrentVideoDetail.PremiumDiscountAmount);
                            }
                            else {
                                $("#spnPremiumPrice").text(CurrentVideoDetail.PremiumPrice);
                            }
                            $(".btnCheckOutRedirect").attr({
                                "data-lastRouteName": 'eventvideoid',
                                "data-innerroutename": 'address',
                                "data-videono": CurrentVideoDetail.VideoNo,
                                "data-eventid": eventFilter.EventId,
                                "data-displayvideodetails": 1
                            });

                            $("#desktop-cpd-logo").attr("src", "");
                            $("#mobile-cpd-logo").attr("src", "");
                            if (videoDetail != null) {
                                if (videoDetail.IsDisplayCPD != "" && videoDetail.CPDLogo != "") {
                                    $("#desktop-cpd-logo").attr("src", videoDetail.CPDLogo);
                                    $("#desktop-cpd-logo").css("display", "block");
                                    $("#mobile-cpd-logo").attr("src", videoDetail.CPDLogo);
                                    $("#mobile-cpd-logo").css("display", "block");
                                    $("#desktop-cpd-logo").attr("data-content", videoDetail.CPDLogoText);
                                    $("#mobile-cpd-logo").attr("data-content", videoDetail.CPDLogoText);
                                }
                            }

                            if (DisplayVideoDetails != 1) {
                                LoadEventOnPromo = 1;
                                $('#backgroundImage').css("background-image", 'url("' + data.ResultObject.SetDisplayImage + '")');
                                $('#backgroundImage').attr("src", data.ResultObject.SetDisplayImage);
                                $('#outer_background_image').css("background-image", 'url("' + data.ResultObject.SetDisplayImage + '")');

                                //Rakesh:commented New UI
                                //  $('#backgroundImage').attr("alt", CurrentVideoDetail.Title);
                                //if (CurrentVideoDetail.Permissions[0].VideoThumbnailURL != "" && CurrentVideoDetail.Permissions[0].VideoThumbnailURL != null) {
                                //    $('#backgroundImage').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailURL + "')");
                                //    $('#outer_background_image').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailURL + "')");
                                //}
                                //else {
                                //    $('#backgroundImage').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailBannerURL + "')");
                                //    $('#outer_background_image').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailBannerURL + "')");
                                //}
                                if (window.matchMedia('(max-width: 400px)').matches) {
                                    $(".video-main-caption").html(truncateString(eventDetail.Title, 30));
                                }
                                else if (window.matchMedia('(max-width: 767px)').matches) {
                                    $(".video-main-caption").html(truncateString(eventDetail.Title, 40));
                                }
                                else {
                                    $(".video-main-caption").html(truncateString(eventDetail.Title, 58));
                                }
                            }
                            else {
                                LoadEventOnPromo = 0;
                            }
                            //hide view block, like dislike block , related videos and content on event load
                            //$('.view-block').css('display', 'none');
                            $('#ViewsCount').hide();
                            $(".like-unlike-pannel").hide();
                            $("#related-videos").hide();
                            $("#related-content").hide();
                            //Event Promo section
                            //Start
                            //$("#videoDescription").html(eventDetail.Description);
                            $("#EventDecription").html(eventDetail.Description);
                            
                            ////Rakesh:Handles Event Description
                            if (getNormalHeight('EventDecription') > 60) {
                                $('#event-description-more').removeClass('display-none');
                            } else {
                                $('#event-description-more').addClass('display-none');
                            }

                            if (data.ResultObject.HasPromo == true && LoadEventOnPromo == 1) {
                                //$('#backgroundImage').attr("src", data.ResultObject.SetDisplayPromoImage);
                                if (data.ResultObject.PromoType != "Video") {
                                    $("#eventvideoplayBtn").addClass('cursor-default');
                                }

                                if (window.matchMedia('(max-width: 400px)').matches) {
                                    $(".video-main-caption").html(truncateString(eventDetail.Title, 30));
                                }
                                else if (window.matchMedia('(max-width: 767px)').matches) {
                                    $(".video-main-caption").html(truncateString(eventDetail.Title, 40));
                                }
                                else {
                                    $(".video-main-caption").html(truncateString(eventDetail.Title, 58));
                                }

                                //$(".mobile-title-caption").html(truncateString(eventDetail.Title, 35));
                                //$("#videoDescription").html(eventDetail.Description);
                                $('.morelink').click(toogleReadMoreLess);
                                if (!IsNullOrEmpty(CurrentVideoDetail)) {
                                    _this.CheckLock(CurrentVideoDetail.HasLock);
                                }
                                _this.CanLikeDislike1(false);
                                if (data.ResultObject.HasCountdownStatus == true) {
                                    if (!IsNullOrEmpty(data.ResultObject.CountdownUTCDateTime) && !IsNullOrEmpty(data.ResultObject.FinalPublishDateTime)) {
                                        var currentDateTime = new Date();

                                        //Assign DateTime in UTC to Jquery Object
                                        var FinalPublishUTCDateObject = data.ResultObject.FinalPublishDateTime;
                                        var CountDownUTCDateObject = data.ResultObject.CountdownUTCDateTime;

                                        //This will give client time zone specific DateTime
                                        var utcFinalPublishDateTime = new Date(Date.UTC(FinalPublishUTCDateObject.YearPartOfDate, FinalPublishUTCDateObject.MonthPartOfDate - 1, FinalPublishUTCDateObject.DayPartOfDate, FinalPublishUTCDateObject.HourPartOfDate, FinalPublishUTCDateObject.MinutePartOfDate, FinalPublishUTCDateObject.SecondPartOfDate));
                                        var utcCountdownUTCDateTime = new Date(Date.UTC(CountDownUTCDateObject.YearPartOfDate, CountDownUTCDateObject.MonthPartOfDate - 1, CountDownUTCDateObject.DayPartOfDate, CountDownUTCDateObject.HourPartOfDate, CountDownUTCDateObject.MinutePartOfDate, CountDownUTCDateObject.SecondPartOfDate));

                                        var localDate = new Date()
                                        var offsetToUTC = localDate.getTimezoneOffset();

                                        var zoneDiff;

                                        if (offsetToUTC != 0) {
                                            zoneDiff = -(offsetToUTC / 60);
                                        }
                                        else {
                                            zoneDiff = 0;
                                        }

                                        $.ajax({
                                            url: 'Script/jquery.countdown.js',
                                            async: false,
                                            dataType: "script",
                                            success: function (jsonData) {
                                            }
                                        });
                                        if (currentDateTime > utcCountdownUTCDateTime && currentDateTime <= utcFinalPublishDateTime) {
                                            //This has to be universal time as the CountDown plugin auto calculates the CountDown datetime depending upon the browser's TimeZone
                                            //var CountDownClientDateObject = new Date(CountDownUTCDateObject.YearPartOfDate, CountDownUTCDateObject.MonthPartOfDate - 1, CountDownUTCDateObject.DayPartOfDate, CountDownUTCDateObject.HourPartOfDate, CountDownUTCDateObject.MinutePartOfDate, CountDownUTCDateObject.SecondPartOfDate);
                                            //var FinalPublishClientDateObject = new Date(FinalPublishUTCDateObject.YearPartOfDate, FinalPublishUTCDateObject.MonthPartOfDate - 1, FinalPublishUTCDateObject.DayPartOfDate, FinalPublishUTCDateObject.HourPartOfDate, FinalPublishUTCDateObject.MinutePartOfDate, FinalPublishUTCDateObject.SecondPartOfDate);
                                            //console.log('year' + FinalPublishUTCDateObject.YearPartOfDate);
                                            //console.log(FinalPublishUTCDateObject.MonthPartOfDate - 1);
                                            //console.log('d' + FinalPublishUTCDateObject.DayPartOfDate);
                                            //console.log('h' + FinalPublishUTCDateObject.HourPartOfDate);
                                            //console.log('mm' + FinalPublishUTCDateObject.MinutePartOfDate);
                                            //console.log('s' + FinalPublishUTCDateObject.SecondPartOfDate);
                                            if ($('#countDown').countdown != null) {
                                                $('#countDown').countdown({ until: utcFinalPublishDateTime, timezone: zoneDiff, compact: true, onExpiry: _this.ExecEventCountDownExpiry });
                                                $('#countDown').css("display", "block");
                                            }
                                        }
                                    }
                                }
                            }

                            //End
                            if (DisplayVideoDetails == 1) {
                                // $('#event_title').addClass('event-section');

                                $(".event-section").removeClass('event-section');
                                $('#VideoDate').html(videoDetail.VideoDate);
                                $('#ViewsCount').show();
                                $(".like-unlike-pannel").show();
                                $("#related-videos").show();
                                $("#related-content").show();
                                $("#videoDescription").html(CurrentVideoDetail.Abstract);
                                $('.morelink').click(toogleReadMoreLess);

                                if (window.matchMedia('(max-width: 400px)').matches) {
                                    $(".video-main-caption").html(truncateString(CurrentVideoDetail.Title, 30));
                                }
                                else if (window.matchMedia('(max-width: 767px)').matches) {
                                    $(".video-main-caption").html(truncateString(CurrentVideoDetail.Title, 40));
                                }
                                else {
                                    $(".video-main-caption").html(truncateString(CurrentVideoDetail.Title, 58));
                                }

                                $(".video-main-time").html(CurrentVideoDetail.Duration);

                                if (CurrentVideoDetail.HasPromo == false && (CurrentVideoDetail.VideoStatus == 4 || CurrentVideoDetail.VideoStatus == 5)) {
                                    $("#eventvideoplayBtn").addClass('cursor-default');
                                }

                                var keywordsection = '';
                                var inspeckeywordsection = '';

                                var KeyWordsString = [];

                                if (!IsNullOrEmpty(CurrentVideoDetail.Keywordlist)) {
                                    if (CurrentVideoDetail.Keywordlist.length != 0) {
                                        $.each(CurrentVideoDetail.Keywordlist, function (index, keyword) {
                                            if (keyword.KeywordType == "custom") {
                                                keywordsection += KeywordHTML(keyword.KeywordName, keyword.KeywordId);
                                            }
                                            else {
                                                inspeckeywordsection += KeywordHTML(keyword.KeywordName, keyword.KeywordId);
                                            }
                                        });
                                    }
                                    if (keywordsection != '') {
                                        $('.custom-keywords').html("Custom Keywords");
                                    }
                                    if (inspeckeywordsection != '') {
                                        $('.inspec-keywords').html("Inspec Keywords");
                                    }

                                    $(".video-keywords-container").html(keywordsection);
                                    $(".inspec-video-keywords-container").html(inspeckeywordsection);
                                    if (CurrentVideoDetail.Keywordlist.length > 0) {
                                        //for (i = 0; i < CurrentVideoDetail.Keywordlist.length; i++) {
                                        //    //KeyWordsString += CurrentVideoDetail.Keywordlist[i].KeywordName + ' OR ';
                                        //    KeyWordsString.push(CurrentVideoDetail.Keywordlist[i].KeywordName);
                                        //}

                                        //var KeyWordsQuery = '["' + KeyWordsString.join('"] OR ["') + '"]';

                                        //console.log(KeyWordsQuery);

                                        var googleSearch = new GoogleSearch();
                                        //googleSearch.SearchTerm = KeyWordsQuery;
                                        googleSearch.Init(CurrentVideoDetail.VideoNo);
                                    }
                                }

                                //speaker
                                var speakersection = ''
                                if (CurrentVideoDetail.Speakers != null) {
                                    $.each(CurrentVideoDetail.Speakers, function (index, speaker) {
                                        var SpeakerImage = '';
                                        if (speaker.PictureUrl.indexOf("$") != -1) {
                                            SpeakerImage = speaker.PictureUrl.slice(0, speaker.PictureUrl.lastIndexOf("$"));
                                        }
                                        else
                                            SpeakerImage = CurrentVideoDetail.SpeakerImageSource + speaker.PictureUrl;

                                        speakersection += SpeakerHTML(index, speaker.Title, speaker.FirstName, speaker.LastName, SpeakerImage);

                                        $(".carousel-inner").html(speakersection);
                                    });
                                }

                                //channel list
                                if (CurrentVideoDetail.ChannelList != null) {
                                    var channelSectionHtml = '<div class="margin-right-15 float-left" style="padding-top: 4px"> This video is from: </div>'

                                    $.each(CurrentVideoDetail.ChannelList, function (index, channel) {
                                        channelSectionHtml += ChannelHTML(channel.Name, channel.Id, channel.ChannelIconImage);
                                    });
                                }

                                $("#videoChannel").html(channelSectionHtml);

                                var relatedVideosHTML = '';
                                relatedVideos = CurrentVideoDetail.relatedVideos;
                                if (relatedVideos != null && relatedVideos != '') {
                                    var time = new Date();
                                    //Rakesh :Related video Count
                                    $('#spnRelatedVideos').html(relatedVideos.length);
                                    $.each(relatedVideos, function (index, data) {
                                        relatedVideosHTML += getRelatedVideoEventHTML(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.SubscriptionType, data.Duration, data.IsSeries, data.SeriesCount, data.SeriesCreatedYear);
                                    });
                                    //Rakesh : Added to remove Loaded show videos
                                    $('#LazyLoader').addClass('display-none');
                                    $('#related-videos-dynamic').removeClass('display-none');

                                    $(document).ready($('#related-videos-dynamic').html(relatedVideosHTML));
                                }

                                _this.CheckLock(CurrentVideoDetail.HasLock);
                                _this.AllowDownload(CurrentVideoDetail.AllowDownload);
                                _this.CanLikeDislike1(CurrentVideoDetail.CanLikeDislike);
                                _this.ShowRelatedContent(CurrentVideoDetail.RelatedContent);

                                _this.RenderAttachment(CurrentVideoDetail.AllowAttachmentDownload);
                                _this.RenderTranscript(CurrentVideoDetail.AllowAttachmentDownload);
                                _this.RenderIETDigitalLibrary(CurrentVideoDetail.DigitalLibrary);

                                $('#backgroundImage').attr("src", CurrentVideoDetail.DisplayImage);
                                //$('#backgroundImage').attr("alt", CurrentVideoDetail.Title);
                                $('#outer_background_image').css("background-image", 'url("' + CurrentVideoDetail.DisplayImage + '")');
                                //if (CurrentVideoDetail.Permissions[0].VideoThumbnailURL != "" && CurrentVideoDetail.Permissions[0].VideoThumbnailURL != null) {
                                //    $('#outer_background_image').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailURL + "')");
                                //    $('#backgroundImage').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailURL + "')");
                                //}
                                //else {
                                //    $('#outer_background_image').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailBannerURL + "')");
                                //    $('#backgroundImage').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailBannerURL + "')");
                                //}

                                if ($('#countDown').countdown != null) {
                                    $('#countDown').css("display", "none");
                                }

                                if (CurrentVideoDetail.HasPromo == true) {
                                    if (CurrentVideoDetail.PromoType != "video") {
                                        $("#eventvideoplayBtn").addClass('cursor-default');
                                    }
                                    $("input[name='txtembed']").addClass('display-none');
                                    _this.AllowDownload(false);
                                    _this.CanLikeDislike1(false);
                                    var PromoDetail = {
                                        HasCountdown: videoDetail.HasCountdownStatus,
                                        CountDateTime: videoDetail.CountdownDateTime
                                    }
                                    $.ajax({
                                        url: 'Script/jquery.countdown.js',
                                        async: false,
                                        dataType: "script",
                                        success: function (jsonData) {
                                        }
                                    });
                                    if (PromoDetail.HasCountdown == true) {
                                        //var currentDate = new date();
                                        //countlogic
                                        if (!IsNullOrEmpty(videoDetail.CountdownUTCDateTime) && !IsNullOrEmpty(videoDetail.FinalPublishDateTime)) {
                                            var currentDateTime = new Date();

                                            //Assign DateTime in UTC to Jquery Object
                                            var FinalPublishUTCDateObject = videoDetail.FinalPublishDateTime;
                                            var CountDownUTCDateObject = videoDetail.CountdownUTCDateTime;

                                            //This will give client time zone specific DateTime
                                            var utcFinalPublishDateTime = new Date(Date.UTC(FinalPublishUTCDateObject.YearPartOfDate, FinalPublishUTCDateObject.MonthPartOfDate - 1, FinalPublishUTCDateObject.DayPartOfDate, FinalPublishUTCDateObject.HourPartOfDate, FinalPublishUTCDateObject.MinutePartOfDate, FinalPublishUTCDateObject.SecondPartOfDate));
                                            var utcCountdownUTCDateTime = new Date(Date.UTC(CountDownUTCDateObject.YearPartOfDate, CountDownUTCDateObject.MonthPartOfDate - 1, CountDownUTCDateObject.DayPartOfDate, CountDownUTCDateObject.HourPartOfDate, CountDownUTCDateObject.MinutePartOfDate, CountDownUTCDateObject.SecondPartOfDate));

                                            var localDate = new Date()
                                            var offsetToUTC = localDate.getTimezoneOffset();

                                            var zoneDiff;

                                            if (offsetToUTC != 0) {
                                                zoneDiff = -(offsetToUTC / 60);
                                            }
                                            else {
                                                zoneDiff = 0;
                                            }

                                            if (currentDateTime > utcCountdownUTCDateTime && currentDateTime <= utcFinalPublishDateTime) {
                                                //This has to be universal time as the CountDown plugin auto calculates the CountDown datetime depending upon the browser's TimeZone
                                                //var CountDownClientDateObject = new Date(CountDownUTCDateObject.YearPartOfDate, CountDownUTCDateObject.MonthPartOfDate - 1, CountDownUTCDateObject.DayPartOfDate, CountDownUTCDateObject.HourPartOfDate, CountDownUTCDateObject.MinutePartOfDate, CountDownUTCDateObject.SecondPartOfDate);
                                                //var FinalPublishClientDateObject = new Date(FinalPublishUTCDateObject.YearPartOfDate, FinalPublishUTCDateObject.MonthPartOfDate - 1, FinalPublishUTCDateObject.DayPartOfDate, FinalPublishUTCDateObject.HourPartOfDate, FinalPublishUTCDateObject.MinutePartOfDate, FinalPublishUTCDateObject.SecondPartOfDate);
                                                //console.log('year' + FinalPublishUTCDateObject.YearPartOfDate);
                                                //console.log(FinalPublishUTCDateObject.MonthPartOfDate - 1);
                                                //console.log('d' + FinalPublishUTCDateObject.DayPartOfDate);
                                                //console.log('h' + FinalPublishUTCDateObject.HourPartOfDate);
                                                //console.log('mm' + FinalPublishUTCDateObject.MinutePartOfDate);
                                                //console.log('s' + FinalPublishUTCDateObject.SecondPartOfDate);
                                                if ($('#countDown').countdown != null) {
                                                    $('#countDown').countdown({ until: utcFinalPublishDateTime, timezone: zoneDiff, compact: true, onExpiry: _this.ExecVideoCountDownExpiry });
                                                    $('#countDown').css("display", "block");
                                                }
                                            }
                                        }
                                    }
                                }
                                else {
                                    var entryid = CurrentVideoDetail.EntryId;
                                    // alert(entryid);
                                    var url = window.location.href;
                                    var embedurl = '<iframe width="550" height="310" name="' + entryid + '" src="' + url.substring(0, url.lastIndexOf('/') + 1) + "EmbedPlayer.aspx?videoid=" + eventFilter.VideoNo + "&guid=" + this.CurrentVideoDetail.VideoId + '" allowfullscreen></iframe>';
                                    var facebookTwitterLink = url.substring(0, url.lastIndexOf('/') + 1) + "EmbedPlayer.aspx?videoid=" + eventFilter.VideoNo + "&guid=" + this.CurrentVideoDetail.VideoId;
                                    $("input[name='txtembedEvent']").val(embedurl);
                                    $("input[name='txtFacebookTwitterEvent']").val(facebookTwitterLink);
                                }
                            }
                            //Player details

                            var KPlayerDetails;

                            if (!IsNullOrEmpty(data.ResultObject.PlayerViewModelresult.ResultObject)) {
                                // KPlayerDetails = data.ResultObject.PlayerViewModelresult.ResultObject.KalturaPlayerDetail;
                            }

                            if (CurrentVideoDetail.HasUserAccess) {
                                //player logic
                                //this.PlayerDetail = {
                                //    PartnerId: KPlayerDetails.PartnerId,
                                //    PlayerId: KPlayerDetails.PlayerId,
                                //    CacheStrng: KPlayerDetails.PlayerCacheString,
                                //    EntryId: CurrentVideoDetail.EntryId,
                                //    Ks: KPlayerDetails.PlayerSession
                                //};
                            }
                            RenderEventScript();
                            if ((eventDetail.Price != '0' && DisplayVideoDetails == 0 && data.ResultObject.HasLock == true) || (CurrentVideoDetail.HasLock && DisplayVideoDetails == 1)) {
                                if (!IsNullOrEmpty(eventFilter.AccessCode) && parseBool(sessionStorage.getItem("accessCodeFlag")) == false && parseBool(sessionStorage.getItem("accessCodeFlag")) != null) {
                                    var messageViewModel = new MessageViewModel();
                                    messageViewModel.CreateWarningMessage("Access code entered is invalid", "overlayId", "okButtonId")
                                    messageViewModel.ShowOverLay();

                                    sessionStorage.removeItem("accessCode");
                                    sessionStorage.removeItem("accessCodeType");
                                    sessionStorage.removeItem("delegateName");

                                    //flag to check if QnA is available  for this event
                                    //QnAAvailable = false;
                                    //flag to check if QnA is visible

                                    //flag to check if Poll is available for this event
                                    //PollAvailable = false;
                                    //flag to check if Poll is visible

                                    onEventPageLoad();
                                }
                                var EventPremiumTxt = "";
                                var premiumPriceDetail = '';
                                if (DisplayVideoDetails != 1) {
                                    _this.CheckLock(data.ResultObject.HasLock);
                                }
                                else {
                                    if (CurrentVideoDetail.PriceType != "Free") {
                                        EventPremiumTxt = EventPremiumTxt + '<div id="premium_video_text" class="premium_video_text premium_video_mobile_text col-md-10" style="text-align:center">';

                                        //if (CurrentVideoDetail.ChannelCategoryTypeId == 1 || (CurrentVideoDetail.ChannelCategoryTypeId == 2 || CurrentVideoDetail.ChannelCategoryTypeId == 3)) {
                                        if (parseBool(localStorage.getItem("IsIndividualUser")) == true || (sessionStorage.getItem("LogonId") == null || sessionStorage.getItem("LogonId") == "")) {
                                            if (CurrentVideoDetail.PriceType == 'Subscription' && CurrentVideoDetail.ChannelCategoryTypeId == 1) {                                                
                                                EventPremiumTxt += ' This video is part of paid channel ' + CurrentVideoDetail.ChannelName + '. Please purchase the channel to gain access to the video.<br/>';
                                                EventPremiumTxt += '<div><button type="button" class="btn btn-default premium_video_btn" data-hasindex="true" data-videoid="' + eventFilter.VideoId + '"  data-innerroutename="BuyChannel">Buy Channel</button></div>';

                                                if (eventDetail.Price != '0') {
                                                    if (data.LoginStatus == ResultStatus.Failed || !(CurrentVideoDetail.EventDetails.IsUserPurchasedPremiumEvent)) {
                                                        EventPremiumTxt += '<p class="margin-top-10">This video is part of paid event ' + '<a href="#" data-toggle="modal" data-target="#premiumEventDetails">' + CurrentVideoDetail.EventDetails.Title + '</a>' + '. Please purchase the event to gain access to the video.<p>';
                                                        EventPremiumTxt += '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                                                        $("#spnEventName").text(eventDetail.Title);
                                                        $("#tblEventvideoDetails").html(CurrentVideoDetail.EventDetails.eventVideoDetails);
                                                        $('#tblEventvideoDetails').paging({ limit: 5 });

                                                        if ($(window).width() < 500) {
                                                            $("#divVideoContainer").addClass('premiumVideoWithBuyEvent');
                                                            $(".paging-nav").addClass('paginationDiv');
                                                            $("#divEventDetails").addClass('divBuyEvent');
                                                        }
                                                    }
                                                }
                                            }
                                            else if (CurrentVideoDetail.PriceType == 'Premium') {
                                                if (CurrentVideoDetail.PremiumDiscountPercentage != '0' && CurrentVideoDetail.PremiumDiscountAmount != '0') {
                                                    EventPremiumTxt += '<p>This is a premium video.You have a ' + CurrentVideoDetail.PremiumDiscountPercentage + '% discount on this video.</p>';
                                                    premiumPriceDetail = '<p>Your new purchase price for this video is only £' + CurrentVideoDetail.PremiumDiscountAmount + ' excluding tax.</p>';
                                                    EventPremiumTxt += premiumPriceDetail;
                                                }
                                                else {
                                                    EventPremiumTxt += '<p>This is a premium video. You can purchase this video for only £' + CurrentVideoDetail.PremiumPrice + '  excluding tax.<p/>';
                                                }
                                                EventPremiumTxt += '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyVideoPrompt">Buy video</button></div>';

                                                if (eventDetail.Price != '0') {
                                                    if ((data.LoginStatus == ResultStatus.Failed && CurrentVideoDetail.EventDiscount > 0) ||
                                                        (!(CurrentVideoDetail.EventDetails.IsUserPurchasedPremiumEvent) && (CurrentVideoDetail.PremiumDiscountPercentage == 0 && (CurrentVideoDetail.DiscountType == 'No Discount')) && CurrentVideoDetail.EventDiscount > 0)) {
                                                        EventPremiumTxt += '<p class="margin-top-10">This video is part of paid event ' + '<a href="#" data-toggle="modal" data-target="#premiumEventDetails">' + CurrentVideoDetail.EventDetails.Title + '</a>' + '. Please purchase the event to gain discount on the video.<p>';
                                                        EventPremiumTxt += '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                                                        $("#spnEventName").text(eventDetail.Title);
                                                        $("#tblEventvideoDetails").html(CurrentVideoDetail.EventDetails.eventVideoDetails);
                                                        $('#tblEventvideoDetails').paging({ limit: 5 });

                                                        if ($(window).width() < 500) {
                                                            $("#divVideoContainer").addClass('premiumVideoWithBuyEvent');
                                                            $(".paging-nav").addClass('paginationDiv');
                                                            $("#divEventDetails").addClass('divBuyEvent');
                                                        }
                                                    }

                                                    if (CurrentVideoDetail.EventDiscount < 100) {
                                                        $('#rdoEvent').attr('onclick', 'return false;');
                                                        $('#rdoEvent').addClass('disabledinput');
                                                        $('#rdoEventSpan').addClass('disabledEventSpan');
                                                    }
                                                }
                                            }
                                            else if (CurrentVideoDetail.PriceType == 'Event Priced' && eventDetail.Price != '0') {
                                                EventPremiumTxt += '<p>This video is part of paid event ' + eventDetail.Title + '. Please purchase the event to gain access to the video.</p>';
                                                EventPremiumTxt += '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                                            }
                                        }
                                        else {
                                            if (CurrentVideoDetail.PriceType == 'Subscription') {
                                                //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                                                
                                                if (data.Message != null && data.Message != null) {
                                                    var messageViewModel = new MessageViewModel();
                                                    messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                                    messageViewModel.ShowOverLay();
                                                    //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end

                                                }EventPremiumTxt += ' This video is part of paid channel ' + CurrentVideoDetail.ChannelName + '. Kindly contact the IET Administrator to gain access to this channel.';
                                            }
                                            else if (CurrentVideoDetail.PriceType == 'Premium') {
                                                //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                                               
                                                if (data.Message != null && data.Message != null) {
                                                    var messageViewModel = new MessageViewModel();
                                                    messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                                    messageViewModel.ShowOverLay();
                                                }
                                                //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end
                                                EventPremiumTxt += 'This is a premium video. Kindly contact the IET Administrator to gain access to this video.';
                                                if (eventDetail.Price != '0') {
                                                    if ((data.LoginStatus == ResultStatus.Failed) || (!(CurrentVideoDetail.EventDetails.IsUserPurchasedPremiumEvent) && (CurrentVideoDetail.PremiumDiscountPercentage == 0 && (CurrentVideoDetail.DiscountType == 'No Discount' || CurrentVideoDetail.DiscountType == null)))) {
                                                        if (CurrentVideoDetail.EventDiscount < 100) {
                                                            $('#rdoEvent').attr('onclick', 'return false;');
                                                            $('#rdoEvent').addClass('disabledinput');
                                                            $('#rdoEventSpan').addClass('disabledEventSpan');
                                                        }
                                                    }
                                                }
                                            }
                                            else if (CurrentVideoDetail.PriceType == 'Event Priced' && eventDetail.Price != '0') {
                                                //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                                                
                                                if (data.Message != null && data.Message != null) {
                                                    var messageViewModel = new MessageViewModel();
                                                    messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                                    messageViewModel.ShowOverLay();
                                                }
                                                //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end
                                                EventPremiumTxt += ' This video is part of paid event ' + eventDetail.Title + '. Kindly contact the IET Administrator to gain access to this event.';
                                            }
                                        }

                                        if (data.LoginStatus == ResultStatus.Failed) {
                                            EventPremiumTxt += '<div class="margin-top-10"> Already bought this video? To view please <a href="view/LoginNew.html">Log in</a></div>';
                                        }
                                        //}
                                        if (eventDetail.MemberDiscount != '0' && eventDetail.DiscountAmount > 0) {
                                            $("#spnPremiumEventPrice").text(eventDetail.DiscountAmount);
                                        }
                                        else {
                                            $("#spnPremiumEventPrice").text(eventDetail.Price);
                                        }

                                        $(".btnEventCheckOutRedirect").attr({
                                            "data-lastRouteName": 'eventvideoid',
                                            "data-innerroutename": 'address',
                                            "data-eventid": eventFilter.EventId,
                                            "data-videono": CurrentVideoDetail.VideoNo,
                                            "data-displayvideodetails": 1
                                        });
                                    }

                                    if (CurrentVideoDetail.IndividualUserType != "member" && CurrentVideoDetail.IndividualUserType != "student") {
                                        if ((CurrentVideoDetail.ChannelCategoryTypeId == 2 || CurrentVideoDetail.ChannelCategoryTypeId == 3) && CurrentVideoDetail.PriceType == 'Subscription') {
                                            EventPremiumTxt += "<div class='margin-top-10'>This video is part of Members/Students channel. To view these, please  <a onclick=OpenURL('http://www.theiet.org/membership/join/index.cfm')>join the IET</a>. Already a Member? To view,  <a href='view/LoginNew.html'>please log in</a></div>"
                                        }
                                    }
                                    else {
                                        if (data.LoginStatus == ResultStatus.Successful) {
                                            if (CurrentVideoDetail.ChannelCategoryTypeId == 2 && CurrentVideoDetail.IndividualUserType == "member" && CurrentVideoDetail.PriceType == 'Subscription') {
                                                EventPremiumTxt += "<div class='margin-top-10'> This video is part of Students channel. To view these, please <a onclick=OpenURL('http://www.theiet.org/membership/join/index.cfm')>join the IET</a>. Already a Student Member? To view, <a href='view/LoginNew.html'>please log in</a></div>"
                                            }
                                            if (CurrentVideoDetail.ChannelCategoryTypeId == 3 && CurrentVideoDetail.IndividualUserType == "student" && CurrentVideoDetail.PriceType == 'Subscription') {
                                                EventPremiumTxt += "<div class='margin-top-10'> This video is part of Members channel. To view these, please <a onclick=OpenURL('http://www.theiet.org/membership/join/index.cfm')>join the IET</a>. Already a Member? To view, <a href='view/LoginNew.html'>please log in</a></div>"
                                            }
                                        }
                                    }

                                    EventPremiumTxt += '<div style="margin-top:10px">If you have an Access Code, Please enter code <a href="" data-toggle="modal" data-target="#modal_SingleAccessCode">here</a></div>';
                                }

                                if (eventDetail.Price != '0' && DisplayVideoDetails == 0 && data.ResultObject.HasLock == true && DisplayVideoDetails != 1) {
                                    EventPremiumTxt = EventPremiumTxt + '<div id="premium_video_text" class="premium_video_text premium_video_mobile_text col-md-10" style="text-align:center">';

                                    if (parseBool(localStorage.getItem("IsIndividualUser")) == true || (sessionStorage.getItem("LogonId") == null || sessionStorage.getItem("LogonId") == "")) {
                                        if (eventDetail.MemberDiscount != '0' && eventDetail.DiscountAmount > 0) {
                                            EventPremiumTxt += '<p>This is a premium event.You have a ' + eventDetail.MemberDiscount + '% discount on this event.</p>';
                                            premiumPriceDetail = '<p>Your new purchase price for this event is only £' + eventDetail.DiscountAmount + ' excluding tax.</p>';
                                            EventPremiumTxt += premiumPriceDetail;
                                        }
                                        else {
                                            EventPremiumTxt += '<p>This is a premium event. You can purchase this event for only £' + eventDetail.Price + '  excluding tax.<p/>';
                                        }
                                        EventPremiumTxt += '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                                    }
                                    else {
                                        //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                                        
                                        if (data.Message != null && data.Message != null) {
                                            var messageViewModel = new MessageViewModel();
                                            messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                            messageViewModel.ShowOverLay();
                                        }
                                        //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end
                                        EventPremiumTxt += 'This is a premium event. Kindly contact the IET Administrator to gain access to this event.';
                                    }

                                    if (data.LoginStatus == ResultStatus.Failed) {
                                        EventPremiumTxt += '<div class="margin-top-10"> Already bought this event? To view please <a href="view/LoginNew.html">Log in</a></div>';
                                    }

                                    EventPremiumTxt += '<div style="margin-top:10px">If you have an Event Access Code, Please enter code <a onclick="BindBtnEventAccessCodeOnEventLandingPage()">here</a></div>';

                                    if (eventDetail.MemberDiscount != '0' && eventDetail.DiscountAmount > 0) {
                                        $("#spnPremiumEventPrice").text(eventDetail.DiscountAmount);
                                    }
                                    else {
                                        $("#spnPremiumEventPrice").text(eventDetail.Price);
                                    }

                                    $(".btnEventCheckOutRedirect").attr({
                                        "data-lastRouteName": 'event',
                                        "data-innerroutename": 'address',
                                        "data-eventid": eventFilter.EventId,
                                        "data-displayvideodetails": 0
                                    });
                                }

                                EventPremiumTxt = EventPremiumTxt + '</div>';
                                $(".video-overlay-div").addClass('alpha30');
                                $(".video-overlay-text").html(EventPremiumTxt);
                                var premium_video_div_height = getDivHeight($("#premium_video_text").height());
                                var t = $(".videoBtns").height() / 2;
                                $("div#premium_video_text").css("margin-top", "-" + premium_video_div_height - t);

                                $('#modal_EventPageaccessCode').on('shown.bs.modal', function () {
                                    if (!(navigator.userAgent.match(/(iPod|iPhone|iPad)/))) {
                                        $('#delegate_name').focus();

                                        $('#PremiumEvent_AccessCode').unbind('keypress');
                                        $('#PremiumEvent_AccessCode').bind('keypress', function (e) {
                                            var key = e.which;
                                            if (key == 13)  // the enter key code
                                            {
                                                StoreEventPageAccessCode();

                                                $("[data-innerroutename='PremiumEventAccessId']").click();
                                            }
                                        });
                                    }
                                });

                                $('#lockBtn').addClass('cursor-default');
                                $(window).resize(function () {
                                    var premium_video_div_height = getDivHeight($("#premium_video_text").height());
                                    var t = $(".videoBtns").height() / 2;
                                    $("div#premium_video_text").css("margin-top", "-" + premium_video_div_height - t);
                                    function getNoPaddingHeight(elementDiv) {
                                        //alert("Hi");
                                        if (document.getElementById(elementDiv) != null) {
                                            $('#' + elementDiv).children().addClass('no-bottom-top-margin');
                                            var parentDiv = document.getElementById(elementDiv);
                                            var ht = parentDiv.scrollHeight;
                                            $('#' + elementDiv).children().removeClass('no-bottom-top-margin');
                                            return ht;
                                        }
                                    }
                                });
                                handleEventQnA();
                            }
                            else {
                                if (!IsNullOrEmpty(eventFilter.AccessCode)) {
                                    sessionStorage.setItem("accessCodeFlag", true);

                                    if (IsNullOrEmpty(sessionStorage.getItem("LogonId")) == true) {
                                        if (parseInt(sessionStorage.getItem("accessCodeType")) == 1) {
                                            //localStorage.setItem("Welcome", sessionStorage.getItem("delegateName"));
                                        }
                                        else {
                                            if (data.ResultObject != null && data.ResultObject.PlayerViewModelresult.ResultObject != null && data.ResultObject.PlayerViewModelresult.ResultObject.AccessSpeaker != null) {
                                                localStorage.setItem("Welcome", data.ResultObject.PlayerViewModelresult.ResultObject.AccessSpeaker.FirstName + " " + data.ResultObject.PlayerViewModelresult.ResultObject.AccessSpeaker.LastName);
                                            }
                                        }
                                        //Additional login to check if user is login then only set the login options
                                        if (!IsNullOrEmpty(localStorage.getItem("LoginStatus")) && localStorage.getItem("LoginStatus") !== "-1") {
                                            var objLoginRepository = new LoginRepository();
                                            objLoginRepository.setMessageForSpeaker();
                                        }
                                    }
                                }
                            }
                            // $('.toggle-video-visibility').click(_this.toggleVideoVisibility);
                            //RenderScript();
                            $('.modal-backdrop').remove();

                            //event binding-start

                            $(".eventtitle").html(eventDetail.Title)
                            $(".eventwebsite").attr("href", eventDetail.Url)
                            $(".eventwebsite").html(eventDetail.Url)
                            $(".eventlogo").attr('src', eventDetail.EventLogo);// eventDetail.EventLogo);

                            //For Sponser Div
                            $(".sponserdiv").html("");
                            if (eventDetail.SponseredItem != null && eventDetail.SponseredItem.SponserImagePath != null) {
                                var str = "<a href='#' onclick=OpenURL('" + eventDetail.SponseredItem.SponserURL + "')><img src='" + eventDetail.SponseredItem.SponserImagePath + "' class='right-video-banner-thumbnail-image'></a>";
                                $('.sponserdiv').append(str);
                            }
                            else {
                                $('#video-content').parent("div").removeClass('col-md-6 col-sm-6').addClass('col-md-9 col-sm-9');
                            }
                            //event binding end     
                            VideoRenderScript();
                            routeProvider.bindInnerRoutes();
                            eventContext.BindPlaybtnClick();

                            if (!WebService.DisableChat) {
                                if (CurrentVideoDetail.VideoStatus == 1) {
                                    var qna = new QnA();
                                    qna.submitMessage();
                                    qna.Init('Event', true);

                                    //var hub = qna.Chat;

                                    qna.QnARepository.GetMessagesForGroup(qna.GroupName);
                                    qna.QnARepository.GetAllAbusiveWords();
                                }
                                else {
                                    //var qna = new QnA();
                                    //qna.Init('Event', false);
                                    //qna.QnARepository.GetMessagesForGroup(qna.GroupName);
                                    ////$('.QnA-main').attr('disabled', 'disabled');
                                    //$('#txtMessage').val('Q&A for the event is now closed');
                                    //$('#txtMessage').attr('disabled', 'disabled');
                                    //$('#btn_reply').removeClass('custom_pointer');

                                }

                                EventIsDisplayQA = eventDetail.EventIsDisplayQA;
                            }

                            if (CurrentVideoDetail.VideoStatus == 1) {
                                var poll = new Poll();
                                poll.Init('Event');

                                EventIsDisplayPolling = eventDetail.EventIsDisplayPolling;
                            }

                            //EventIsDisplayQA = eventDetail.EventIsDisplayQA;
                            //EventIsDisplayPolling = eventDetail.EventIsDisplayPolling;

                            // console.log('eventrepo' + PollQuestionAvailable);

                            if (PollQuestionAvailable == 0) {
                                //This is to analyze the flow

                                EventIsDisplayPolling = false;
                            }

                            if (EventIsDisplayQA == 1) {
                                QnAVisible = 1;
                            }
                            else {
                                QnAVisible = 0;
                            }

                            if (EventIsDisplayPolling == 1) {
                                PollVisible = 1;
                            }
                            else {
                                PollVisible = 0;
                            }

                            if (EventIsDisplayQA == 1 && EventIsDisplayPolling == 1) {
                                QnAVisible = 0;
                            }

                            //flag to check if QnA is available  for this event
                            QnAAvailable = EventIsDisplayQA;
                            //flag to check if QnA is visible

                            if (WebService.DisableChat) {
                                QnAAvailable = false;
                            }

                            //flag to check if Poll is available for this event
                            PollAvailable = EventIsDisplayPolling;
                            //flag to check if Poll is visible

                            onEventPageLoad();

                            PollQuestionAvailable = 0;
                        }

                        else {
                            //not access logic
                            _this.CheckLock(CurrentVideoDetail.HasLock);
                            _this.AllowDownload(CurrentVideoDetail.AllowDownload);
                            _this.CanLikeDislike1(CurrentVideoDetail.CanLikeDislike);
                        }

                        if (DisplayVideoDetails == 0) {
                            _this.CheckLock(data.ResultObject.HasLock);
                        }
                    }
                }
                else {
                    $("#videoDescription").html("Event not found!!").css({ "font-size": "25px", "font-weight": "bold" });
                    $("#EventDecription").html("Event not found!!").css({ "font-size": "25px", "font-weight": "bold" });
                    //Rakesh:Commented for thumbnail New UI Change
                    // $('#backgroundImage').css("background-image", "url('Images/img_noevent.jpg')");
                    $('#backgroundImage').attr("src", 'Images/img_noevent.jpg');

                    $('#outer_background_image').css("background-image", "url('Images/img_novideo.png')");
                    $('.eventnotfound').hide()
                    $(".embedmodal").css('display', 'none');
                }
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    getUrlParameter: function () {
        // Read a page's GET URL variables and return them as an associative array.
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },

    CheckUserIsLoggedInOnEventPage: function () {
        var object = {
            Data: {
                "logonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId")
            }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/CheckUserIsLoggedIn',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.LoginStatus) {
                    $("#modal_EventPageaccessCode").modal('show');
                }
                else {
                    _this.MessageViewModel.CreateConfirmationMessageWithOKCancelWithTitle(data.Message, "overlayId", "LoginButtonId", "RegisterButtonId", 'Login', 'Register', function () {
                        $("#LoginButtonId").unbind();
                        $("#LoginButtonId").bind("click", function (e) {
                            sessionStorage.setItem("IsEventVideoAceess", "true");
                            sessionStorage.setItem("withindex", -1);
                            sessionStorage.setItem("RedirectLocation", window.location.href);
                            sessionStorage.setItem("RedirectFrom", window.location.href);
                            sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href)
                            location.href = "view/" + Application.Login.BaseURL;
                        });
                        $("#RegisterButtonId").unbind();
                        $("#RegisterButtonId").bind("click", function (e) {
                            sessionStorage.setItem("withindex", -1);
                            sessionStorage.setItem("RedirectLocation", window.location.href);
                            sessionStorage.setItem("RedirectFrom", window.location.href);
                            sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href)
                            policyLogin(helloNetwork.adB2CSignInSignUp, loginDisplayType.Page);
                        });
                    });
                    _this.MessageViewModel.ShowOverLay();
                }
            },
            function (data, status, headers, config) {
                Spinner.Stop();
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    ExecEventCountDownExpiry: function () {
        $('#countDown').hide();
        location.reload(true)
        //  $("[data-innerroutename='video']").click();
    },
    ExecVideoCountDownExpiry: function () {
        $('#countDown').hide();
        location.reload(true)
        //  $("[data-innerroutename='video']").click();
    },
    GetEventVideoDayWise: function (currentRouteSetting, routeProvider, routeCurrentContext, eventFilter) {
        var _this = this;
        var object = {
            Data: { "eventfilter": eventFilter }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'EventManagement/EventService.svc/GetEventVideoDayWise',
            function (data, status, headers, config) {
                if (data != null && data.ResultObject != null) {
                    $(".divVideoSchedule").html("");
                    var loginStatus = data.LoginStatus;
                    var eventDetail = data.ResultObject.EvenData;
                    var selectedDate = data.ResultObject.SelectedEventDate.replace(new RegExp("-", "g"), '/').split("/");
                    var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
                    var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                    var fromDate = eventDetail.EventFromDate.replace(new RegExp("-", "g"), '/').split("/");
                    var toDate = eventDetail.EventToDate.replace(new RegExp("-", "g"), '/').split("/");
                    var dateFromObj = new Date(fromDate[2], fromDate[1] - 1, fromDate[0]);
                    var dateToObj = new Date(toDate[2], toDate[1] - 1, toDate[0]);

                    var selectedDate = new Date(selectedDate[2], selectedDate[1] - 1, selectedDate[0]);
                    // to display header above div
                    var strhtag = "";
                    var currentdateformat = "";
                    var activeRoom = "";
                    $.each(data.ResultObject.EventRooms, function (index, data) {
                        if (data.Id == eventDetail.ActiveRoomId) {
                            activeRoom = data.Name;
                        }
                    });
                    currentdateformat = (weekday[selectedDate.getDay()]) + " " + selectedDate.getDate() + " " + months[selectedDate.getMonth()] + " " + selectedDate.getFullYear();
                    if (data.ResultObject.DaywiseEventVideosList.length == 0) {
                        strhtag = "<h4>No Video scheduled for " + currentdateformat + " in " + activeRoom + " room</h4>";
                    }
                    else {
                        strhtag = "<h4>Video schedule for " + currentdateformat + " in " + activeRoom + " room</h4>";
                    }

                    if ($.trim(eventFilter.SelectedEventDate) == "") {
                        $("#ulVideoScheduletabs").html("");
                        while (dateFromObj <= dateToObj) {
                            var strForDays = "";
                            var liatag = "";
                            var month = (dateFromObj.getMonth() + 1);
                            if (month < 10) {
                                month = '0' + month;
                            }
                            var date = dateFromObj.getDate();
                            if (date < 10) {
                                date = '0' + date;
                            }

                            var dateValue = date + "/" + month + "/" + dateFromObj.getFullYear();
                            var liatag = "<a href='' data-toggle='tab' data-innerroutename='daywisevideoschedule' data-eventId=" + eventDetail.Id + "  data-dateValue=" + dateValue + " data-toggle='tab'>" + (weekday[dateFromObj.getDay()]) + "</a>";
                            if (dateFromObj.toDateString() == selectedDate.toDateString()) {
                                $("#ulVideoScheduletabs").append("<li class='active'>" + liatag + "</li>");
                            }
                            else {
                                $("#ulVideoScheduletabs").append("<li>" + liatag + "</li>");
                            }

                            var newDate = dateFromObj.setDate(dateFromObj.getDate() + 1);
                            dateFromObj = new Date(newDate);
                        }
                        /*Initiating Responsive Tabs*/
                        $('.tab-responsive-event-days').tabdrop({ text: 'More Days' });
                        /*Initiating Responsive Tabs End*/
                    }

                    if (data.ResultObject.EventRooms != null) {
                        $('.tab-responsive-event-rooms').unbind().removeData();
                        $("#ulEventRoomstabs").html("");

                        var eventDate;
                        var eventFromDate = new Date(fromDate[2], fromDate[1] - 1, fromDate[0]);
                        var monthevent = (eventFromDate.getMonth() + 1);
                        if (monthevent < 10) {
                            monthevent = '0' + monthevent;
                        }
                        var datevent = eventFromDate.getDate();
                        if (datevent < 10) {
                            datevent = '0' + datevent;
                        }
                        if ($.trim(eventFilter.SelectedEventDate) == "") {
                            eventDate = datevent + "/" + monthevent + "/" + eventFromDate.getFullYear();
                        }
                        else {
                            eventDate = eventFilter.SelectedEventDate;
                        }
                        $.each(data.ResultObject.EventRooms, function (index, data) {
                            var lieventName = "<a href='' data-toggle='tab' data-innerroutename='daywisevideoschedule' data-eventId=" + eventDetail.Id + "  data-dateValue=" + eventDate + "  data-roomId=" + data.Id + " data-toggle='tab'>" + data.Name + "</a>";
                            if (data.Id == eventDetail.ActiveRoomId) {
                                $("#ulEventRoomstabs").append("<li class='active'>" + lieventName + "</li>");
                            }
                            else {
                                $("#ulEventRoomstabs").append("<li>" + lieventName + "</li>");
                            }
                        });
                        $('.tab-responsive-event-rooms').tabdrop({ text: 'More Rooms' });
                    }

                    $(".divVideoSchedule").append(strhtag);

                    $.each(data.ResultObject.DaywiseEventVideosList, function (index, data) {
                        // to display actual contents inside div :divVideoSchedule
                        var strdivtag = "";
                        var SpeakerName = "";
                        $.each(data.SpeakerList, function (index, SpeakerDetails) {
                            SpeakerName += SpeakerDetails.FirstName + " " + SpeakerDetails.LastName + ", ";
                        });
                        SpeakerName = SpeakerName.substring(0, SpeakerName.length - 2);

                        var lockStatus = _this.checkLockForScheduledVideo(eventDetail.IsFree, data.HasLock);
                        if (data.VideoStatusType.toLowerCase() == "non live1") {
                            var time = new Date();

                            var eventVideoroute = 'data-hasIndex="true" data-innerroutename="eventvideoid" data-isoldrequest="false" data-DisplayVideoDetails=1 data-eventId="' + eventDetail.Id + '"  data-videoid="' + data.VideoId + '" data-videono="' + data.VideoNo + '"';
                            strdivtag = "<div class='col-xs-6 col-md-6 no-padding bottom-margin-15 '>";

                            strdivtag += "<div class='thumbnail-background thumbnail-desktop-list margin-right-10 related-video-image' " + eventVideoroute + "  style=background-image:url(\'" + data.DisplayImage + "?" + time.getTime() + "\')>";
                            strdivtag += "<img class='playBtn-small related_video-play-image' src='Images/" + lockStatus + "'>";
                            strdivtag += "</div>";
                            strdivtag += '<div class="col-md-6 col-sm-6 col-xs-12 no-padding ">';
                            strdivtag += '<div class="padding-right-10">';
                            strdivtag += '<a  class="text-color font-bold custom_pointer" ' + eventVideoroute + ' >' + data.VideoTitle + '</a>';
                            strdivtag += '</div>';
                            strdivtag += '<div class="font-size-11">' + truncateString(eventDetail.Title, 28) + ' </div>';
                            strdivtag += '<div class="font-size-11">' + SpeakerName + '</div>';
                            strdivtag += '</div>';
                            strdivtag += "</div>";
                        }
                        else {
                            strdivtag = " <div class='event-schedule-item-container clearfix'>";
                            strdivtag += "<div class='item-time'>" + data.VideoEventStartTime + " </div>";
                            if (data.VideoStatusType.toLowerCase() == "set as reminder") {
                                var setasreminderHTML = "";
                                var tooltip = '';
                                var anchorcssClass = 'SET_reminder';
                                if (loginStatus == ResultStatus.Successful) {
                                    if (data.HasLock == false) {
                                        setasreminderHTML = " data-innerroutename='sendremindermail' data-eventId=" + eventDetail.Id + " data-eventtitle=\"" + truncateString(eventDetail.Title, 28) + "\"    data-videoid=" + data.VideoId + " data-videono=" + data.VideoNo + "  data-videotitle=\"" + data.VideoTitle + "\"" + " data-videostarttime=\"" + data.VideoEventStartTime + "\"" + " data-videoendtime=\"" + data.VideoEventEndTime + "\"" + " data-videoeventdate=\"" + currentdateformat + "\"  "
                                        tooltip = 'Please click to set reminder notification for video.'
                                        anchorcssClass = 'SET_reminderAfterLogin';
                                    }
                                    else {
                                        tooltip = 'Reminder cannot be set as Video is locked'
                                    }
                                }
                                else {
                                    tooltip = 'Please login to set reminder';
                                }

                                strdivtag += "<div class='item-description padding-left-5'><a class=custom_pointer data-innerroutename='eventvideoid' data-isoldrequest='false' data-hasIndex='true' data-DisplayVideoDetails=1   data-eventId=" + eventDetail.Id + "  data-videostatus=" + data.VideoStatus + "  data-videoid=" + data.VideoId + "  data-videono=" + data.VideoNo + ">" + data.VideoTitle + "</a></div>";
                                strdivtag += "<div class='item-speaker padding-left-5'>" + SpeakerName + "</div>";
                                strdivtag += "<span class='glyphicon glyphicon-time'></span><a class='" + anchorcssClass + "' onclick='canSetasReminder(" + loginStatus + "," + data.HasLock + ")'title='" + tooltip + "'" + setasreminderHTML + " >" + " " + data.VideoStatusType + "</a>";
                            }
                            else {
                                if (data.VideoStatusType == "Coming Soon") {
                                    //strdivtag += "<div class='videoStatus pull-left ' style='clear:left'><span class='videoStatusSpan'>" + data.VideoStatusType + "</span> </div>";
                                    strdivtag += "<div class='videoStatus pull-left custom_pointer' style='clear:left'><span class='videoStatusSpan' data-hasIndex='true' data-innerroutename='eventvideoid' data-isoldrequest='false' href='#'  data-eventId=" + eventDetail.Id + "  data-videostatus=" + data.VideoStatus + "  data-videoid=" + data.VideoId + "  data-videono=" + data.VideoNo + "  data-SubscriptionType=" + data.SubscriptionType + "  data-Duration= " + data.Duration + " >" + data.VideoStatusType + "</span> </div>";
                                    strdivtag += "<div class='item-description padding-left-5'><a class='custom_pointer' data-hasIndex='true' data-innerroutename='eventvideoid' data-isoldrequest='false' data-DisplayVideoDetails=1  data-eventId=" + eventDetail.Id + "  data-videostatus=" + data.VideoStatus + "  data-videoid=" + data.VideoId + "  data-videono=" + data.VideoNo + "  data-SubscriptionType=" + data.SubscriptionType + " data-Duration= " + data.Duration + ">" + data.VideoTitle + "</a></div>";
                                }
                                else {
                                    if (isLiveVideoOn == true && videoNo != data.VideoNo) {
                                        strdivtag += "<div class='videoStatus pull-left custom_pointer' style='clear:left'><span class='videoStatusSpan' data-hasIndex='true' data-innerroutename='eventvideoid' data-isoldrequest='false' href='#'  data-eventId=" + eventDetail.Id + "  data-videostatus=" + data.VideoStatus + "  data-videoid=" + data.VideoId + "  data-videono=" + data.VideoNo + "  data-SubscriptionType=" + data.SubscriptionType + " data-Duration= " + data.Duration + " >" + data.VideoStatusType + "</span> </div>";
                                        strdivtag += "<div  class='item-description padding-left-5'><a class='custom_pointer' target='_blank'  href= '" + "http://localhost/IETTVPortal/?videoid=" + data.VideoNo + "'  data-SubscriptionType=" + data.SubscriptionType + "  data-Duration= " + data.Duration + ">" + data.VideoTitle + "</a></div>";
                                    }
                                    else {
                                        strdivtag += "<div class='videoStatus pull-left custom_pointer' style='clear:left'><span class='videoStatusSpan' data-hasIndex='true' data-innerroutename='eventvideoid' data-isoldrequest='false' href='#'  data-eventId=" + eventDetail.Id + "  data-videostatus=" + data.VideoStatus + "  data-videoid=" + data.VideoId + "  data-videono=" + data.VideoNo + "  data-SubscriptionType=" + data.SubscriptionType + "  data-Duration= " + data.Duration + " >" + data.VideoStatusType + "</span> </div>";
                                        strdivtag += "<div class='item-description padding-left-5'><a class='custom_pointer' data-hasIndex='true' data-innerroutename='eventvideoid' data-isoldrequest='false' data-DisplayVideoDetails=1  data-eventId=" + eventDetail.Id + "  data-videostatus=" + data.VideoStatus + "  data-videoid=" + data.VideoId + "  data-videono=" + data.VideoNo + "  data-SubscriptionType=" + data.SubscriptionType + "  data-Duration= " + data.Duration + ">" + data.VideoTitle + "</a></div>";
                                    }
                                }

                                strdivtag += "<div class='item-speaker padding-left-5'>" + SpeakerName + "</div>";
                            }

                            strdivtag += "</div>";
                        }

                        $(".divVideoSchedule").append(strdivtag);
                    });
                    //VideoRenderScript();
                    routeProvider.bindInnerRoutes();
                    if (!WebService.DisableGA) {
                        storeurlDetailsInGA('Event Title - ' + eventDetail.Title);
                    }
                }
            },
            function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },
    getRelatedVideos: function (currentRouteSetting, routeProvider, routeCurrentContext) {
        Repository.LoadDataWithGet(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetVideoVideoModel',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    //Bind all subscriptions to view.
                    if (data.ResultObject == null) {
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            /*Carousel Logic start */
                            var relatedVideosHTML = '';

                            var count = 0;

                            $.each(data.ResultObject.Popularlist, function (index, data) {
                                relatedVideosHTML += getRelatedVideoHTML(data.ImageUrl, data.VideoUrl, data.ChannelName, data.VideoTitle);
                            });

                            $(document).ready($('#related-videos').html(relatedVideosHTML));
                            //RenderPlayer();
                        }
                        else {
                            $('#VideoTable').html("No records found.");
                        }
                        $('#NoRecordFound').hide();
                    }
                }
            }
            ,
            function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            });
    },
    //step2

    CheckLock: function (hasLock) {
        var _this = this;

        if (hasLock == true) {
            //   _this.HideDownload(true);
            //_this.HideVideo(true);
            $("#eventvideoplayBtn").css("display", "none");
            $("#lockBtn").css("display", "block");
        }
        else {
            $("#eventvideoplayBtn").css("display", "block");
            $("#lockBtn").css("display", "none");
            //_this.HideVideo(false);
        }
    },

    checkLockForScheduledVideo: function (eventIsFree, scheduledVideoHasLock) {
        var accessbtn = "";
        if (eventIsFree == true) {
            accessbtn = 'play.png';
        }
        else if (scheduledVideoHasLock) {
            accessbtn = 'lock.png';
        }
        else {
            accessbtn = 'play.png';
        }

        return accessbtn;
    },

    AllowDownload: function (allowDownload) {
        var _this = this;

        if (allowDownload == false) {
            $('.download-video-button').attr('disabled', true);
            $('.download-btn-div').attr('disabled', true);
            $('.download-video-button').css('pointer-events', 'none');
        }
        else {
            $('.download-video-button').attr('disabled', false);
            $('.download-video-button').css('pointer-events', '');
            $('.download-btn-div').attr('disabled', false);
        }
    },
    CanLikeDislike1: function (canLikeDislike) {
        if (canLikeDislike == true) {
            $(".like-unlike-pannel").attr('disabled', false);
            $(".view-block").attr('disabled', false);
            $(".like").attr('disabled', false);
            $(".unlike").attr('disabled', false);
            $(".glyphicon-thumbs-down").css('pointer-events', '');
            $(".glyphicon-thumbs-up").css('pointer-events', '');
            $(".likevalue").html(CurrentVideoDetail.LikesCount);
            $(".dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            //$("#likevaluemobile").html(CurrentVideoDetail.LikesCount);
            //$("#dislikevaluemobile").html(CurrentVideoDetail.DisLikesCount);
            if (CurrentVideoDetail.ViewsCount <= 1) {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Play");
            }
            else {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Plays");
            }
        }
        else {
            $(".like-unlike-pannel").attr('disabled', true);
            $(".view-block").attr('disabled', true);
            $(".like").attr('disabled', true);
            $(".unlike").attr('disabled', true);
            $('.button_style_none').attr('disabled', true);
            $(".glyphicon-thumbs-down").css('pointer-events', 'none');
            $(".glyphicon-thumbs-up").css('pointer-events', 'none');
            $(".likevalue").html(CurrentVideoDetail.LikesCount);
            $(".dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            //$("#likevaluemobile").html(CurrentVideoDetail.LikesCount);
            //$("#dislikevaluemobile").html(CurrentVideoDetail.DisLikesCount);
            if (CurrentVideoDetail.ViewsCount <= 1) {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Play");
            }
            else {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Plays");
            }
        }
    },
    ShowRelatedContent: function (RelatedContentData) {
        $("#dynamicRelatedContentMain").html("");
        if (RelatedContentData != null && RelatedContentData.RelatedContentRecord != null) {
            if (RelatedContentData.RelatedContentRecord.length == 0) {
                $("#related-content").hide();
            }
            var i = 0;
            $.each(RelatedContentData.RelatedContentRecord, function (index, data) {
                i += 1;
                var ImageType = data.Type == "Book" ? 'Images/book.png' : 'Images/journal.png';
                var strDiv = '<div class="col-lg-6 col-md-6 col-xs-12 col-sm-12 related-content-record-container">';
                strDiv += '<a href="' + data.DOI + '" target="_blank"><div class="related-content-icon" style="background-image:url(' + ImageType + ')"></div><a>';
                strDiv += '<div class="related-content-text">';
                strDiv += '<a href="' + data.DOI + '" target="_blank" class="text-color font-bold custom_pointer">' + data.Title + '</a>';
                strDiv += ' <div>' + data.Type + '</div>';
                strDiv += ' </div>';
                strDiv += ' </div>';

                if (i <= 4) {
                    $("#dynamicRelatedContentMain").append(strDiv);
                }
            });
        }
    },
    RenderAttachment: function (allowed) {
        var _this = this;
        var attachmenthtml = '';
        if (CurrentVideoDetail.Attachment != null) {
            $.each(CurrentVideoDetail.Attachment, function (index, data) {
                if (data.IsActive) {
                    var classMoreAttachments = "";
                    var str = '';
                    if (index > 2) {
                        classMoreAttachments = "more-attachments display-none"
                    }
                    if (allowed == false) {
                        str = '<span  class="text-color font-bold" id="DownloadAttachment" > ' + data.AttachmentFileName + '</span>';
                    }
                    else {
                        //str = '<span><a class="text-color font-bold" id="DownloadAttachment" data-innerroutename="DownloadAttachment" target="_blank"   href="#"  fileurl="' + data.AttachmentFileNameWithPath + '">' + data.AttachmentFileName + '</a></span>'
                        str = '<span><a class="text-color font-bold" id="DownloadAttachment" data-innerroutename="DownloadAttachment" target="_blank" style="cursor: pointer;"   fileurl="' + data.AttachmentFileNameWithPath + '">' + data.AttachmentFileName + '</a></span>'
                    }
                    attachmenthtml += '<div class="download_docs ' + classMoreAttachments + '"><img src="' + GetAttachmentImage(data.AttachmentType) + '" />' + str + '</div>';
                }
            });
        }
        $(".download_section").html(attachmenthtml);
        if (attachmenthtml != "") {
            //$('#video-content').removeClass('col-md-12 col-sm-12').addClass('col-md-7 col-sm-7');
            $('#video-attachment').removeClass('display-none');
        }
    },

    RenderTranscript: function (allowed) {
        var _this = this;
        var transcripthtml = '';

        if (CurrentVideoDetail.TranscriptList != null) {
            $.each(CurrentVideoDetail.TranscriptList, function (index, data) {
                var classMoreTranscripts = "";
                //var str = '';
                //var filename = '';
                //var ext = '';
                if (index > 2) {
                    classMoreTranscripts = "more-transcripts display-none"
                }
                //if (data.Text != '') {
                //    ext = data.FileName.split('.')[1];
                //    filename = data.Text + '.' + ext;
                //}
                //else {
                //    filename = data.FileName;
                //}
                if (allowed == false) {
                    str = '<span  class="text-color font-bold" id="DownloadTranscript" > ' + data.FileName + '</span>';
                }
                else {
                    str = '<span><a class="text-color font-bold" id="DownloadTranscript" data-innerroutename="DownloadAttachment" target="_blank" style="cursor: pointer;"   fileurl="' + data.FilePath + '">' + data.FileName + '</a></span>';
                }
                transcripthtml += '<div class="download_docs ' + classMoreTranscripts + '"><img src="' + GetAttachmentImage(data.AttachmentType) + '" />' + str + '</div>';
            });
        }
        $(".transcript_section").html(transcripthtml);
        if (transcripthtml != "") {
            //$('#video-content').removeClass('col-md-12 col-sm-12').addClass('col-md-7 col-sm-7');
            $('#transcript-attachment').removeClass('display-none');
        }
    },

    RenderIETDigitalLibrary: function (digitalLibraryUrl) {
        var digitalLibraryHtml = '';
        var urltitle = '';
        if (digitalLibraryUrl != "") {
            urltitle = '<span class="text-color font-bold">' + digitalLibraryUrl + '</span>'
            digitalLibraryHtml += '<div class="download_docs"><img class="digital-library" src="Images/journal.png" /><a target="_blank" class="custom_pointer" href="' + digitalLibraryUrl + '">' + urltitle + '</a>';
        }
        $('.digital-library-container').html(digitalLibraryHtml);
        if (digitalLibraryHtml != "") {
            //$('#video-content').removeClass('col-md-12 col-sm-12').addClass('col-md-7 col-sm-7');
            $('#IET-digital-library').removeClass('display-none');
        }
    },
    DisposePlayer: function () {
        if (myPlayer) {
            myPlayer.dispose();
        }
    },
    EventPlayVideo: function () {
        var _this = this;
        toggleEventVideoVisibility();
    },
    EventRenderVideoPanel: function (renderPlayer) {
        var _this = this;
        if (renderPlayer) {
            $(".video-thumbnail-toggle-background").toggleClass("display-none");
            $("#player").removeClass('hidden');
            /// Author: Sanjana
            /// Date:02-07-2017
            /// Decription:highlight divs
            $('.myclips').removeClass('disabledbutton');
            $('.share-img-icon').removeClass('disabledbutton');
            $("#transcript-img").removeClass('selectedIcon');
            $(".myclips").removeClass('selectedIcon');
            $(".share-img-icon").removeClass('selectedIcon');
            //End
        }
        else {
            $(".video-thumbnail-toggle-background").toggleClass("display-none");
            $("#player").removeClass('hidden');
        }
    },
    CanVideoPlay: function () {
        var _this = this;
        var canPlay = false;
        if (CurrentVideoDetail.HasLock == true || (CurrentVideoDetail.HasPromo == true && CurrentVideoDetail.PromoType != "video") || (CurrentVideoDetail.HasPromo == true && CurrentVideoDetail.PromoType != "video" && (CurrentVideoDetail.VideoStatus == 4 || CurrentVideoDetail.VideoStatus == 5))) {
            canPlay = false;
        }
        else {
            canPlay = true;
        }
        return canPlay;
    },
    CanEventPlay: function () {
        var _this = this;
        var canPlay = false;

        if (!EventModel.CanPlay) {
            canPlay = false;
        }
        else {
            canPlay = true;
        }

        return canPlay;
    },
    //Stream Code Commented Start 2018/04/11
    //EventRenderPlayer: function () {
    //    // var partnerid=video.PartnerId;
    //    var _this = this;
    //    var entryId = '';
    //    var _this = this;
    //    if (EventModel.HasPromo && LoadEventOnPromo == 1) {
    //        if (_this.CanEventPlay() == false) {
    //            return;
    //        }
    //        else {
    //            entryId = EventModel.StreamUKId;
    //        }
    //    }
    //    else {
    //        if (_this.CanVideoPlay() == false) {
    //            return;
    //        }
    //        else {
    //            entryId = CurrentVideoDetail.EntryId;
    //        }
    //    }

    //    $.getScript(WebService.StreamUrl, function () {
    //        _this.EventRenderVideoPanel(true);

    //        mw.setConfig('Kaltura.EnableEmbedUiConfJs', true);
    //        mw.setConfig('EmbedPlayer.EnableIpadHTMLControls', true);
    //        mw.setConfig('Kaltura.ForceFlashOnDesktop', false);

    //        var player = PlayerDetail;

    //        var kWidgetEmbedSettings = {
    //            'targetId': 'player',
    //            'wid': player.PartnerId,
    //            'uiconf_id': player.PlayerId,
    //            'flashvars': {
    //                "streamerType": "auto",
    //                'ks': player.Ks,
    //                'autoPlay': true
    //            },
    //            'params': { // params allows you to set flash embed params such as wmode, allowFullScreen etc
    //                'wmode': 'transparent'
    //            },
    //            'cache_st': player.CacheStrng,
    //            'entry_id': entryId,//'0_8g8u8vq3'//playerDetails.ukstreamId
    //            /// Author: Sanjana
    //            /// Date: 22-08-2017
    //            /// Decription: do seek when user clicks on clip video
    //            'readyCallback': function (playerId) {
    //                var kdp = document.getElementById(playerId);
    //                //Checks Transcript file available or not
    //                debugger;
    //                if (CurrentVideoDetail.IsSubTitleContentAvailable & !CurrentVideoDetail.IsLive & !CurrentVideoDetail.HasLock) {
    //                    IETTVTranscript.Transcript_Highlight_Listener(playerId);
    //                    $("#transcript-img").show();
    //                }
    //                var isClip = false;
    //                var starttime = sessionStorage.getItem("Clip_StartTime");
    //                var endtime = sessionStorage.getItem("Clip_EndTime");
    //                var endSeconds;
    //                var currentSeconds;
    //                if (starttime != null && endtime != null) {
    //                    isClip = true;
    //                    currentSeconds = converttimetoseconds(starttime);
    //                    endSeconds = converttimetoseconds(endtime);
    //                } else {
    //                    starttime = $.url().param('st');
    //                    endtime = $.url().param('et');
    //                    if (starttime != undefined && endtime != undefined) {
    //                        isClip = true;
    //                        currentSeconds = converttimetoseconds(starttime);
    //                        endSeconds = converttimetoseconds(endtime);
    //                    }
    //                }
    //                // Once playing issue seek
    //                var seekDone = false;
    //                kdp.kBind('playerUpdatePlayhead', function (event) {
    //                    if (isClip) {
    //                        if (!seekDone) {
    //                            kdp.sendNotification('doSeek', currentSeconds - 1);
    //                        }
    //                        if (parseInt(event) == endSeconds) {
    //                            kdp.sendNotification('doPause');
    //                        }
    //                        seekDone = true;
    //                    }
    //                });
    //                // Wait for "media ready" before starting playback:
    //                var iOS = /Android|iPad|iPhone|iPod/.test(navigator.userAgent);

    //                if (iOS != true) {
    //                    kdp.kBind('mediaReady', function () {
    //                        kdp.sendNotification('doPlay');
    //                    })
    //                }
    //                ////Add a binding for when seek is completed:
    //                //kdp.kBind('playerSeekEnd', function () {
    //                //    // Pause player after 2 second
    //                //    if (isClip) {
    //                //        setTimeout(function () {
    //                //            kdp.sendNotification('doPause');
    //                //        }, 1000)
    //                //    }
    //                //});
    //            }
    //            //End
    //        }

    //        kWidget.embed(kWidgetEmbedSettings);
    //        // $("#player").css('display', 'inline-block !important');
    //    });

    //},
    //AttachScript: function () {
    //    $.getScript(WebService.StreamUrl, function () {
    //        //console.log('file loaded');

    //        mw.setConfig('Kaltura.EnableEmbedUiConfJs', true);
    //        mw.setConfig('EmbedPlayer.EnableIpadHTMLControls', true);
    //        mw.setConfig('Kaltura.ForceFlashOnDesktop', false);

    //        var video = CurrentVideoDetail;
    //        var player = PlayerDetail;
    //        //console.log(video);
    //        //console.log(player);

    //        var kWidgetEmbedSettings = {
    //            'targetId': 'player',
    //            'wid': player.PartnerId,
    //            'uiconf_id': player.PlayerId,
    //            'flashvars': {
    //                "streamerType": "auto",
    //                'ks': player.Ks,
    //                'autoPlay': true
    //            },
    //            'cache_st': player.CacheStrng,
    //            'entry_id': video.EntryId//'0_8g8u8vq3'//playerDetails.ukstreamId

    //        }
    //        kWidget.embed(kWidgetEmbedSettings);
    //    });

    //},
    //Stream Code Commented End 2018/04/11

    //Azure Code added by Start 2018/04/19
    EventRenderPlayer: function () {
        //alert(video.PartnerId);
        // var partnerid=video.PartnerId;
        var _this = this;

        if (EventModel.HasPromo && LoadEventOnPromo == 1) {
            if (_this.CanEventPlay() == false) {
                return;
            }
        }
        else {
            if (_this.CanVideoPlay() == false) {
                return;
            }
        }

        $("#player").show();

        _this.EventRenderVideoPanel(true);

        var video = CurrentVideoDetail;
        //var player = PlayerDetail;
        var isClip = false;
        var starttime;
        var endtime;
        var endSeconds;
        var myOptions = {
            //Need to be relooked
            techOrder: ["azureHtml5JS", "flashSS", "html5FairPlayHLS", "silverlightSS", "html5"],
            "nativeControlsForTouch": false,
            controls: true,
            autoplay: true,
            width: "100%",
            height: "100%",
            "logo": { "enabled": false },
            plugins: {
                ga: {
                    //'eventLabel' : 'EventLabelForTracking', //default is URL source
                    'debug': false, //default is false
                    'eventsToTrack': ['playerConfig', 'loaded', 'playTime', 'percentsPlayed', 'start', 'error', 'buffering', 'bitrate'], // default is ['playerConfig', 'loaded', 'playTime', 'percentsPlayed', 'start', 'end', 'play', 'pause', 'error', 'buffering', 'fullscreen', 'seek', 'bitrate']
                    'percentsPlayedInterval': 20 //default is 20
                }
            }
        }
        myPlayer = null;
        myPlayer = amp("azuremediaplayer", myOptions, function () {
            //'this' refers to the player instance in the ready function
            if (CurrentVideoDetail.IsSubTitleContentAvailable & !CurrentVideoDetail.IsLive & !CurrentVideoDetail.HasLock) {
                IETTVTranscript.Transcript_Highlight_Listener("azuremediaplayer");
                //$("#transcript-img").show();
                $('.transcript-icon').removeClass('hidden');
            }
            starttime = sessionStorage.getItem("Clip_StartTime");
            endtime = sessionStorage.getItem("Clip_EndTime");
            var currentSeconds;
            if (starttime != null && endtime != null) {
                isClip = true;
                currentSeconds = converttimetoseconds(starttime);
                endSeconds = converttimetoseconds(endtime);
            }
            else {
                starttime = $.url().param('st');
                endtime = $.url().param('et');
                if (starttime != undefined && endtime != undefined) {
                    isClip = true;
                    currentSeconds = converttimetoseconds(starttime);
                    endSeconds = converttimetoseconds(endtime);
                }
            }
            //if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
            if (/Android/i.test(navigator.userAgent)) {
                myPlayer.play();
            }
        });

        //myPlayer.addEventListener(amp.eventName.play, playerVideoPlayedHandler);
        myPlayer.addEventListener(amp.eventName.ended, playerEventStoppedHandler);

        //allows to display english subtitles when replaying video
        myPlayer.addEventListener(amp.eventName.loadeddata, function () {
            _this.setTrack("en", "subtitles");
        });

        var seekDone = false;
        myPlayer.addEventListener(amp.eventName.playing, function () {
            if (isClip == true) {
                if (!seekDone) {
                    myPlayer.currentTime(clipStartTime);
                    seekDone = true;
                }
            }
        });

        myPlayer.addEventListener(amp.eventName.timeupdate, function () {
            if (Math.floor(myPlayer.currentTime()) == endSeconds) {
                var duration = myPlayer.duration().toString().split('.')[1];
                var currentTime = endSeconds + "." + duration;
                if (myPlayer.duration().toString() != currentTime) {
                    myPlayer.pause();
                    myPlayer.currentTime(endSeconds + 1);
                }
            }
        });
        var subtitleObject = [];
        $.each(CurrentVideoDetail.lstSrtSubTitles, function (index, value) {
            var time = new Date();
            if (value != '' && value != null) {
                subtitleObject.push({
                    "src": $.url().data.attr.source.split('?')[0] + value.SubtitlePath + "?" + time.getTime(),
                    "srclang": value.LanguageAbbreviation,
                    "label": value.Language,
                    "kind": "subtitles",
                    "default": value.Language == "English" ? true : false
                })
            }
        });
        myPlayer.src([
            {
                "src": CurrentVideoDetail.SmoothStreamingURL,
                "type": "application/vnd.ms-sstr+xml"
            }
        ],
            subtitleObject)
    },
    setTrack: function (language, kind) {
        for (var i = 0; i < myPlayer.textTracks_.length; i++) {
            if (myPlayer.textTracks_.tracks_[i].language == language && myPlayer.textTracks_.tracks_[i].kind == kind) {
                myPlayer.textTracks_.tracks_[i].mode = "showing";
            }
            if (myPlayer.textTracks_.tracks_[i].kind == "captions") {
                myPlayer.textTracks_.tracks_[i].mode = "disabled";
            }
        }
    },
    //Azure Code added by End 2018/04/19
    VideoLikeActivity: function (jsonData) {
        var _this = this;

        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoLikeActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        
                    }
                    else {
                        var like = data.ResultObject.Likes;
                        var dislike = data.ResultObject.DisLikes;
                        var view = data.ResultObject.Views;

                        var lastactivity = data.ResultObject.LastActivity;
                        $(".dislikevalue").text(dislike);
                        $(".likevalue").text(like);
                        //$("#likevaluemobile").html(CurrentVideoDetail.LikesCount);
                        //$("#dislikevaluemobile").html(CurrentVideoDetail.DisLikesCount);
                        //$("#ViewsCount").text(view + " View");
                        if (view <= 1) {
                            $("#ViewsCount").html(view + " Play");
                        }
                        else {
                            $("#ViewsCount").html(view + " Plays");
                        }
                        _this.ToggleLikeDislike("Like");

                        
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    VideoDislikeActivity: function (jsonData) {
        var _this = this;

        var object = {
            Data: { "videoActivity": jsonData }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoDislikeActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        
                    }
                    else {
                        var like = data.ResultObject.Likes;
                        var dislike = data.ResultObject.DisLikes;
                        var view = data.ResultObject.Views;
                        var lastactivity = data.ResultObject.LastActivity;
                        $(".dislikevalue").text(dislike);
                        $(".likevalue").text(like);
                        if (view <= 1) {
                            $("#ViewsCount").html(view + " Play");
                        }
                        else {
                            $("#ViewsCount").html(view + " Plays");
                        }
                        _this.ToggleLikeDislike("Dislike");

                        
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },
    VideoViewActivity: function (jsonData) {
        var _this = this;
        //if (_this.CanLikeDislike1() == false) {
        //    return;
        //}
        //if (played >= 1) {
        //    return;
        //}
        //played++;
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoViewActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        
                    }
                    else {
                        var like = data.ResultObject.Likes;
                        var dislike = data.ResultObject.DisLikes;
                        var view = data.ResultObject.Views;

                        $(".dislikevalue").text(dislike);
                        $(".likevalue").text(like);

                        if (view <= 1) {
                            $("#ViewsCount").html(view + " Play");
                        }
                        else {
                            $("#ViewsCount").html(view + " Plays");
                        }

                        
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    SendReminderMail: function (emailDetails) {
        var messageViewModel = new MessageViewModel();

        var object = {
            Data: { "emailDetails": emailDetails }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'EventManagement/EventService.svc/SendMail',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null || data.ResultObject == false) {
                        messageViewModel.CreateWarningMessage(data.Message);
                        messageViewModel.ShowOverLay();
                    }
                    else {
                        messageViewModel.CreateInfoMessage(data.Message);
                        messageViewModel.ShowOverLay();
                    }
                }
                else {
                    messageViewModel.CreateWarningMessage(data.Message);
                    messageViewModel.ShowOverLay();
                }
            },
            function (data, status, headers, config) {
                messageViewModel.CreateErrorMessage(data.Message);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    ToggleLikeDislike: function (lastactivity) {
        var _this = this;
        if (lastactivity != "" || lastactivity != null) {
            if (lastactivity == "Like") {
                // $(".like").attr('disabled', true);
                //  $(".unlike").attr('disabled', false);
                $(".unlike").css('pointer-events', '');
                $(".like").css('pointer-events', 'none');
                $(".glyphicon-thumbs-down").css('pointer-events', '');
                $(".glyphicon-thumbs-up").css('pointer-events', 'none');
            }
            else if (lastactivity == "Dislike") {
                $(".glyphicon-thumbs-down").css('pointer-events', 'none');
                $(".glyphicon-thumbs-up").css('pointer-events', '');
                // $(".like").attr('disabled', false);
                ///$(".unlike").attr('disabled', true);
                $(".unlike").css('pointer-events', 'none');
                $(".like").css('pointer-events', '');
            }
        }
    },

    DownloadVideo: function (currentRouteSetting, routeProvider, routeCurrentContext) {
        var _this = this;
        var video = CurrentVideoDetail;

        //var Download = {
        //    Action: "Download",
        //    LogonId: BrowserStorage.getLogonId(),
        //    VideoID: video.VideoId,
        //    Type: "Video",
        //    VideoTitle: video.Title,
        //    Name: video.Title,
        //    ChannelID: video.ChannelId,
        //    EntryID: PlayerDetail.EntryId,
        //    SubscriptionType: video.PriceType,
        //    Duration: video.Duration
        //};

        var object = {
            Data: { "encodedAssetID": CurrentVideoDetail.EncodedAssetId }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetDownloadURL',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            var videodetail = data.ResultObject;
                            //window.location.href = videodetail;
                            //window.open(videodetail, '_blank');
                            $("#anchordwldlink").attr("href", videodetail);
                            $("#anchordwldlink")[0].click();
                        }
                    }
                }
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    }
};

function playerEventStoppedHandler() {
    myPlayer.exitFullscreen();
    disableSpinner = true;
    $("#player").addClass('hidden');
    $(".video-thumbnail-toggle-background").removeClass("display-none");

    $('.share-img-icon').addClass('disabledbutton');
    $('.myclips').addClass('disabledbutton');
    $('.share-img-icon').removeClass('selectedIcon');
    $('.myclips').removeClass('selectedIcon');
    played = 0;
    //console.log('stop');
    var video = CurrentVideoDetail;
    var data =
    {
        Action: "Stop",
        VideoID: video.VideoId,
        VideoTitle: video.Title,
        ActionTime: GetCurrentDate(),
        LogonId: BrowserStorage.getLogonId(),
        IpAddress: "",
        UserName: "",
        Duration: video.Duration
    };
};

function converttimetoseconds(time) {
    var p = time.split(':'), s = 0, m = 1;
    while (p.length > 0) {
        s += m * parseInt(p.pop(), 10);
        m *= 60;
    }
    var totalSeconds = Math.floor(s);
    return totalSeconds;
}
function getRelatedVideoEventHTML(videoid, videoNo, channelName, videoTitle, videoimage, hasLock, channelId, SubscriptionType, Duration, isSeries, seriesCount, seriesCreatedYear) {
    var accessbtn = '';

    if (channelId == null) {
        channelId = '';
    }
    if (channelName == null) {
        channelName = '';
    }
    var videoroute = '';
    var channelroute = '';
    //var channelHTMLCode = '';

    if (hasLock == false) {
        accessbtn = 'play.png';
    }
    else {
        accessbtn = 'lock.png';
    }
    var seriesOverlayData = "";
    if (videoid != "" && isSeries == false) {
        videoroute = 'data-innerroutename=\"videoid\"  data-videono=\"' + videoNo + '\"  data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\'';
        channelroute = 'data-innerroutename="Channel" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\'';
        //  channelHTMLCode = '<div class=thumbnail-channel ' + channelroute + ' ><span>' + channelName + '</span></div>'
    }
    else if (isSeries == true) {
        videoroute = 'data-innerroutename=\"series\"  data-videono=\"' + videoNo + '\"  data-ChannelId=\"' + channelId + '\"  data-hasindex="true" data-videoId=\'0\'  data-seriesid=\'' + videoid + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        seriesOverlayData = '<div class="series_overlay_content"> <div class="series_overlay_count">' + seriesCount + '</div> <div class="series_overlay_video_text">Videos</div> </div>';
        channelName = seriesCreatedYear;
        channelroute = 'style="cursor: default;"';
    }

    //var addtionaVideoHTML = '<div class="twoColumnClearLeft col-md-6 col-xs-6 related-video-padding-alignment bottom-margin-15">' +
    var addtionaVideoHTML = '<div class="col-md-2 col-xs-6 related-videos_new">' +
        '<div class="bottom-margin-10 related-video-image-background">' +
        '<a href="?videoid=' + videoNo + '"  class="thumbnail-background thumbnail-desktop-list border1px disablehreflink" ' + videoroute + ' style="background-image:url(\'' + videoimage + '\')">' +
        '<img class="playBtn-small playBtn-small-btn-content" src="Images/' + accessbtn + '">' +
        '</a>' +
        seriesOverlayData +
        '</div>' +
        '<div class="col-md-11 no-padding">' +
        '<span>' +
        '<a href="?videoid=' + videoNo + '" class="list-caption disablehreflink" ' + videoroute + '>' +
        (videoTitle) +
        '</a>' +
        '</span>' +
        '</div>' +
        '<div class="col-md-11 no-padding">' +
        '<a href="?Channel=' + channelName + '"  class="list-channel disablehreflink" ' + channelroute + '>' +
        channelName +
        '</a>' +
        '</div>' +
        '</div>';

    return addtionaVideoHTML;
}
function toggleEventVideoVisibility() {
    //$(".video-thumbnail-toggle-background").toggleClass("display-none");
    //$("#player").removeClass('hidden');
    EventRepository.EventRenderPlayer();
}

function toogleReadMoreLess() {
    var moretext = "Show more";
    var lesstext = "Show less";
    if ($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
    } else {
        $(this).addClass("less");
        $(this).html(lesstext);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
}

//function to display premium event text
function getDivHeight(premium_text_height) {
    return premium_text_height / 2;
}

function RenderEventScript() {
    /*To toggle view of video description area*/ /*located in commonScripts.js*/
    VideoViewMoreScript();
    windowResizeactions();
    $(window).resize(function () {
        /*located in commonScripts.js*/
        windowResizeactions();
    });
}

function canSetasReminder(loginStatus, hasLock) {
    var messageViewModel = new MessageViewModel();
    if (loginStatus == 0 && hasLock == true) {
        messageViewModel.CreateInfoMessage("Reminder cannot be set as Video is locked", "overlayId", "okButtonId");
        messageViewModel.ShowOverLay();
    }
    if (loginStatus == -1) {
        messageViewModel.CreateInfoMessage("Please login to set reminder", "overlayId", "okButtonId");
        messageViewModel.ShowOverLay();
    }
    return false;
}

function VideoSpeakerRenderScript() {
    var run = true;
    /*Calling checkIsMobile in window resize*/

    /*This function is used to check window size if window  size is less than 992 we are considering it as mobile*/
    function checkIsMobile() {
        if ($(window).width() < 992) {
            returnValue = 1;
        } else {
            returnValue = 0;
        }
        return returnValue;
    }

    var $carouselSpeaker = $("#speaker-carousel .carousel");

    /*by default stop carousel cycle*/
    $carouselSpeaker.carousel('pause');
    // get right & left controls
    var $rightSpeakerControl = $carouselSpeaker.find(".right.carousel-control");
    var $leftSpeakerControl = $carouselSpeaker.find(".left.carousel-control");

    var totContentSpeaker = $('#speaker-carousel .carousel-inner').children('.item').size();
    /*Hiding left and right controll if carousel item is 3 or less*/
    if ($(window).width() < 992) {
        if (totContentSpeaker <= 1) {
            $leftSpeakerControl.css('display', 'none');
            $rightSpeakerControl.css('display', 'none');
        }
    }
    else {
        if (totContentSpeaker <= 2) {
            $leftSpeakerControl.css('display', 'none');
            $rightSpeakerControl.css('display', 'none');
        }
    }

    // hide the left control (first slide) on load
    $leftSpeakerControl.hide();

    /* hide and show left and right arrow when carousel slide */
    $carouselSpeaker.on('slid.bs.carousel', function () {
        // get active slide
        var $activeSpeaker = $carouselSpeaker.find(".item.active");

        // if the last slide,

        rightArrowHide();

        // if the first slide,
        if (!$activeSpeaker.prev().length) {
            // hide the left control
            $leftSpeakerControl.css('display', 'none');
            // if not,
        } else {
            // show it
            $leftSpeakerControl.css('display', 'block');
        }
    });

    /*this function is used to show /hide right arrow */
    function rightArrowHide() {
        var showSpeaker;
        if (checkIsMobile() == 1) {
            showSpeaker = $carouselSpeaker.find(".item.active").next().length;
        } else {
            showSpeaker = $carouselSpeaker.find(".item.active").next().next().length;
        }
        if (!showSpeaker) {
            // hide the right control
            $rightSpeakerControl.css('display', 'none');
            // if not,
        } else {
            // show the right control
            $rightSpeakerControl.css('display', 'block');
        }
    }
    var flag = 0;
    $('#speaker-carousel .carousel .item').removeClass('active');
    $('#speaker-carousel .carousel .item').each(function () {
        /*Making first item active*/
        if (flag == 0) {
            $(this).addClass('active');
            flag = 1;
        }
    });

    /*This is used to show three images in speaker carousal */
    run = false;
    var multiple = function () {
        /*removeing active class*/
        $('#speaker-carousel .carousel .item').removeClass('active');

        var flagItemActiveFirst = 0;
        $('#speaker-carousel .carousel .item').each(function () {
            /*Making first item active*/
            if (flagItemActiveFirst == 0) {
                $(this).addClass('active');
                flagItemActiveFirst = 1;
            }
            var next = $(this).next();

            if (!next.length) {
                next = $(this).siblings(':first');
            }
            next.children(':first-child').clone().appendTo($(this));

            //next = next.next();

            //if (!next.length) {
            //    next = $(this).siblings(':first');
            //}
            //next.children(':first-child').clone().appendTo($(this));
            run = true;
        });

        // hiding left controll in this function to work it in window resize
        $leftSpeakerControl.hide();

        /* calling show / hide right arrow */
        rightArrowHide();
    };

    /*This function is used to remove last two images from each slide to show only one image in mobile view*/
    var undo = function () {
        $('#speaker-carousel .carousel .item').each(function () {
            //  $(this).children().last().remove();
            run = false;
        });
    };

    //ensuring proper arrangement on load
    if ($(window).width() > 992) {
        multiple();
    }

    $(window).resize(function () {
        if (run == false && $(window).width() > 992) {
            $('#speaker-carousel .carousel .item').each(function () {
                $(this).children().slice(1).remove();
            });
            multiple();
        } else if (run == true && $(window).width() < 992) {
            $('#speaker-carousel .carousel .item').each(function () {
                $(this).children().slice(1).remove();
            });
            undo();
        }
        rightArrowHide();
    });
}

function VideoRenderScript() {
    VideoSpeakerRenderScript();
    /*To toggle view of video description area*/ /*located in commonScripts.js*/
    VideoViewMoreScript();
    windowResizeactions();
    $(window).resize(function () {
        /*located in commonScripts.js*/
        windowResizeactions();
    });
}
function CopyToClipboardEvent() {
    if ($('#embedcodeEvent').hasClass("DataTocopy")) {
        $("#embedcodeEvent").copymeEvent();
    } else if ($('#facebookcodeEvent').hasClass("DataTocopy")) {
        $("#facebookcodeEvent").copymeEvent()
    }

    var messageViewModel = new MessageViewModel();
    messageViewModel.CreateInfoMessage("Copied to clipboard successfully", "overlayId", "okButtonId");
    messageViewModel.ShowOverLay();
    $('#iframeEmbedEvent').prop('checked', true);
    $('#facebookTwitterEmbedEvent').prop('checked', false);
    $('#embedcodeEvent').addClass("DataTocopy");
}
function callDownloadVideo() {
    if (localStorage.getItem('AccountId') != 0) {
        if (!this.CurrentVideoDetail.HasLock) {
            //$('#helptext').text(CurrentVideoDetail.Title + " is about to download.<br/> ")

            //$('#helptext').text(CurrentVideoDetail.Title + " is about to download.<br/> ")
            $("#DownloadHelp").modal({
                backdrop: 'static',
                keyboard: false
            });
            $("#DownloadHelp").modal('show');
            $("#btnDownloadContinue").unbind();
            $("#btnDownloadContinue").bind("click", function (e) {
                $("#DownloadHelp").modal('hide');
                EventRepository.DownloadVideo();
            });
        }
        else {
            var messageViewModel = new MessageViewModel();
            messageViewModel.CreateInfoMessage("Please subscribe to download the video.", "overlayId", "okButtonId");
            messageViewModel.ShowOverLay();
        }
    }
    else {
        var messageViewModel = new MessageViewModel();
        messageViewModel.CreateInfoMessage("Please login to download the video.", "overlayId", "okButtonId");
        messageViewModel.ShowOverLay();
    }
}

function getSpeakerDetails(position, name) {
    var _this = this;
    if (CurrentVideoDetail.Speakers != null) {
        $.each(CurrentVideoDetail.Speakers, function (index, speaker) {
            if (index == position) {
                var SpeakerImage = '';
                if (speaker.PictureUrl.indexOf("$") != -1) {
                    SpeakerImage = speaker.PictureUrl.slice(0, speaker.PictureUrl.lastIndexOf("$"));
                }
                else {
                    SpeakerImage = CurrentVideoDetail.SpeakerImageSource + speaker.PictureUrl;
                }

                $('#speaker_image').attr("src", SpeakerImage);
                if (speaker.Title != '') {
                    $('#spkr_name').text(speaker.Title + " " + speaker.FirstName + " " + speaker.LastName);
                } else {
                    $('#spkr_name').text(speaker.FirstName + " " + speaker.LastName);
                }
                $('#spkr_jobtitle').text(speaker.JobTitle);
                $('#spkr_company_name').text(speaker.Organization);
                $('#spkr_affiliations').text(speaker.Affiliation);
                $('#spkr_biography').html(speaker.Biography)
                $("#viewBioPrompt").modal({
                    backdrop: 'static',
                    keyboard: false
                });
                $("#viewBioPrompt").modal('show');
                return false;
            }
        });
    }
}

function SpeakerHTML(position, title, fname, lname, image) {
    var speakersectionhtml = "<div class='item active'>" +
        "<div class='col-md-6 no-padding col-sm-12 col-xs-12 user-block'>" +
        "<div class='thumbnail float-left margin-right-5'>" +
        "<img src='" + image + "' width='50' height='50' class='img-border'/>" +
        "</div>" +
        "<div class='padding-top-5 spkr-info padding-right-20'>" +
        "<div class='no-padding spkr-carousel'>" +
        "<span class='spkr-fname'>" + title + " </span><span class='spkr-fname word-wrap'>" + fname + " </span><span class='spkr-lname word-wrap'>" + lname + "</span>" +
        //"<span class='spkr-fname'>Noshank </span><span class='spkr-lname'>hgktlpanmgjtkloa</span>" +
        "</div>" +
        "<div class='spkr-bio'>" +
        "<a  class=\"text-color custom_pointer\" onClick=\"getSpeakerDetails(" + position + ", \'" + name + "\')\"> View Bio</a>" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</div>";

    return speakersectionhtml;
}

var access_CodeTypeEvent = "";
var txtAccessCodeEvent = "";

function BindBtnEventAccessCodeOnEventLandingPage() {   
    $("#modal_EventPageaccessCode").modal('show');
}

function StoreEventPageAccessCode() {
    var AccessCode = ($('#PremiumEvent_AccessCode').val().trim());

    sessionStorage.setItem("accessCode", AccessCode);
    sessionStorage.setItem("accessCodeType", EventAccessCodeType);
    sessionStorage.setItem("accessCodeFlag", false);
}

function StoreAccessCodeInEventPage() {
    txtAccessCodeEvent = ($('#txtAccessCode').val().trim());
    var IsUserLoggedInEventPage = "0";

    if (document.getElementById("rdoSpeaker").checked) {
        sessionStorage.setItem("IsEventVideoAceess", "true");
        sessionStorage.setItem("accessCode", txtAccessCodeEvent);
        sessionStorage.setItem("accessCodeType", SpeakerAccessCodeType);
        sessionStorage.setItem("accessCodeFlag", false);
    }
    else if (document.getElementById("rdoEvent").checked) {

        sessionStorage.setItem("accessCode", txtAccessCodeEvent);
        sessionStorage.setItem("accessCodeType", EventAccessCodeType);
        sessionStorage.setItem("accessCodeFlag", false);
        SetEventAccessCodeDetailsFromLocalStorage();    
        location.href = window.location.href;  
    }
    else if (document.getElementById("rdoVideo").checked) {
        sessionStorage.setItem("accessCode", txtAccessCodeEvent);
        sessionStorage.setItem("accessCodeType", VideoAccessCodeType);
        sessionStorage.setItem("accessCodeFlag", false);
        SetEventAccessCodeDetailsFromLocalStorage();
        location.href = window.location.href;        

    }
}
//This is the temp function
function SetEventAccessCodeDetailsFromLocalStorage() {
    var accessCode = "";
    var accessCodeType = "";
    var accessCodeFlag = "";
    var routeSeriesVideoId = "eventvideoid";

    if (!IsNullOrEmpty(localStorage.getItem("accessCode"))) {
        accessCode = localStorage.getItem("accessCode");
        sessionStorage.setItem("accessCode", accessCode);
    }

    if (!IsNullOrEmpty(localStorage.getItem("accessCodeType"))) {
        accessCodeType = localStorage.getItem("accessCodeType");
        sessionStorage.setItem("accessCodeType", accessCodeType);
    }

    if (!IsNullOrEmpty(localStorage.getItem("accessCodeFlag"))) {
        accessCodeFlag = localStorage.getItem("accessCodeFlag");
        sessionStorage.setItem("accessCodeFlag", accessCodeFlag);
    }

    if (!IsNullOrEmpty(sessionStorage.getItem("RedirectFrom"))) {
        var redirectFrom = sessionStorage.getItem("RedirectFrom")
        if (redirectFrom == routeSeriesVideoId) {
            sessionStorage.setItem("RedirectLocation", routeSeriesVideoId)
        }
    }  
}
function SetRedirectLocationToEventPage() {
    sessionStorage.setItem("IsEventVideoAceess", "true");
    sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);
    //BrowserStorage.setRedireceLocation(Application.EventVideoId.BaseURL);
    //BrowserStorage.setRedireceFrom(Application.EventVideoId.BaseURL);

    BrowserStorage.setRedireceLocation(window.location.href);
    BrowserStorage.setRedireceFrom(window.location.href);
    location.href = "view/" + Application.Login.BaseURL;
}

function toJSDate(date, time) {
    var toDate = date.split("/");
    var toTime = time.split(":");

    //(year, month, day, hours, minutes, seconds, milliseconds)
    //subtract 1 from month because Jan is 0 and Dec is 11
    return new Date(toDate[2], (toDate[1] - 1), toDate[0], toTime[0], toTime[1], 0, 0);
}

function getNormalHeight(elementDiv) {
    if (document.getElementById(elementDiv) != null) {
        var parentDiv = document.getElementById(elementDiv);
        return parentDiv.scrollHeight;
    }
}
this.PlayerDetail = {};
this.RelatedVideos = {};
this.CurrentVideoDetail = {};
this.SpeakerDetails = {};
var entryid = '';
var played = 0;
var isLiveVideoOn = false;
var EventIsDisplayQA = false;
var EventIsDisplayPolling = false;
var EventAccessCodeType = 1;
var VideoAccessCodeType = 3;
var PollQuestionAvailable = 0;
var SeriesvideosPerPage = 20;
var DefaultSeriesVideosDisplayPage = 3;
var currentPage = 1;

var SeriesRepository = {
    MessageViewModel: new MessageViewModel(),

    getSeriesVideo: function (currentRouteSetting, routeCurrentContext, seriesFilter, routeProvider, seriesContext) {
        played = 0;
        var _this = this;
        currentPage = seriesFilter.ViewCount;
        var object = {
            Data: { "currentRequest": seriesFilter }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'SeriesManagement/SeriesService.svc/getSeriesVideo',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            _this.RenderSeriesVideos(currentRouteSetting, routeCurrentContext, seriesFilter, seriesContext, data, routeProvider);
                        }
                    }

                    //VideoRepository.getRelatedVideos(currentRouteSetting, routeProvider, routeCurrentContext, seriesFilter, seriesContext);
                    //_this.getComments(currentRouteSetting, routeProvider, routeCurrentContext, videoFilter, videoContext);
                    //VideoRepository.getRelatedContent(currentRouteSetting, routeProvider, routeCurrentContext, seriesFilter, seriesContext);
                }
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },
    ShowNotFoundMsg: function () {
        $('#LazyLoader').addClass('display-none');
        $('#LazyLoaderComments').addClass('display-none');
        $('#LazyLoaderRelatedContent').addClass('display-none');
        $("#videoDescription").html("Video not found!!");
        $("#videoDescription").css({ "font-size": "25px", "font-weight": "bold" })
        $('#backgroundImage').css("background-image", "url('Images/img_novideo.png')");
        $('#outer_background_image').css("background-image", "url('Images/img_novideo.png')");
        $('.modal-backdrop').remove();
        $(".share-embed-qna-poll-icons-desktop-video").css('display', 'none');
        $(".share-embed-qna-poll-container-desktop").css('display', 'none');
        $("#related-content").hide();
        $("#related-videos").css('display', 'none');
        $(".comment-pagination").css('display', 'none');
        $("#ViewsCount").html("0 Play");
        $("#likevalue").html("0");
        $("#dislikevalue").html("0");
        $(".likevalue").html("0");
        $(".dislikevalue").html("0");
        $('.eventnotfound').hide();
        $('.IfVideoNotFound').hide();
        EviSearchMaintainToggleState();
    },
    getCurrentSeriesVideo: function (currentRouteSetting, routeProvider, routeCurrentContext, seriesFilter, seriesContext) {
        played = 0;
        var _this = this;
        var object = {
            Data: { "currentRequest": seriesFilter }
        };

        //var urlParams = BrowserStorage.getRedireceLocation();
        //var methodname = "";
        //if (urlParams == 'seriesvideoid') {
        //    methodname = "getCurrentSeriesVideo";
        //} else {
        //    methodname = "getCurrentSeriesVideos";

        //}

        
        Repository.LoadDataJSON(WebService.BaseURL + 'SeriesManagement/SeriesService.svc/getCurrentSeriesVideo',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            if (true == true) {
                                // entryid = '0_8g8u8vq3';
                                var isAuthenticated = true;
                                //if (data.LoginStatus == 0) {
                                //    isAuthenticated = true;
                                //}
                                //else
                                //{
                                //    isAuthenticated = false;
                                //}

                                localStorage.setItem("LoginStatus", data.LoginStatus);
                                localStorage.setItem("nextViewVideoCount", "0");
                                var seriesVideosTotalCount = data.ResultObject.seriesVideosTotalCount;
                                var videoDetail = data.ResultObject.PlayerViewModelresult;
                                var seriesDetail = data.ResultObject.SeriesData[0];
                                if (seriesDetail == undefined || seriesDetail == null) {
                                    _this.ShowNotFoundMsg();
                                    return;
                                }
                                var time = new Date();
                                this.CurrentVideoDetail = {
                                    VideoId: videoDetail.VideoId,
                                    ChannelId: videoDetail.ChannelId,
                                    ChannelCategoryTypeId: videoDetail.ChannelCategoryTypeId,
                                    Title: videoDetail.VideoTitle,
                                    VideoTitle: videoDetail.VideoTitle,
                                    Description: videoDetail.ShortDescription,
                                    Abstract: videoDetail.Abstract,
                                    DisplayImage: videoDetail.DisplayImage + "?" + time.getTime(),
                                    ChannelName: videoDetail.ChannelName,
                                    //EntryId: videoDetail.StreamUKId,
                                    EncodedAssetId: videoDetail.EncodedAssetId,
                                    SmoothStreamingURL: videoDetail.SmoothStreamingURL,
                                    ShowOnPortal: videoDetail.ShowOnPortal,
                                    DefaultChannel: videoDetail.channelName,
                                    Permissions: videoDetail.PermissionDetail,
                                    Attachment: videoDetail.Attachment,
                                    ChannelList: videoDetail.ChannelList,//current video detail
                                    Speakers: videoDetail.Speaker,
                                    SpeakerImageSource: videoDetail.SpeakerImageSource,
                                    DefaultSpeakerImage: videoDetail.DefaultSpeakerImage,
                                    Keywordlist: videoDetail.Keywordlist,
                                    HasLock: videoDetail.HasLock,
                                    HasPromo: videoDetail.HasPromo,
                                    PromoType: videoDetail.PromoType,
                                    HasUserAccess: videoDetail.HasUserAccess,
                                    ViewsCount: videoDetail.ViewsCount,
                                    LikesCount: videoDetail.LikesCount,
                                    DisLikesCount: videoDetail.DisLikesCount,
                                    LastLikeDislikeActivity: videoDetail.LastLikeDislikeActivity,
                                    Duration: videoDetail.Duration,
                                    PremiumPrice: videoDetail.PremiumPrice,
                                    CanPlay: videoDetail.CanPlay,
                                    CanLikeDislike: videoDetail.CanLikeDislike,
                                    AllowDownload: videoDetail.AllowDownload,
                                    relatedVideos: videoDetail.RelatedVideos,
                                    AllowAttachmentDownload: videoDetail.AllowAttachmentDownload,
                                    Comments: videoDetail.Comments,
                                    IsCommentsEnable: videoDetail.IsCommentsEnable,
                                    PriceType: videoDetail.PriceType,
                                    Duration: videoDetail.Duration,
                                    SubscriptionType: videoDetail.SubscriptionType,
                                    VideoDate: videoDetail.VideoDate,
                                    RelatedContent: videoDetail.RelatedContent,
                                    IsLive: videoDetail.IsLive,
                                    IsQnAEnabled: videoDetail.DisplayQAndA,
                                    IsPollingEnabled: videoDetail.DisplayPolling,
                                    SponseredItem: videoDetail.SponseredItem,
                                    IsDisplayCPD: videoDetail.DisplayCPD,
                                    CPDLogo: videoDetail.CPDLogo,
                                    TranscriptList: videoDetail.objTranscriptList,
                                    DigitalLibrary: videoDetail.DigitalLibrary,
                                    PremiumDiscountPercentage: videoDetail.PremiumDiscountPercentage,
                                    PremiumDiscountAmount: videoDetail.PremiumDiscountAmount,
                                    SubscriptionType: videoDetail.SubscriptionType,
                                    Duration: videoDetail.Duration,
                                    EventDetails: videoDetail.EventDetails,
                                    DiscountType: videoDetail.DiscountType,
                                    EventDiscount: videoDetail.EventDiscount,
                                    IndividualUserType: videoDetail.IndividualUserType.toLowerCase(),
                                    // Rakesh : Set Transcript Parameters
                                    IsSubTitleContentAvailable: videoDetail.IsSubTitleContentAvailable,
                                    SubTitleJsonPath: videoDetail.SubTitleJsonPath,
                                    lstSrtSubTitles: videoDetail.lstSrtSubTitles,
                                    /// Author: Sanjana
                                    /// Date: 19-07-2017
                                    /// Decription: get and set video duration in 00:00:00 format
                                    TimeDuration: videoDetail.TimeDuration,
                                    VideoNo: videoDetail.VideoNo
                                };

                                //Rakesh: Begin  Load IETTVTranscript.Js and load Transcript Content

                                if (!CurrentVideoDetail.IsLive & !CurrentVideoDetail.HasLock) {
                                    $.getScript("Script/Transcript/IETTVTranscript.js", function () {
                                        if (CurrentVideoDetail.IsSubTitleContentAvailable) {
                                            IETTVTranscript.BindLanguagesDropdown(CurrentVideoDetail.lstSrtSubTitles);
                                            $('.transcript-icon').removeClass('hidden');
                                            // IETTVTranscript.LoadTranscripts(CurrentVideoDetail.SubTitleJsonPath);
                                        }
                                    });
                                }

                                $('.myclips').addClass('disabledbutton');
                                $('.share-img-icon').addClass('disabledbutton');
                                $('.transcript-icon').addClass('hidden');
                                //Rakesh: End
                                /// Author: Sanjana
                                /// Date:02-07-2017
                                /// Decription: hide and show divs
                                if (CurrentVideoDetail.IsLive) {
                                    $('.myclips').addClass('hidden');
                                    $('.share-img-icon').addClass('hidden');
                                }
                                else {
                                    if (!IsNullOrEmpty(sessionStorage.getItem("LogonId"))) {
                                        if (sessionStorage.getItem("IsIPLogin") == null || sessionStorage.getItem("IsIPLogin") == "false") {
                                            $('.myclips').removeClass('hidden');
                                        }
                                        else {
                                            $('.myclips').addClass('hidden');
                                        }
                                    }
                                    else {
                                        $('.myclips').addClass('hidden');
                                    }
                                }
                                //End
                                if (!IsNullOrEmpty(CurrentVideoDetail.EventDetails) && !IsNullOrEmpty(CurrentVideoDetail.EventDetails.Id)) {
                                    sessionStorage.setItem("EventId", CurrentVideoDetail.EventDetails.Id);
                                }
                                //console.log(CurrentVideoDetail);
                                //alert(videoDetail.ChannelName);
                                //videoDetail.PriceType=  SubscriptionType
                                // SubscriptionType = sessionStorage.setItem("data-SubscriptionType", PriceType);
                                // alert(SubscriptionType);
                                $(".div_Videotitle").text(truncateString(CurrentVideoDetail.Title, 58));
                                sessionStorage.setItem("VideoNo", videoDetail.VideoNo);
                                sessionStorage.setItem("SeriesVideoTitle", CurrentVideoDetail.VideoTitle)
                                if (CurrentVideoDetail.HasLock == true) {
                                    $(".share-embed-buttons").css('display', 'none');
                                }
                                if (!IsNullOrEmpty(CurrentVideoDetail.Title)) {
                                    $(".div_Videotitle").text(truncateString(CurrentVideoDetail.Title, 58))
                                }
                                var relatedVideosHTML = '';
                                relatedVideos = CurrentVideoDetail.relatedVideos;
                                if (relatedVideos != null && relatedVideos != '') {
                                    //Rakesh :Related video Count
                                    $('#spnRelatedVideos').html(relatedVideos.length);

                                    $.each(relatedVideos, function (index, data) {
                                        var time = new Date();
                                        relatedVideosHTML += getRelatedSeriesVideoHTML(data.VideoId, data.VideoNo, data.ChannelName, data.VideoTitle, data.DisplayImage + "?" + time.getTime(), data.HasLock, data.ChannelId, data.SubscriptionType, data.Duration, data.IsSeries, data.SeriesCount, data.SeriesCreatedYear);
                                    });
                                    //Rakesh : Added to remove Loaded show videos
                                    $('#LazyLoader').addClass('display-none');
                                    $('#related-videos-dynamic').removeClass('display-none');

                                    $(document).ready($('#related-videos-dynamic').html(relatedVideosHTML));
                                }

                                if (!IsNullOrEmpty(CurrentVideoDetail.VideoId)) {
                                    sessionStorage.setItem("VideoId", CurrentVideoDetail.VideoId);
                                }

                                //$(".sponserdiv").html("");
                                //if (CurrentVideoDetail.SponseredItem != null && CurrentVideoDetail.SponseredItem.SponserImagePath != null) {
                                //    var str = "<a href='#' onclick=OpenURL('" + CurrentVideoDetail.SponseredItem.SponserURL + "')><img src='" + CurrentVideoDetail.SponseredItem.SponserImagePath + "' class='right-video-banner-thumbnail-image'></a>";
                                //    $('.sponserdiv').append(str);
                                //}

                                $("#desktop-cpd-logo").attr("src", "");
                                $("#mobile-cpd-logo").attr("src", "");
                                if (CurrentVideoDetail.IsDisplayCPD && CurrentVideoDetail.CPDLogo != "") {
                                    $("#desktop-cpd-logo").attr("src", CurrentVideoDetail.CPDLogo);
                                    $("#desktop-cpd-logo").css("display", "block");
                                    $("#mobile-cpd-logo").attr("src", CurrentVideoDetail.CPDLogo);
                                    $("#mobile-cpd-logo").css("display", "block");
                                }

                                //var KPlayerDetails = data.ResultObject.PlayerViewModelresult.KalturaPlayerDetail;

                                $('#VideoDate').html(CurrentVideoDetail.VideoDate);
                                //to display premium message text

                                if (CurrentVideoDetail.HasLock == true) {
                                    if (!IsNullOrEmpty(seriesFilter.AccessCode) && parseBool(sessionStorage.getItem("accessCodeFlag")) == false && parseBool(sessionStorage.getItem("accessCodeFlag")) != null) {
                                        var messageViewModel = new MessageViewModel();
                                        messageViewModel.CreateWarningMessage("Access code entered is invalid", "overlayId", "okButtonId")
                                        messageViewModel.ShowOverLay();

                                        sessionStorage.removeItem("accessCode");
                                        sessionStorage.removeItem("accessCodeType");
                                    }

                                    var videoType = '';
                                    var btnPurchaseProduct = '';
                                    var premiumPriceDetailFirst = '';
                                    var premiumPriceDetailSecond = '';
                                    var premiumEventDetail = '';
                                    var btnPurchaseEvent = '';
                                    var premiumhtml = '';
                                    if (CurrentVideoDetail.PriceType != "Free") {
                                        $(".embedmodal").css('display', 'none');
                                        //Message for institute & corporate user if they are trying to purchase product.
                                        if (parseBool(localStorage.getItem("IsIndividualUser")) == true || (sessionStorage.getItem("LogonId") == null || sessionStorage.getItem("LogonId") == "")) {
                                            if (CurrentVideoDetail.PriceType == 'Subscription') {
                                                if (CurrentVideoDetail.ChannelCategoryTypeId == 1) {
                                                    videoType = ' This video is part of paid channel ' + CurrentVideoDetail.ChannelName + '. Please purchase the channel to gain access to the video.';
                                                    btnPurchaseProduct = '<div><button type="button" class="btn btn-default premium_video_btn"  data-innerroutename="buySubscription">Buy channel</button></div>';

                                                    if (CurrentVideoDetail.EventDetails != null && CurrentVideoDetail.EventDetails.Price != '0') {
                                                        var PublishStartDatetime = CurrentVideoDetail.EventDetails.PublishStartDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishStartDate, CurrentVideoDetail.EventDetails.PublishStartTime) : "";
                                                        var CurrentDateTime = new Date();
                                                        var PublishEpiryDatetime = CurrentVideoDetail.EventDetails.PublishExpiryDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishExpiryDate, CurrentVideoDetail.EventDetails.PublishExpiryTime) : "";

                                                        if (data.LoginStatus == ResultStatus.Failed || !(CurrentVideoDetail.EventDetails.IsUserPurchasedPremiumEvent)) {
                                                            var eventHTML = GetEventDetails(PublishStartDatetime, CurrentDateTime, PublishEpiryDatetime, CurrentVideoDetail.EventDetails.IsHideRecord, CurrentVideoDetail.EventDetails.EventStatus, CurrentVideoDetail.EventDetails.eventVideoDetails, CurrentVideoDetail.EventDetails.Title, "btnVisible", data.Message);

                                                            premiumEventDetail = eventHTML.premiumEventDetail;
                                                            btnPurchaseEvent = eventHTML.btnPurchaseEvent;
                                                            //premiumEventDetail = 'This video is part of paid event ' + '<a href="#" data-toggle="modal" data-target="#premiumEventDetails">' + CurrentVideoDetail.EventDetails.Title + '</a>' + '. Please purchase the event to gain access to the video.';
                                                            //btnPurchaseEvent = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                                                            $("#spnEventName").text(CurrentVideoDetail.EventDetails.Title);
                                                            $("#tblEventvideoDetails").html(CurrentVideoDetail.EventDetails.eventVideoDetails);
                                                            $('#tblEventvideoDetails').paging({ limit: 5 });

                                                            if ($(window).width() < 500) {
                                                                $("#divVideoContainer").addClass('premiumVideoWithBuyEvent');
                                                                $(".paging-nav").addClass('paginationDiv');
                                                                $("#divEventDetails").addClass('divBuyEvent');
                                                            }

                                                            WindowResizeForVideo();
                                                        }
                                                    }
                                                }
                                            }
                                            else if (CurrentVideoDetail.PriceType == 'Premium') {
                                                videoType = 'This is a premium video. You can purchase this video for only £' + CurrentVideoDetail.PremiumPrice + ' excluding tax.';
                                                if (CurrentVideoDetail.PremiumDiscountPercentage != '0' && CurrentVideoDetail.PremiumDiscountAmount != '0') {
                                                    premiumPriceDetailFirst = 'This is a premium video. You have a ' + CurrentVideoDetail.PremiumDiscountPercentage + '% discount on this video.'
                                                    premiumPriceDetailSecond = 'Your new purchase price for this video is only £' + CurrentVideoDetail.PremiumDiscountAmount + ' excluding tax.';
                                                }
                                                btnPurchaseProduct = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyVideoPrompt">Buy video</button></div>';
                                                if (CurrentVideoDetail.PremiumDiscountPercentage != '0' && CurrentVideoDetail.PremiumDiscountAmount != '0') {
                                                    $("#spnPremiumPrice").text(CurrentVideoDetail.PremiumDiscountAmount);
                                                }
                                                else {
                                                    $("#spnPremiumPrice").text(CurrentVideoDetail.PremiumPrice);
                                                }

                                                if (CurrentVideoDetail.EventDetails != null && CurrentVideoDetail.EventDetails.Price != '0') {
                                                    var PublishStartDatetime = CurrentVideoDetail.EventDetails.PublishStartDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishStartDate, CurrentVideoDetail.EventDetails.PublishStartTime) : "";
                                                    var CurrentDateTime = new Date();
                                                    var PublishEpiryDatetime = CurrentVideoDetail.EventDetails.PublishExpiryDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishExpiryDate, CurrentVideoDetail.EventDetails.PublishExpiryTime) : "";

                                                    if ((data.LoginStatus == ResultStatus.Failed && CurrentVideoDetail.EventDiscount > 0) ||
                                                        (!(CurrentVideoDetail.EventDetails.IsUserPurchasedPremiumEvent) && (CurrentVideoDetail.PremiumDiscountPercentage == 0 && (CurrentVideoDetail.DiscountType == 'No Discount')) && CurrentVideoDetail.EventDiscount > 0)) {
                                                        var eventHTML = GetEventDetails(PublishStartDatetime, CurrentDateTime, PublishEpiryDatetime, CurrentVideoDetail.EventDetails.IsHideRecord, CurrentVideoDetail.EventDetails.EventStatus, CurrentVideoDetail.EventDetails.eventVideoDetails, CurrentVideoDetail.EventDetails.Title, "btnVisible", data.Message);

                                                        premiumEventDetail = eventHTML.premiumEventDetail;
                                                        btnPurchaseEvent = eventHTML.btnPurchaseEvent;

                                                        //premiumEventDetail = 'This video is part of paid event ' + '<a href="#" data-toggle="modal" data-target="#premiumEventDetails">' + CurrentVideoDetail.EventDetails.Title + '</a>' + '. Please purchase the event to gain discount on the video.';
                                                        //btnPurchaseEvent = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                                                        $("#spnEventName").text(CurrentVideoDetail.EventDetails.Title);
                                                        $("#tblEventvideoDetails").html(CurrentVideoDetail.EventDetails.eventVideoDetails);
                                                        $('#tblEventvideoDetails').paging({ limit: 5 });

                                                        if ($(window).width() < 500) {
                                                            $("#divVideoContainer").addClass('premiumVideoWithBuyEvent');
                                                            $(".paging-nav").addClass('paginationDiv');
                                                            $("#divEventDetails").addClass('divBuyEvent');
                                                        }

                                                        WindowResizeForVideo();
                                                    }

                                                    if (CurrentVideoDetail.EventDiscount < 100) {
                                                        $('#rdoEvent').attr('onclick', 'return false;');
                                                        $('#rdoEvent').addClass('disabledinput');
                                                        $('#rdoEventSpan').addClass('disabledEventSpan');
                                                    }
                                                }

                                                $(".btnCheckOutRedirect").attr({
                                                    "data-lastRouteName": sessionStorage.getItem("LastRouteName"),
                                                    "data-innerroutename": 'address',
                                                    "data-videono": videoDetail.VideoNo,
                                                    "data-seriesid": seriesFilter.SeriesId
                                                });
                                            }

                                            else if (CurrentVideoDetail.PriceType == 'Event Priced' && CurrentVideoDetail.EventDetails.Price != '0') {
                                                var PublishStartDatetime = CurrentVideoDetail.EventDetails.PublishStartDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishStartDate, CurrentVideoDetail.EventDetails.PublishStartTime) : "";
                                                var CurrentDateTime = new Date();
                                                var PublishEpiryDatetime = CurrentVideoDetail.EventDetails.PublishExpiryDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishExpiryDate, CurrentVideoDetail.EventDetails.PublishExpiryTime) : "";

                                                var eventHTML = GetEventDetails(PublishStartDatetime, CurrentDateTime, PublishEpiryDatetime, CurrentVideoDetail.EventDetails.IsHideRecord, CurrentVideoDetail.EventDetails.EventStatus, CurrentVideoDetail.EventDetails.eventVideoDetails, CurrentVideoDetail.EventDetails.Title, 'EventPriced', data.Message);
                                                videoType = eventHTML.videoType;
                                                btnPurchaseProduct = eventHTML.btnPurchaseProduct;

                                                //videoType = ' This video is part of paid event ' + CurrentVideoDetail.EventDetails.Title + '. Please purchase the event to gain access to the video.';
                                                //btnPurchaseProduct = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                                            }
                                        }
                                        else {
                                            if (CurrentVideoDetail.PriceType == 'Subscription') {
                                                
                                                //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                                                if (data.Message != null && data.Message != null) {
                                                    var messageViewModel = new MessageViewModel();
                                                    messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                                    messageViewModel.ShowOverLay();
                                                }
                                                //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end
                                                videoType = ' This video is part of paid channel ' + CurrentVideoDetail.ChannelName + '. Kindly contact the IET Administrator to gain access to this channel.';
                                            }
                                            else if (CurrentVideoDetail.PriceType == 'Premium') {
                                               
                                                //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                                                if (data.Message != null && data.Message != null) {
                                                    var messageViewModel = new MessageViewModel();
                                                    messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                                                    messageViewModel.ShowOverLay();
                                                }
                                                //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end
                                                videoType = 'This is a premium video. Kindly contact the IET Administrator to gain access to this video.';
                                                if (CurrentVideoDetail.EventDetails != null && CurrentVideoDetail.EventDetails.Price != '0') {
                                                    if ((data.LoginStatus == ResultStatus.Failed) || (!(CurrentVideoDetail.EventDetails.IsUserPurchasedPremiumEvent) && (CurrentVideoDetail.PremiumDiscountPercentage == 0 && (CurrentVideoDetail.DiscountType == 'No Discount' || CurrentVideoDetail.DiscountType == null)))) {
                                                        if (CurrentVideoDetail.EventDiscount < 100) {
                                                            $('#rdoEvent').attr('onclick', 'return false;');
                                                            $('#rdoEvent').addClass('disabledinput');
                                                            $('#rdoEventSpan').addClass('disabledEventSpan');
                                                        }
                                                    }
                                                }
                                            }
                                            else if (CurrentVideoDetail.PriceType == 'Event Priced' && CurrentVideoDetail.EventDetails.Price != '0') {
                                                var PublishStartDatetime = CurrentVideoDetail.EventDetails.PublishStartDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishStartDate, CurrentVideoDetail.EventDetails.PublishStartTime) : "";
                                                var CurrentDateTime = new Date();
                                                var PublishEpiryDatetime = CurrentVideoDetail.EventDetails.PublishExpiryDate != null ? toJSDate(CurrentVideoDetail.EventDetails.PublishExpiryDate, CurrentVideoDetail.EventDetails.PublishExpiryTime) : "";

                                                var eventHTML = GetEventDetails(PublishStartDatetime, CurrentDateTime, PublishEpiryDatetime, CurrentVideoDetail.EventDetails.IsHideRecord, CurrentVideoDetail.EventDetails.EventStatus, CurrentVideoDetail.EventDetails.eventVideoDetails, CurrentVideoDetail.EventDetails.Title, 'btnInvisible', data.Message);

                                                videoType = eventHTML.videoType;

                                                //videoType = ' This video is part of paid event ' + CurrentVideoDetail.EventDetails.Title + '. Kindly contact the IET Administrator to gain access to this event.';
                                            }
                                        }
                                        premiumhtml = '<div id="premium_video_text" class="premium_video_text premium_video_mobile_text col-md-10" style="text-align:center">'
                                        if (CurrentVideoDetail.ChannelCategoryTypeId == 1 || ((CurrentVideoDetail.ChannelCategoryTypeId == 2 || CurrentVideoDetail.ChannelCategoryTypeId == 3) && CurrentVideoDetail.PriceType == 'Premium')) {
                                            if (premiumPriceDetailFirst == '' && premiumPriceDetailSecond == '') {
                                                premiumhtml += '<p>' + videoType + ' </p>' + btnPurchaseProduct;
                                            }
                                            else {
                                                premiumhtml += '<p>' + premiumPriceDetailFirst + ' </p>' + '<p>' + premiumPriceDetailSecond + ' </p>' + btnPurchaseProduct;
                                            }

                                            if (premiumEventDetail != '') {
                                                premiumhtml += '<p class="margin-top-10">' + premiumEventDetail + '</p>' + btnPurchaseEvent;
                                            }

                                            if (data.LoginStatus == ResultStatus.Failed) {
                                                premiumhtml += '<div class="margin-top-10"> Already bought this video? To view please <a href="view/LoginNew.html">Log in</a></div>';
                                            }
                                        }

                                        if (CurrentVideoDetail.EventDetails != null) {
                                            if (CurrentVideoDetail.EventDetails.MemberDiscount != '0' && CurrentVideoDetail.EventDetails.DiscountAmount > 0) {
                                                $("#spnPremiumEventPrice").text(CurrentVideoDetail.EventDetails.DiscountAmount);
                                            }
                                            else {
                                                $("#spnPremiumEventPrice").text(CurrentVideoDetail.EventDetails.Price);
                                            }

                                            $(".btnEventCheckOutRedirect").attr({
                                                "data-lastRouteName": sessionStorage.getItem("LastRouteName"),
                                                "data-innerroutename": 'address',
                                                "data-eventid": CurrentVideoDetail.EventDetails.Id,
                                                "data-videono": videoDetail.VideoNo,
                                                "data-seriesid": seriesFilter.SeriesId
                                            });
                                        }
                                    }
                                    premiumhtml += '<div style="margin-top:10px">If you have an Access Code, Please enter code <a href="" data-toggle="modal" data-target="#modal_SingleAccessCode">here</a></div>';
                                    $("#premiumprice").text(CurrentVideoDetail.PremiumPrice);
                                    //console.log(premiumhtml);
                                    $(".video-overlay-div").addClass('alpha30');
                                    $(".video-overlay-text").html(premiumhtml);
                                    //var premium_video_div_height = getDivHeight($("#premium_video_text").height());
                                    //var height_premium_text = $(".videoBtns").height() / 2;
                                    var premium_video_div_height = getDivHeight($("#premium_video_text").height());
                                    var t = $(".videoBtns").height() / 2;
                                    //alert(t);
                                    $("div#premium_video_text").css("margin-top", "-" + premium_video_div_height - t);
                                    //code to avoid IOS devices

                                    $('#lockBtn').addClass('cursor-default');
                                    $(window).resize(function () {
                                        /* to adjust overlay text */
                                        var premium_video_div_height = getDivHeight($("#premium_video_text").height());
                                        var t = $(".videoBtns").height() / 2;
                                        $("div#premium_video_text").css("margin-top", "-" + premium_video_div_height - t);
                                    });

                                    // console.log('===' + premium_video_div_height);

                                    //handleEventQnA();
                                    routeProvider.bindRoutes();
                                    seriesContext.BindPlaybtnClick();
                                }
                                else {
                                    if (!IsNullOrEmpty(seriesFilter.AccessCode)) {
                                        sessionStorage.setItem("accessCodeFlag", true);

                                        if (IsNullOrEmpty(sessionStorage.getItem("LogonId")) == true) {
                                            if (parseInt(sessionStorage.getItem("accessCodeType")) == 1) {
                                                //localStorage.setItem("Welcome", sessionStorage.getItem("delegateName"));
                                            }
                                            else {
                                                if (data.ResultObject.PlayerViewModelresult.AccessSpeaker != null) {
                                                    localStorage.setItem("Welcome", data.ResultObject.PlayerViewModelresult.AccessSpeaker.FirstName + " " + data.ResultObject.PlayerViewModelresult.AccessSpeaker.LastName);
                                                }
                                            }
                                            //Additional login to check if user is login then only set the login options
                                            if (!IsNullOrEmpty(localStorage.getItem("LoginStatus")) && localStorage.getItem("LoginStatus") !== "-1") {
                                                var objLoginRepository = new LoginRepository();
                                                objLoginRepository.setMessageForSpeaker();
                                            }
                                        }
                                    }
                                }
                                //var desc = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
                                //$("#videoDescription").html(AddReadMore(CurrentVideoDetail.Abstract));
                                //$("#videoDescription").html(desc);
                                $("#videoDescription").html(CurrentVideoDetail.Abstract);
                                //$("#videoDescription").html('<p>Phasellus lorem lacus, vestibulum a tristiquePhasellus lorem lacus, vestibulum a tristiquePhasellus lorem lacus, vestibulum a tristiquePhasellus lorem lacus, vestibulum a tristiquePhasellus lorem lacus, vestibulum a tristiquePhasellus lorem lacus, vestibulum a tristique</p> <p>ut, consectetur sit amet nisl. Maecenas nec metus vel libero aliquet accumsan. Nunc vel sem ac justo hendrerit sagittis.</p><p>Proin nec ultrices dui. Aliquam justo nibh, malesuada ac lacinia eget, tempor eget dolor. Mauris finibus magna at lacus gravida, vehicula iaculis ex efficitur. Integer eu sapien at leo rhoncus sodales. Proin tincidunt quam eu molestie semper. Donec elementum,</p> <p>ligula aliquam porttitor ultrices, sapien lorem cursus lorem, non molestie ligula neque ut velit. Aliquam laoreet, leo eget ultrices sagittis, felis mauris varius nulla, quis interdum est leo non est. Ut fermentum ante est, a feugiat nisi bibendum a. Etiam euismod ultrices hendrerit. Aenean et eros a urna placerat volutpat sed id lectus. Suspendisse ultricies ornare accumsan. Ut nulla enim, pharetra in hendrerit sed, fringilla ultricies purus. Ut tristique orci purus, vitae dapibus est malesuada aliquet.</p>');
                                // $('.morelink').click(toogleReadMoreLess);

                                //$(".video-main-caption").html(truncateString(CurrentVideoDetail.Title, 58))

                                if (window.matchMedia('(max-width: 400px)').matches) {
                                    $(".video-main-caption").html(truncateString(CurrentVideoDetail.Title, 30));
                                }
                                else if (window.matchMedia('(max-width: 767px)').matches) {
                                    $(".video-main-caption").html(truncateString(CurrentVideoDetail.Title, 40));
                                }
                                else {
                                    $(".video-main-caption").html(truncateString(CurrentVideoDetail.Title, 58));
                                }

                                if (CurrentVideoDetail.HasPromo == false) {
                                    $(".video-main-time").html(CurrentVideoDetail.Duration);
                                }
                                //    $(".video-main-pricetype").html(CurrentVideoDetail.SubscriptionType);

                                var entryid = CurrentVideoDetail.EntryId;
                                var url = window.location.href;
                                var embedurl = '<iframe width="550" height="310"  name="' + entryid + '" src="' + url.substring(0, url.lastIndexOf('/') + 1) + "EmbedPlayer.aspx?videoid=" + seriesFilter.VideoNo + "&guid=" + this.CurrentVideoDetail.VideoId + '" allowfullscreen></iframe>';
                                var facebookTwitterLink = url.substring(0, url.lastIndexOf('/') + 1) + "EmbedPlayer.aspx?videoid=" + this.CurrentVideoDetail.VideoNo + "&guid=" + this.CurrentVideoDetail.VideoId; //Modified code for PS-1470:IET TV- 'Video Not Found' is appearing while playing Embed link of a Series
                                $("input[name='txtembedSeries']").val(embedurl);
                                $("input[name='txtFacebookTwitterSeries']").val(facebookTwitterLink);

                                //speaker
                                var speakersection = ''
                                if (CurrentVideoDetail.Speakers != null) {
                                    $.each(CurrentVideoDetail.Speakers, function (index, speaker) {
                                        var SpeakerImage = '';
                                        if (speaker.PictureUrl.indexOf("$") != -1) {
                                            SpeakerImage = speaker.PictureUrl.slice(0, speaker.PictureUrl.lastIndexOf("$"));
                                        }
                                        else
                                            SpeakerImage = CurrentVideoDetail.SpeakerImageSource + speaker.PictureUrl;

                                        speakersection += SpeakerHTML(index, speaker.Title, speaker.FirstName, speaker.LastName, SpeakerImage);

                                        $(".carousel-inner").html(speakersection);
                                    });
                                }

                                //keyword logic
                                var keywordsection = '';
                                var inspeckeywordsection = '';
                                if (CurrentVideoDetail.Keywordlist.length != 0) {
                                    $.each(CurrentVideoDetail.Keywordlist, function (index, keyword) {
                                        if (keyword.KeywordType == "custom") {
                                            keywordsection += KeywordHTML(keyword.KeywordName, keyword.KeywordId);
                                        }
                                        else {
                                            inspeckeywordsection += KeywordHTML(keyword.KeywordName, keyword.KeywordId);
                                        }
                                    });
                                }

                                if (keywordsection != '') {
                                    $('.custom-keywords').html("Custom Keywords");
                                }
                                if (inspeckeywordsection != '') {
                                    $('.inspec-keywords').html("Inspec Keywords");
                                }

                                $(".video-keywords-container").html(keywordsection);
                                $(".inspec-video-keywords-container").html(inspeckeywordsection);

                                //speaker
                                var speakersection = ''
                                if (CurrentVideoDetail.Speakers != null) {
                                    $.each(CurrentVideoDetail.Speakers, function (index, speaker) {
                                        var SpeakerImage = '';
                                        if (speaker.PictureUrl.indexOf("$") != -1) {
                                            SpeakerImage = speaker.PictureUrl.slice(0, speaker.PictureUrl.lastIndexOf("$"));
                                        }
                                        else
                                            SpeakerImage = CurrentVideoDetail.SpeakerImageSource + speaker.PictureUrl;

                                        speakersection += SpeakerHTML(index, speaker.Title, speaker.FirstName, speaker.LastName, SpeakerImage);

                                        $(".carousel-inner").html(speakersection);
                                    });
                                }

                                //channel list
                                if (CurrentVideoDetail.ChannelList != null) {
                                    var channelSectionHtml;
                                    var channelSectionHtml_title;
                                    channelSectionHtml_title = '<div  class="title_video" style="padding-left:2px">' + CurrentVideoDetail.Title + '</div>'
                                    channelSectionHtml = '<div class="margin-right-15 float-left" style="padding-top: 4px"> This video is from: </div>'
                                    $.each(CurrentVideoDetail.ChannelList, function (index, channel) {
                                        channelSectionHtml += ChannelHTML(channel.Name, channel.Id, channel.ChannelIconImage, channel.Duration, channel.SubscriptionType);
                                    });
                                }

                                $("#videoChannel").html(channelSectionHtml);
                                $("#Video_Title").html(channelSectionHtml_title);
                                // $('#backgroundImage').attr("src", "Images/logo.png");
                                $('#backgroundImage').attr("src", CurrentVideoDetail.DisplayImage);
                                $('#backgroundImage').css("background-image", "url(" + CurrentVideoDetail.DisplayImage + ")");
                                $('#outer_background_image').css("background-image", "url('" + CurrentVideoDetail.DisplayImage + "')");
                                // $('#backgroundImage').attr("alt", CurrentVideoDetail.Title);
                                //if (CurrentVideoDetail.Permissions[0].VideoThumbnailURL != "" && CurrentVideoDetail.Permissions[0].VideoThumbnailURL != null) {
                                //    $('#backgroundImage').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailURL + "')");
                                //    $('#outer_background_image').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailURL + "')");
                                //}
                                //else
                                //{
                                //    $('#backgroundImage').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailBannerURL + "')");
                                //    $('#outer_background_image').css("background-image", "url('" + CurrentVideoDetail.Permissions[0].VideoThumbnailBannerURL + "')");
                                //}

                                if (CurrentVideoDetail.HasUserAccess) {
                                    //player logic
                                    //this.PlayerDetail = {
                                    //    PartnerId: KPlayerDetails.PartnerId,
                                    //    PlayerId: KPlayerDetails.PlayerId,
                                    //    CacheStrng: KPlayerDetails.PlayerCacheString,
                                    //    EntryId: CurrentVideoDetail.EntryId,
                                    //    Ks: KPlayerDetails.PlayerSession
                                    //};
                                }

                                $.ajax({
                                    url: 'Script/jquery.countdown.js',
                                    async: false,
                                    dataType: "script",
                                    success: function (jsonData) {
                                    }
                                });

                                if (CurrentVideoDetail.HasPromo == true) {
                                    $("#playBtn").addClass('cursor-default');
                                    _this.AllowDownload(false);
                                    _this.CanLikeDislike1(false);
                                    var PromoDetail = {
                                        HasCountdown: videoDetail.HasCountdownStatus,
                                        CountDateTime: videoDetail.CountdownDateTime
                                    }

                                    if (PromoDetail.HasCountdown == true) {
                                        //var currentDate = new date();
                                        //countlogic
                                        if (!IsNullOrEmpty(videoDetail.CountdownUTCDateTime) && !IsNullOrEmpty(videoDetail.FinalPublishDateTime)) {
                                            var currentDateTime = new Date();

                                            //Assign DateTime in UTC to Jquery Object
                                            var FinalPublishUTCDateObject = videoDetail.FinalPublishDateTime;
                                            var CountDownUTCDateObject = videoDetail.CountdownUTCDateTime;

                                            //This will give client time zone specific DateTime
                                            var utcFinalPublishDateTime = new Date(Date.UTC(FinalPublishUTCDateObject.YearPartOfDate, FinalPublishUTCDateObject.MonthPartOfDate - 1, FinalPublishUTCDateObject.DayPartOfDate, FinalPublishUTCDateObject.HourPartOfDate, FinalPublishUTCDateObject.MinutePartOfDate, FinalPublishUTCDateObject.SecondPartOfDate));
                                            var utcCountdownUTCDateTime = new Date(Date.UTC(CountDownUTCDateObject.YearPartOfDate, CountDownUTCDateObject.MonthPartOfDate - 1, CountDownUTCDateObject.DayPartOfDate, CountDownUTCDateObject.HourPartOfDate, CountDownUTCDateObject.MinutePartOfDate, CountDownUTCDateObject.SecondPartOfDate));

                                            var localDate = new Date()
                                            var offsetToUTC = localDate.getTimezoneOffset();

                                            var zoneDiff;

                                            if (offsetToUTC != 0) {
                                                zoneDiff = -(offsetToUTC / 60);
                                            }
                                            else {
                                                zoneDiff = 0;
                                            }

                                            if (currentDateTime > utcCountdownUTCDateTime && currentDateTime <= utcFinalPublishDateTime) {
                                                //This has to be universal time as the CountDown plugin auto calculates the CountDown datetime depending upon the browser's TimeZone
                                                if ($('#countDown').countdown != null) {
                                                    $('#countDown').countdown({ until: utcFinalPublishDateTime, timezone: zoneDiff, compact: true, onExpiry: _this.ExecCountDownExpiry });
                                                    $('#countDown').css("display", "block");
                                                }
                                            }
                                        }
                                    }
                                }
                                //lock functionality
                                _this.CheckLock(CurrentVideoDetail.HasLock);
                                if (CurrentVideoDetail.HasPromo == false) {
                                    _this.AllowDownload(CurrentVideoDetail.AllowDownload);
                                    _this.CanLikeDislike1(CurrentVideoDetail.CanLikeDislike);
                                }
                                _this.RenderAttachment(CurrentVideoDetail.AllowAttachmentDownload);
                                _this.RenderTranscript(CurrentVideoDetail.AllowAttachmentDownload);
                                _this.RenderIETDigitalLibrary(CurrentVideoDetail.DigitalLibrary);
                                _this.CommentsEnableDisable(CurrentVideoDetail.IsCommentsEnable);
                                _this.ShowRelatedContent(CurrentVideoDetail.RelatedContent);

                                if (CurrentVideoDetail.HasUserAccess) {
                                    var lastactivity = videoDetail.LastLikeDislikeActivity;
                                    if (CurrentVideoDetail.CanLikeDislike) {
                                        _this.ToggleLikeDislike(lastactivity);
                                    }
                                }
                                else {
                                    //below two function not required
                                    // _this.HideLikeDislike(true)
                                    //    _this.HideDownload(true)
                                    //_this.RenderAttachment(false);
                                }
                                RenderScript();
                                $('.modal-backdrop').remove();
                                routeProvider.bindInnerRoutes();
                                if (!WebService.DisableGA) {
                                    storeurlDetailsInGA('Series Title - ' + seriesDetail.SeriesName);
                                }
                                seriesContext.BindPlaybtnClick();
                            }
                            else {
                                //not access logic
                                _this.CheckLock(CurrentVideoDetail.HasLock);
                                _this.AllowDownload(CurrentVideoDetail.AllowDownload);
                                _this.CanLikeDislike1(CurrentVideoDetail.CanLikeDislike);
                                _this.RenderAttachment(CurrentVideoDetail.AllowAttachmentDownload);
                                _this.RenderTranscript(CurrentVideoDetail.AllowAttachmentDownload);
                                _this.CommentsEnableDisable(CurrentVideoDetail.IsCommentsEnable)
                            }

                            $(".series-name").html(seriesDetail.SeriesName)
                            sessionStorage.setItem("SeriesName", seriesDetail.SeriesName);
                            sessionStorage.setItem("SeriesId", seriesDetail.SeriesId);
                            //$(".eventwebsite").attr("href", seriesDetail.Url)
                            //$(".eventwebsite").html(seriesDetail.Url)
                            $("#serieslogo").attr('src', seriesDetail.IconImage);

                            $(".sponserdiv").html("");
                            if (seriesDetail.SponseredItem != null && seriesDetail.SponseredItem.SponserImagePath != null) {
                                var str = "<a href='#' onclick=OpenURL('" + seriesDetail.SponseredItem.SponserURL + "')><img src='" + seriesDetail.SponseredItem.SponserImagePath + "' class='right-video-banner-thumbnail-image'></a>";
                                $('.sponserdiv').append(str);
                            }
                            else {
                                $('#video-content').parent("div").removeClass('col-md-6 col-sm-6').addClass('col-md-9 col-sm-9');
                            }

                            _this.RenderSeriesVideos(currentRouteSetting, routeCurrentContext, seriesFilter, seriesContext, data, routeProvider);
                        }

                        var KeyWordsString = [];

                        if (!IsNullOrEmpty(CurrentVideoDetail.Keywordlist)) {
                            if (CurrentVideoDetail.Keywordlist.length > 0) {
                                //for (i = 0; i < CurrentVideoDetail.Keywordlist.length; i++) {
                                //    //KeyWordsString += CurrentVideoDetail.Keywordlist[i].KeywordName + ' OR ';
                                //    KeyWordsString.push(CurrentVideoDetail.Keywordlist[i].KeywordName);
                                //}

                                //var KeyWordsQuery = '["' + KeyWordsString.join('"] OR ["') + '"]';

                                //console.log(KeyWordsQuery);

                                var googleSearch = new GoogleSearch();
                                //googleSearch.SearchTerm = KeyWordsQuery;
                                googleSearch.Init(CurrentVideoDetail.VideoNo);
                            }
                        }

                        //if (!WebService.DisableChat) {
                        //    if (CurrentVideoDetail.IsLive) {
                        //        var qna = new QnA();
                        //        qna.submitMessage();
                        //        qna.Init('Video', true);

                        //        //var hub = qna.Chat;

                        //        qna.QnARepository.GetMessagesForGroup(qna.GroupName);
                        //        qna.QnARepository.GetAllAbusiveWords();
                        //    }
                        //    else {
                        //        var qna = new QnA();
                        //        qna.Init('Video', false);
                        //        qna.QnARepository.GetMessagesForGroup(qna.GroupName);
                        //        //$('.QnA-main').attr('disabled', 'disabled');
                        //        $('#txtMessage').attr('disabled', 'disabled');
                        //    }
                        //}

                        //var poll = new Poll();
                        //poll.Init('Video');

                        VideoIsDisplayQA = CurrentVideoDetail.IsQnAEnabled;
                        VideoIsDisplayPolling = CurrentVideoDetail.IsPollingEnabled;

                        //console.log('Videorepo' + PollQuestionAvailable);

                        if (PollQuestionAvailable == 0) {
                            //This is to analyze the flow

                            VideoIsDisplayPolling = false;
                        }

                        if (VideoIsDisplayQA == 1) {
                            QnAVisibleVideo = 1;
                        }
                        else {
                            QnAVisibleVideo = 0;
                        }

                        if (VideoIsDisplayPolling == 1) {
                            PollVisibleVideo = 1;
                        }
                        else {
                            PollVisibleVideo = 0;
                        }

                        if (VideoIsDisplayQA == 1 && VideoIsDisplayPolling == 1) {
                            QnAVisibleVideo = 0;
                        }

                        //flag to check if QnA is available  for this event
                        QnAAvailableVideo = VideoIsDisplayQA;
                        //flag to check if QnA is visible

                        if (WebService.DisableChat) {
                            QnAAvailableVideo = false;
                        }

                        //flag to check if Poll is available for this event
                        PollAvailableVideo = VideoIsDisplayPolling;
                        //flag to check if Poll is visible

                        //onVideoPageLoad();

                        //VideoRepository.getRelatedVideos(currentRouteSetting, routeProvider, routeCurrentContext, seriesFilter, seriesContext);
                        //_this.getComments(currentRouteSetting, routeProvider, routeCurrentContext, videoFilter, videoContext);
                        //VideoRepository.getRelatedContent(currentRouteSetting, routeProvider, routeCurrentContext, seriesFilter, seriesContext);

                        $(document).ready(function () {
                            var eviSearchPagination = parseBool(localStorage.getItem("eviSearchRoute"));
                            if (eviSearchPagination && sessionStorage.getItem("searchTranscriptTerm") != "" && !CurrentVideoDetail.HasLock) {
                                if ($(window).width() < 992) {
                                    $('.transcript-toggle').trigger("click");
                                }
                                else {
                                    $('.transcript-increase').trigger("click");
                                }
                            }
                        });
                    }
                }
                else {
                    $(".share-embed-qna-poll-icons-desktop-video").css('display', 'none');
                    $(".share-embed-qna-poll-container-desktop").css('display', 'none');
                    _this.ShowNotFoundMsg();
                    return;
                }
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    RenderSeriesVideos: function (currentRouteSetting, routeCurrentContext, seriesFilter, seriesContext, data, routeProvider) {
        var nextViewVideoCount = 0;
        var seriesVideosHTML = ''
        var seriesVideosTotalCount = 0;
        var seriesVideosAndEventsTotalCount = 0;
        var eventIds = data.ResultObject.EventId;
        if (!IsNullOrEmpty(data.ResultObject.SeriesVideosDetail)) {
            if (data.ResultObject.SeriesVideosDetail.length > 0) {
                seriesVideosTotalCount = data.ResultObject.seriesVideosTotalCount;
                seriesVideosAndEventsTotalCount = data.ResultObject.seriesVideosAndEventsTotalCount;

                //Rakesh : Set Series count
                $('#spnSeriesVideosCount').html(data.ResultObject.SeriesVideosDetail.length);

                for (k = 0; k < data.ResultObject.SeriesVideosDetail.length; k++) {
                    //var startIndex = 1;
                    //var endIndex = 1;
                    //if (currentPage == 1) {
                    //    startIndex = 1;
                    //    endIndex = currentPage * VideosPerPage;
                    //}
                    //else {
                    //    startIndex = (currentPage * VideosPerPage) - VideosPerPage + 1;
                    //    endIndex = currentPage * VideosPerPage;
                    //}
                    //if (startIndex <= k + 1 && endIndex >= k + 1) {
                    var seriesVideosDetail = data.ResultObject.SeriesVideosDetail[k];
                    var time = new Date();
                    seriesVideosHTML += searchSeriesVideos(seriesVideosDetail.VideoId, seriesVideosDetail.VideoNo, seriesVideosDetail.ChannelName, seriesVideosDetail.VideoTitle, seriesVideosDetail.DisplayImage + "?" + time.getTime(), seriesVideosDetail.HasLock, seriesVideosDetail.ChannelId, seriesVideosDetail.ChannelColor, seriesVideosDetail.ChannelMappingDetail, seriesVideosDetail.IsJisc, seriesVideosDetail.SubscriptionType, seriesVideosDetail.Duration, seriesVideosDetail.IsEvent, seriesVideosDetail.EventId, seriesVideosDetail.EventName, seriesVideosDetail.IsHideRecord, seriesVideosDetail.EventStatus, seriesVideosDetail.PublishStartDate, seriesVideosDetail.PublishStartTime, seriesVideosDetail.PublishExpiryDate, seriesVideosDetail.PublishExpiryTime, seriesVideosDetail.Speaker);
                    //}
                }
            }

            $('#SearchResult').html(seriesVideosHTML);

            var displayPages = seriesVideosAndEventsTotalCount / SeriesvideosPerPage;
            //var currentPage = 1;
            var seriesName = IsNullOrEmpty(sessionStorage.getItem("SeriesName")) ? "" : sessionStorage.getItem("SeriesName");
            $("#seriesNoOfVideos").html(seriesVideosTotalCount + " Videos from the " + seriesName);
            if (seriesVideosAndEventsTotalCount == 1) {
                $("#result").html("<p>" + seriesVideosAndEventsTotalCount + " result found, </p>");
            }
            else {
                $("#result").html("<p>" + seriesVideosAndEventsTotalCount + " results found, </p>");
            }
            $("#pageno").html("<p> page " + currentPage + " of " + Math.ceil(displayPages) + " </p>");
            $("#mobileresult").html("<p class=\"float-left\">page " + currentPage + " of " + Math.ceil(displayPages) + " </p>")

            if (localStorage.getItem("nextViewVideoCount") == "null" || localStorage.getItem("nextViewVideoCount") == "" || localStorage.getItem("nextViewVideoCount") == null) {
                localStorage.setItem("nextViewVideoCount", "0");
            }

            if (eventIds != null && eventIds != "") {
                //sessionStorage.setItem("SeriesEventIds", eventIds);
                sessionStorage.setItem("SeriesEventIds", JSON.stringify(eventIds));
            }

            nextViewVideoCount = localStorage.getItem("nextViewVideoCount");

            if (nextViewVideoCount == 0 && seriesVideosAndEventsTotalCount > SeriesvideosPerPage) {
                localStorage.setItem("nextViewVideoCount", "1");

                $(".pageNavigation").twbsPagination({
                    totalPages: Math.ceil(displayPages),
                    start: 1,
                    visiblePages: DefaultSeriesVideosDisplayPage,
                    first: "First",
                    last: "Last",

                    onPageClick: function (event, page) {
                        var seriesId = IsNullOrEmpty(sessionStorage.getItem("SeriesId")) ? "" : sessionStorage.getItem("SeriesId");
                        var videoId = IsNullOrEmpty(sessionStorage.getItem("VideoId")) ? "" : sessionStorage.getItem("VideoId");
                        var accessCode = IsNullOrEmpty(sessionStorage.getItem("accessCode")) ? "" : sessionStorage.getItem("accessCode");
                        var accessCodeType = IsNullOrEmpty(sessionStorage.getItem("accessCodeType")) ? "0" : sessionStorage.getItem("accessCodeType");

                        $("#hdnCurrentPage").val(page);

                        var seriesFilter = {
                            SeriesId: seriesId,
                            VideoId: videoId,
                            LogonId: BrowserStorage.getLogonId(),
                            AccessCode: accessCode,
                            AccessCodeType: accessCodeType,
                            SelectedSeriesDate: '',
                            ViewCount: page,
                            EventId: eventIds
                        };

                        seriesFilter.SortBy = $(".seriesSearchResultdropdown-text").first().attr("data-sortTypeKey");

                        SeriesRepository.getSeriesVideo(currentRouteSetting, routeCurrentContext, seriesFilter, routeProvider, seriesContext);
                    }
                });
            }

            if (seriesVideosAndEventsTotalCount > SeriesvideosPerPage) {
                localStorage.setItem("nextViewCommentCount", "1");

                //$(".pageNavigation").twbsPagination({
                //    totalPages: Math.ceil(displayPages),
                //    //start: 1,
                //    visiblePages: DefaultSeriesVideosDisplayPage,
                //});
            }

            //if (seriesVideosTotalCount > SeriesvideosPerPage) {
            //    $(".pagination-panel").css("display", "block");
            //}

            routeProvider.bindInnerRoutes();
        }
        else {
            $("#result").html("No result found");
            //$(".search-title").html("<h3 style=\"float: left;\">" + IsNullOrEmpty(Result.QSearchText) ? searchkeyword : Result.QSearchText + "</h3>");
            //$("#mobileresult").html("<p class=\"float-right\"> No result found</p>");
            $("#comments_pageno").html("");
            $("#mobileresult").html("");
            $(".pagination-panel").css("display", "none");
        }
    },

    CommentsEnableDisable: function (commentsIsEnable) {
        //  console.log(commentsIsEnable);
        if (commentsIsEnable == false) {
            $("#comments-panel :input").prop('disabled', true);
            $("#comments-panel :input").prop('title', 'Please login');
            //$("#comments-panel>a").css('pointer-events', 'none');
            //$("#comments-panel>a").css('cursor', 'default');
            // $("#comments-panel a").click(function () { return false });
            //$("#comments-panel").find('a') .prop('disabled', true);
        }
        else {
            $("#comments-panel :input").prop('disabled', false);
            $("#comments-panel :input").prop('title', '');
            // $("#comments-panel a").click(function () { return false });
            //$("#comments-panel > a").css('pointer-events', 'none');
            //$("#comments-panel > a").css('cursor', 'default');
            //  $("#comments-panel :a").prop('disabled', true);
            //  $("#comments-panel").find('a').prop('disabled', true);
        }
    },

    ExecCountDownExpiry: function () {
        $('#countDown').hide();
        location.reload(true)
        //  $("[data-innerroutename='video']").click();
    },

    DownloadVideo: function (currentRouteSetting, routeProvider, routeCurrentContext) {
        var _this = this;
        var video = CurrentVideoDetail;

        //var Download = {
        //    Action: "Download",
        //    LogonId: BrowserStorage.getLogonId(),
        //    VideoID: video.VideoId,
        //    Type: "Video",
        //    VideoTitle: video.Title,
        //    Name: video.Title,
        //    ChannelID: video.ChannelId,
        //    EntryID: PlayerDetail.EntryId,
        //    SubscriptionType: video.PriceType,
        //    Duration: video.Duration
        //};

        var object = {
            Data: { "encodedAssetID": CurrentVideoDetail.EncodedAssetId }
        };

        //console.log(Download);

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetDownloadURL',//DownloadLink',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            var videodetail = data.ResultObject;

                            window.location.href = videodetail;
                        }
                        else {
                        }
                    }
                }
                else {
                }
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    /*code added for the download atytachemnt*/
    DownloadAttachment: function (currentRouteSetting, routeProvider, routeCurrentContext) {
        var _this = this;
        var video = CurrentVideoDetail;

        var Download = {
            Action: "AttachmentDownload",
            LogonId: BrowserStorage.getLogonId(),
            VideoID: video.VideoId,
            Type: "Attachment",
            VideoTitle: video.Title,
            //Name: video.Attachment,
            ChannelID: video.ChannelId,
            SubscriptionType: video.PriceType,
            Duration: video.Duration
            // EntryID: PlayerDetail.EntryId
        };

        var object = {
            Data: { "download": Download }
        };

        //console.log(Download);

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/DownloadAttachment',//DownloadLink',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            var videodetail = data.ResultObject;

                            window.location.href = videodetail;
                        }
                        else {
                        }
                    }
                }
                else {
                }
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    //NN
    GetSpeakerDetail: function (currentRouteSetting, routeProvider, routeCurrentContext, speakerid) {
        var _this = this;
        if (CurrentVideoDetail.Speakers != null) {
            $.each(CurrentVideoDetail.Speakers, function (index, speaker) {
                if (speaker.Id == speakerid) {
                    var SpeakerImage = '';
                    if (speaker.PictureUrl.indexOf("$") != -1) {
                        SpeakerImage = speaker.PictureUrl.slice(0, speaker.PictureUrl.lastIndexOf("$"));
                    }
                    else
                        SpeakerImage = CurrentVideoDetail.SpeakerImageSource + speaker.PictureUrl;

                    $('#speaker_image').attr("src", SpeakerImage);
                    $('#spkr_name').text(speaker.FirstName + " " + speaker.LastName);
                    $('#spkr_jobtitle').text(speaker.JobTitle);
                    $('#spkr_company_name').text(speaker.Organization);
                    $('#spkr_affiliations').text(speaker.Affiliation);
                    $('#spkr_biography').html(speaker.Biography)
                    $("#viewBioPrompt").modal({
                        backdrop: 'static',
                        keyboard: false
                    });
                    $("#viewBioPrompt").modal('show');
                    return false;
                }
            });
        }
    },

    getPlayerDetails: function (videoFilter) {
        var _this = this;

        var object = {
            Data: { "videoFilter": videoFilter }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetCurrentVideoDetail',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //no data
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            if (data.ResultObject.HasUserAccess == true) {
                                var videoDetail = data.ResultObject;
                                var time = new Date();
                                this.CurrentVideoDetail = {
                                    VideoId: videoFilter.VideoId,
                                    ChannelId: videoDetail.ChannelId,
                                    Title: videoDetail.VideoTitle,
                                    Description: videoDetail.ShortDescription,
                                    Abstract: videoDetail.Abstract,
                                    DisplayImage: videoDetail.DisplayImage + "?" + time.getTime(),
                                    ChannelName: videoDetail.ChannelName,
                                    //EntryId: videoDetail.StreamUKId,
                                    EncodedAssetID: videoDetail.EncodedAssetID,
                                    SmoothStreamingURL: videoDetail.SmoothStreamingURL,
                                    ShowOnPortal: videoDetail.ShowOnPortal,
                                    DefaultChannel: videoDetail.channelName,
                                    Permissions: videoDetail.PermissionDetail,
                                    Attachment: videoDetail.Attachment,
                                    ChannelList: videoDetail.ChannelList,//current video detail
                                    Speakers: videoDetail.Speaker,
                                    SpeakerImageSource: videoDetail.SpeakerImageSource,
                                    Keywordlist: videoDetail.Keywordlist,
                                    HasLock: videoDetail.HasLock,
                                    HasPromo: videoDetail.HasPromo,
                                    PromoType: videoDetail.PromoType,
                                    HasUserAccess: videoDetail.HasUserAccess,
                                    ViewsCount: videoDetail.ViewsCount,
                                    LikesCount: videoDetail.LikesCount,
                                    DisLikesCount: videoDetail.DisLikesCount,
                                    Duration: videoDetail.Duration,
                                    PremiumPrice: videoDetail.PremiumPrice,
                                    Comments: videoDetail.Comments,
                                    PriceType: videoDetail.PriceType,
                                    Duration: videoDetail.Duration,
                                    SubscriptionType: videoDetail.SubscriptionType
                                };

                                //var KPlayerDetails = data.ResultObject.KalturaPlayerDetail;

                                //player logic
                                //this.PlayerDetail = {
                                //    PartnerId: KPlayerDetails.PartnerId,
                                //    PlayerId: KPlayerDetails.PlayerId,
                                //    CacheStrng: KPlayerDetails.PlayerCacheString,
                                //    EntryId: CurrentVideoDetail.EntryId,
                                //    Ks: KPlayerDetails.PlayerSession
                                //};
                                //console.log(this.PlayerDetail);
                                //console.log(this.CurrentVideoDetail);

                                //_this.AttachScript();
                            }
                            else {
                                //promo details logic
                                //counter liogic
                            }
                        }
                    }
                }
                else {
                }
            }, function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(videoFilter));
    },

    getRelatedVideos: function (currentRouteSetting, routeProvider, routeCurrentContext) {
        played = 0;
        Repository.LoadDataWithGet(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetVideoVideoModel',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    //Bind all subscriptions to view.
                    if (data.ResultObject == null) {
                        $('#NoRecordFound').html(data.Message);
                        $('#Table_Video').hide();
                    }
                    else {
                        if (data.ResultObject.length != 0) {
                            /*Carousel Logic start */
                            var relatedVideosHTML = '';

                            var count = 0;

                            $.each(data.ResultObject.Popularlist, function (index, data) {
                                relatedVideosHTML += getRelatedSeriesVideoHTML(data.ImageUrl, data.VideoUrl, data.ChannelName, data.VideoTitle, data.SubscriptionType, data.Duration, data.IsSeries, data.SeriesCount, data.SeriesCreatedYear);
                            });

                            $(document).ready($('#related-videos').html(relatedVideosHTML));
                            //RenderPlayer();
                        }
                        else {
                            $('#VideoTable').html("No records found.");
                        }
                        $('#NoRecordFound').hide();
                    }
                }
            }
            ,
            function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            });
    },

    ShowRelatedContent: function (RelatedContentData) {
        $("#dynamicRelatedContentMain").html("");
        if (RelatedContentData != null && RelatedContentData.RelatedContentRecord != null) {
            if (RelatedContentData.RelatedContentRecord.length == 0) {
                $("#related-content").hide();
            }
            var i = 0;
            $.each(RelatedContentData.RelatedContentRecord, function (index, data) {
                i += 1;
                var ImageType = data.Type == "Book" ? 'Images/book.png' : 'Images/journal.png';
                var strDiv = '<div class="col-lg-12 col-md-12 col-xs-12 col-sm-12 related-content-record-container">';
                strDiv += '<a href="' + data.DOI + '" target="_blank"><div class="related-content-icon" style="background-image:url(' + ImageType + ')"></div><a>';
                strDiv += '<div class="related-content-text">';
                strDiv += '<a href="' + data.DOI + '" target="_blank" class="text-color font-bold custom_pointer">' + data.Title + '</a>';
                strDiv += ' <div>' + data.Type + '</div>';
                strDiv += ' </div>';
                strDiv += ' </div>';

                if (i <= 4) {
                    $("#dynamicRelatedContentMain").append(strDiv);
                }
            });
        }
    },

    //step 1
    RenderSeriesVideoPanel: function (renderPlayer) {
        var _this = this;
        if (renderPlayer) {
            $(".video-thumbnail-toggle-background").toggleClass("display-none");
            $("#player").removeClass('hidden');
            /// Author: Sanjana
            /// Date:02-07-2017
            /// Decription:highlight divs
            $('.myclips').removeClass('disabledbutton');
            $('.share-img-icon').removeClass('disabledbutton');
            $("#transcript-img").removeClass('selectedIcon');
            $(".myclips").removeClass('selectedIcon');
            $(".share-img-icon").removeClass('selectedIcon');
            //End
        }
        else {
            $(".video-thumbnail-toggle-background").toggleClass("display-none");
            $("#player").removeClass('hidden');
        }
    },

    //step2
    CheckLock: function (hasLock) {
        var _this = this;

        if (hasLock == true) {
            //   _this.HideDownload(true);
            //_this.HideVideo(true);
            $("#playBtn").css("display", "none");
            $("#lockBtn").css("display", "block");
        }
        else {
            $("#playBtn").css("display", "block");
            $("#lockBtn").css("display", "none");
            //_this.HideVideo(false);
        }
    }, AllowDownload: function (allowDownload) {
        var _this = this;

        if (allowDownload == false) {
            $('.download-video-button').attr('disabled', true);
            $('.download-btn-div').attr('disabled', true);
            $('.download-video-button').css('pointer-events', 'none');
        }
        else {
            $('.download-video-button').attr('disabled', false);
            $('.download-video-button').css('pointer-events', '');
            $('.download-btn-div').attr('disabled', false);
        }
    },
    CanLikeDislike1: function (canLikeDislike) {
        if (canLikeDislike == true) {
            $(".like-unlike-pannel").attr('disabled', false);
            $(".view-block").attr('disabled', false);
            $(".like").attr('disabled', false);
            $(".unlike").attr('disabled', false);
            $(".glyphicon-thumbs-down").css('pointer-events', '');
            $(".glyphicon-thumbs-up").css('pointer-events', '');
            $("#likevalue").html(CurrentVideoDetail.LikesCount);
            $("#dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            $("#mobile-likevalue").html(CurrentVideoDetail.LikesCount);
            $("#mobile-dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            if (CurrentVideoDetail.ViewsCount <= 1) {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Play");
            }
            else {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Plays");
            }
        }
        else {
            $(".like-unlike-pannel").attr('disabled', true);
            $(".view-block").attr('disabled', true);
            $(".like").attr('disabled', true);
            $(".unlike").attr('disabled', true);
            $('.button_style_none').attr('disabled', true);
            $(".glyphicon-thumbs-down").css('pointer-events', 'none');
            $(".glyphicon-thumbs-up").css('pointer-events', 'none');
            $("#likevalue").html(CurrentVideoDetail.LikesCount);
            $("#dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            $("#mobile-likevalue").html(CurrentVideoDetail.LikesCount);
            $("#mobile-dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            if (CurrentVideoDetail.ViewsCount <= 1) {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Play");
            }
            else {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Plays");
            }
        }
    },

    CanPlay: function () {
        var _this = this;
        var canPlay = false;
        if (CurrentVideoDetail.HasLock == true || (CurrentVideoDetail.HasPromo == true && CurrentVideoDetail.PromoType != "video") || CurrentVideoDetail.ShowOnPortal == false) {
            canPlay = false;
        }
        else {
            canPlay = true;
        }
        return canPlay;
    },

    CanLikeDislike: function () {
        var _this = this;
        var canLike = false;
        if (CurrentVideoDetail.HasLock == true || CurrentVideoDetail.HasPromo == true || CurrentVideoDetail.ShowOnPortal == false) {
            canLike = false;
        }
        else {
            canLike = true;
        }
        return canLike;
    },

    RenderAttachment: function (allowed) {
        var _this = this;
        var attachmenthtml = '';
        if (allowed == false) {
            return;
        }
        else if (allowed == true) {
            if (CurrentVideoDetail.Attachment != null) {
                //$('#video-content').removeClass('col-md-12 col-sm-12').addClass('col-md-7 col-sm-7');
                $('#video-attachment').removeClass('display-none');
                $.each(CurrentVideoDetail.Attachment, function (index, data) {
                    if (data.IsActive) {
                        attachmenthtml += '<div class="download_docs">' +
                            '<img src="' + GetAttachmentImage(data.AttachmentType) + '" />' +
                            '<span><a class="text-color font-bold" id="DownloadAttachment" data-innerroutename="DownloadAttachment" target="_blank"   fileurl="' + data.AttachmentFileNameWithPath + '">' + data.AttachmentFileName + '</a></span>' +
                            '</div>';
                    }
                });

                $(".download_section").html(attachmenthtml);
            }
        }
    },

    RenderAttachment: function (allowed) {
        var _this = this;
        var attachmenthtml = '';
        if (CurrentVideoDetail.Attachment != null) {
            $.each(CurrentVideoDetail.Attachment, function (index, data) {
                if (data.IsActive) {
                    var classMoreAttachments = "";
                    var str = '';
                    if (index > 2) {
                        classMoreAttachments = "more-attachments display-none"
                    }
                    if (allowed == false) {
                        str = '<span  class="text-color font-bold" id="DownloadAttachment" > ' + data.AttachmentFileName + '</span>';
                    }
                    else {
                        str = '<span><a class="text-color font-bold" id="DownloadAttachment" data-innerroutename="DownloadAttachment" target="_blank" style="cursor: pointer;"  fileurl="' + data.AttachmentFileNameWithPath + '">' + data.AttachmentFileName + '</a></span>'
                    }
                    attachmenthtml += '<div class="download_docs ' + classMoreAttachments + '"><img src="' + GetAttachmentImage(data.AttachmentType) + '" />' + str + '</div>';
                }
            });
        }
        $(".download_section").html(attachmenthtml);
        if (attachmenthtml != "") {
            //$('#video-content').removeClass('col-md-12 col-sm-12').addClass('col-md-7 col-sm-7');
            $('#video-attachment').removeClass('display-none');
        }
    },

    RenderTranscript: function (allowed) {
        var _this = this;
        var transcripthtml = '';

        if (CurrentVideoDetail.TranscriptList != null) {
            $.each(CurrentVideoDetail.TranscriptList, function (index, data) {
                var classMoreTranscripts = "";
                //var str = '';
                //var filename = '';
                //var ext = '';
                if (index > 2) {
                    classMoreTranscripts = "more-transcripts display-none"
                }
                //if (data.Text != '') {
                //    ext = data.FileName.split('.')[1];
                //    filename = data.Text + '.' + ext;
                //}
                //else {
                //    filename = data.FileName;
                //}
                if (allowed == false) {
                    str = '<span  class="text-color font-bold" id="DownloadTranscript" > ' + data.FileName + '</span>';
                }
                else {
                    str = '<span><a class="text-color font-bold" id="DownloadTranscript" data-innerroutename="DownloadAttachment" style="cursor: pointer;" target="_blank"  fileurl="' + data.FilePath + '">' + data.FileName + '</a></span>';
                }
                transcripthtml += '<div class="download_docs ' + classMoreTranscripts + '"><img src="' + GetAttachmentImage(data.AttachmentType) + '" />' + str + '</div>';
            });
        }
        $(".transcript_section").html(transcripthtml);
        if (transcripthtml != "") {
            //$('#video-content').removeClass('col-md-12 col-sm-12').addClass('col-md-7 col-sm-7');
            $('#transcript-attachment').removeClass('display-none');
        }
    },

    RenderIETDigitalLibrary: function (digitalLibraryUrl) {
        var digitalLibraryHtml = '';
        var urltitle = '';
        if (digitalLibraryUrl != "") {
            urltitle = '<span class="text-color font-bold">' + digitalLibraryUrl + '</span>'
            digitalLibraryHtml += '<div class="download_docs"><img src="' + GetAttachmentImage("digitallibrary") + '" /><a target="_blank" class="custom_pointer" href="' + digitalLibraryUrl + '">' + urltitle + '</a>';
        }
        $('.digital-library-container').html(digitalLibraryHtml);
        if (digitalLibraryHtml != "") {
            //$('#video-content').removeClass('col-md-12 col-sm-12').addClass('col-md-7 col-sm-7');
            $('#IET-digital-library').removeClass('display-none');
        }
    },

    //step3
    HideVideo: function (defaultHide) {
        var _this = this;
        var hide = true;
        if (_this.CanPlay() == false) {
            hide = true;
        }
        else if (defaultHide == false) {
            var value = _this.HasPermission("HideRecord");
            if (value == false) {
                hide = false;
            }
        }
        if (hide == true) {
            //_this.RenderVideoPanel(false);
            _this.HideDownload(true);
            _this.HideLikeDislike(true);
        }
        else {
            //_this.RenderVideoPanel(true);
            _this.HideDownload(false);
            _this.HideLikeDislike(false);
        }
    },

    HideDownload: function (defaultHide) {
        var _this = this;
        var hide = true;

        if (defaultHide == false) {
            if (_this.CanLikeDislike() == false) {
                hide = true;
            }
            else {
                var value = this.HasPermission("AllowDownload");
                if (value == false) {
                    hide = false;
                }
                else {
                    hide = true;
                }
            }
        }

        if (hide == true) {
            $('.download-video-button').attr('disabled', true);
            $('.download-btn-div').attr('disabled', true);
            $('.download-video-button').css('pointer-events', 'none');
        }
        else {
            $('.download-video-button').attr('disabled', false);
            $('.download-video-button').css('pointer-events', '');
            $('.download-btn-div').attr('disabled', false);
        }
    },

    HideLikeDislike: function (defaultHide) {
        var _this = this;
        var hide = true;
        if (defaultHide == false) {
            if (_this.CanLikeDislike() == false) {
                hide = true;
            }
            else
                var value = this.HasPermission("ShowRating");
            if (value == false) {
                hide = false;
            }
            else {
                hide = true;
            }
        }
        if (hide == false) {
            $(".like-unlike-pannel").attr('disabled', false);
            $(".view-block").attr('disabled', false);
            $(".like").attr('disabled', false);
            $(".unlike").attr('disabled', false);
            $(".glyphicon-thumbs-down").css('pointer-events', '');
            $(".glyphicon-thumbs-up").css('pointer-events', '');
            $("#likevalue").html(CurrentVideoDetail.LikesCount);
            $("#dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            $("#mobile-likevalue").html(CurrentVideoDetail.LikesCount);
            $("#mobile-dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            if (CurrentVideoDetail.ViewsCount <= 1) {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Play");
            }
            else {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Plays");
            }
        }
        else {
            $(".like-unlike-pannel").attr('disabled', true);
            $(".view-block").attr('disabled', true);
            $(".like").attr('disabled', true);
            $(".unlike").attr('disabled', true);
            $(".glyphicon-thumbs-down").css('pointer-events', 'none');
            $(".glyphicon-thumbs-up").css('pointer-events', 'none');
            $("#likevalue").html(CurrentVideoDetail.LikesCount);
            $("#dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            $("#mobile-likevalue").html(CurrentVideoDetail.LikesCount);
            $("#mobile-dislikevalue").html(CurrentVideoDetail.DisLikesCount);
            if (CurrentVideoDetail.ViewsCount <= 1) {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Play");
            }
            else {
                $("#ViewsCount").html(CurrentVideoDetail.ViewsCount + " Plays");
            }
        }
    },

    HasPermission: function (key) {
        var permission = CurrentVideoDetail.Permissions;
        var value = null;
        if (permission != null) {
            $.each(permission, function (k, v) {
                // key == "cars" and value == 27, etc.
                if (v != null) {
                    if (v.PermissionType == key) {
                        value = v.PermissionStatus;
                        //console.log(key + " " + value);
                        return;
                    }
                }
            });
        }
        if (value == null) {
            value = false;
        }

        return value;
    },
    //Stream Code Commented Start 2018/04/11
    //RenderPlayer: function () {
    //    //alert(video.PartnerId);
    //    // var partnerid=video.PartnerId;
    //    var _this = this;
    //    if (_this.CanPlay() == false) {
    //        return;
    //    }

    //    $.getScript(WebService.StreamUrl, function () {
    //        //console.log('file loaded');

    //        _this.RenderSeriesVideoPanel(true);

    //        mw.setConfig('Kaltura.EnableEmbedUiConfJs', true);
    //        mw.setConfig('EmbedPlayer.EnableIpadHTMLControls', true);
    //        mw.setConfig('Kaltura.ForceFlashOnDesktop', false);

    //        var video = CurrentVideoDetail;
    //        var player = PlayerDetail;
    //        //console.log(video);
    //        //console.log(player);

    //        var kWidgetEmbedSettings = {
    //            'targetId': 'player',
    //            'wid': player.PartnerId,
    //            'uiconf_id': player.PlayerId,
    //            'flashvars': {
    //                "streamerType": "auto",
    //                'ks': player.Ks,
    //                'autoPlay': true,
    //                'share.plugin': false
    //            },
    //            'params': { // params allows you to set flash embed params such as wmode, allowFullScreen etc
    //                'wmode': 'transparent'
    //            },
    //            'cache_st': player.CacheStrng,
    //            'entry_id': video.EntryId,//'0_8g8u8vq3'//playerDetails.ukstreamId
    //            /// Author: Sanjana
    //            /// Date: 22-08-2017
    //            /// Decription: do seek when user clicks on clip video
    //            'readyCallback': function (playerId) {
    //                var kdp = document.getElementById(playerId);
    //                //Checks Transcript file available or not
    //                debugger;
    //                if (CurrentVideoDetail.IsSubTitleContentAvailable & !CurrentVideoDetail.IsLive & !CurrentVideoDetail.HasLock) {
    //                    IETTVTranscript.Transcript_Highlight_Listener(playerId);
    //                    $("#transcript-img").show();
    //                }
    //                var isClip = false;
    //                var starttime = sessionStorage.getItem("Clip_StartTime");
    //                var endtime = sessionStorage.getItem("Clip_EndTime");
    //                var endSeconds;
    //                var currentSeconds;
    //                if (starttime != null && endtime != null) {
    //                    isClip = true;
    //                    currentSeconds = converttimetoseconds(starttime);
    //                    endSeconds = converttimetoseconds(endtime);
    //                } else {
    //                    starttime = $.url().param('st');
    //                    endtime = $.url().param('et');
    //                    if (starttime != undefined && endtime != undefined) {
    //                        isClip = true;
    //                        currentSeconds = converttimetoseconds(starttime);
    //                        endSeconds = converttimetoseconds(endtime);
    //                    }
    //                }
    //                // Once playing issue seek
    //                var seekDone = false;
    //                kdp.kBind('playerUpdatePlayhead', function (event) {
    //                    if (isClip) {
    //                        if (!seekDone) {
    //                            kdp.sendNotification('doSeek', currentSeconds - 1);
    //                        }
    //                        if (parseInt(event) == endSeconds) {
    //                            kdp.sendNotification('doPause');
    //                        }
    //                        seekDone = true;
    //                    }
    //                });
    //                // Wait for "media ready" before starting playback:
    //                var iOS = /Android|iPad|iPhone|iPod/.test(navigator.userAgent);

    //                if (iOS != true) {
    //                    kdp.kBind('mediaReady', function () {
    //                        kdp.sendNotification('doPlay');
    //                    })
    //                }
    //                ////Add a binding for when seek is completed:
    //                //kdp.kBind('playerSeekEnd', function () {
    //                //    // Pause player after 2 second
    //                //    if (isClip) {
    //                //        setTimeout(function () {
    //                //            kdp.sendNotification('doPause');
    //                //        }, 1000)
    //                //    }
    //                //});
    //            }
    //            //End
    //        }
    //        kWidget.embed(kWidgetEmbedSettings);
    //    });

    //},
    //AttachScript: function () {
    //    $.getScript('http://open.http.mmp.streamuk.com/html5/html5lib/v2.0.RC3/mwEmbedLoader.php/p/2000439', function () {
    //        //console.log('file loaded');

    //        mw.setConfig('Kaltura.EnableEmbedUiConfJs', true);
    //        mw.setConfig('EmbedPlayer.EnableIpadHTMLControls', true);
    //        mw.setConfig('Kaltura.ForceFlashOnDesktop', false);

    //        var video = CurrentVideoDetail;
    //        var player = PlayerDetail;
    //        //console.log(video);
    //        //console.log(player);

    //        var kWidgetEmbedSettings = {
    //            'targetId': 'player',
    //            'wid': player.PartnerId,
    //            'uiconf_id': player.PlayerId,
    //            'flashvars': {
    //                "streamerType": "auto",
    //                'ks': player.Ks,
    //                'autoPlay': true,
    //                'share.plugin': false
    //            },
    //            'cache_st': player.CacheStrng,
    //            'entry_id': video.EntryId//'0_8g8u8vq3'//playerDetails.ukstreamId

    //        }
    //        kWidget.embed(kWidgetEmbedSettings);
    //    });
    //},
    //Stream Code Commented End 2018/04/11
    RenderPlayer: function () {
        //alert(video.PartnerId);
        // var partnerid=video.PartnerId;
        var _this = this;
        if (_this.CanPlay() == false) {
            return;
        }
        $("#player").show();

        _this.RenderSeriesVideoPanel(true);

        var video = CurrentVideoDetail;
        //var player = PlayerDetail;
        var isClip = false;
        var starttime;
        var endtime;
        var endSeconds;
        var myOptions = {
            //Need to be relooked
            techOrder: ["azureHtml5JS", "flashSS", "html5FairPlayHLS", "silverlightSS", "html5"],
            "nativeControlsForTouch": false,
            controls: true,
            autoplay: true,
            width: "100%",
            height: "100%",
            "logo": { "enabled": false },
            plugins: {
                ga: {
                    //'eventLabel' : 'EventLabelForTracking', //default is URL source
                    'debug': false, //default is false
                    'eventsToTrack': ['playerConfig', 'loaded', 'playTime', 'percentsPlayed', 'start', 'error', 'buffering', 'bitrate'], // default is ['playerConfig', 'loaded', 'playTime', 'percentsPlayed', 'start', 'end', 'play', 'pause', 'error', 'buffering', 'fullscreen', 'seek', 'bitrate']
                    'percentsPlayedInterval': 20 //default is 20
                }
            }
        }
        myPlayer = null;
        myPlayer = amp("azuremediaplayer", myOptions, function () {
            //'this' refers to the player instance in the ready function
            if (CurrentVideoDetail.IsSubTitleContentAvailable & !CurrentVideoDetail.IsLive & !CurrentVideoDetail.HasLock) {
                IETTVTranscript.Transcript_Highlight_Listener("azuremediaplayer");
                //$("#transcript-img").show();
                $('.transcript-icon').removeClass('hidden');
            }
            starttime = sessionStorage.getItem("Clip_StartTime");
            endtime = sessionStorage.getItem("Clip_EndTime");
            var currentSeconds;
            if (starttime != null && endtime != null) {
                isClip = true;
                currentSeconds = converttimetoseconds(starttime);
                endSeconds = converttimetoseconds(endtime);
            }
            else {
                starttime = $.url().param('st');
                endtime = $.url().param('et');
                if (starttime != undefined && endtime != undefined) {
                    isClip = true;
                    currentSeconds = converttimetoseconds(starttime);
                    endSeconds = converttimetoseconds(endtime);
                }
            }
            //if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(navigator.userAgent)) {
            if (/Android/i.test(navigator.userAgent)) {
                myPlayer.play();
            }
        });
        myPlayer.addEventListener(amp.eventName.play, function () {
            playerSeriesPlayedHandler();
        });
        myPlayer.addEventListener(amp.eventName.ended, function () {
            playerSeriesStoppedHandler();
        });
        //allows to display english subtitles when replaying video
        myPlayer.addEventListener(amp.eventName.loadeddata, function () {
            _this.setTrack("en", "subtitles");
        });

        var seekDone = false;
        myPlayer.addEventListener(amp.eventName.playing, function () {
            if (isClip == true) {
                if (!seekDone) {
                    myPlayer.currentTime(clipStartTime);
                    seekDone = true;
                }
            }
        });

        myPlayer.addEventListener(amp.eventName.timeupdate, function () {
            if (Math.floor(myPlayer.currentTime()) == endSeconds) {
                var duration = myPlayer.duration().toString().split('.')[1];
                var currentTime = endSeconds + "." + duration;
                if (myPlayer.duration().toString() != currentTime) {
                    myPlayer.pause();
                    myPlayer.currentTime(endSeconds + 1);
                }
            }
        });
        var subtitleObject = [];
        $.each(CurrentVideoDetail.lstSrtSubTitles, function (index, value) {
            var time = new Date();
            if (value != '' && value != null) {
                subtitleObject.push({
                    "src": $.url().data.attr.source.split('?')[0] + value.SubtitlePath + "?" + time.getTime(),
                    "srclang": value.LanguageAbbreviation,
                    "label": value.Language,
                    "kind": "subtitles",
                    "default": value.Language == "English" ? true : false
                })
            }
        });
        myPlayer.src([
            {
                "src": CurrentVideoDetail.SmoothStreamingURL,
                "type": "application/vnd.ms-sstr+xml"
            }
        ],
            subtitleObject)
    },
    setTrack: function (language, kind) {
        for (var i = 0; i < myPlayer.textTracks_.length; i++) {
            if (myPlayer.textTracks_.tracks_[i].language == language && myPlayer.textTracks_.tracks_[i].kind == kind) {
                myPlayer.textTracks_.tracks_[i].mode = "showing";
            }
            if (myPlayer.textTracks_.tracks_[i].kind == "captions") {
                myPlayer.textTracks_.tracks_[i].mode = "disabled";
            }
        }
    },

    SetCountDown: function (date) {
        var _this = this;

        var newYear = new Date();
        newYear = new Date(newYear.getFullYear() + 1, 1 - 1, 1);
        $('#countdownTimer').countdown({ until: newYear });
    },

    VideoViewActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        //if (played >= 1) {
        //    return;
        //}
        //played++;
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoViewActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("Activity could not be logged");
                    }
                    else {
                        var like = data.ResultObject.Likes;
                        var dislike = data.ResultObject.DisLikes;
                        var view = data.ResultObject.Views;

                        $("#dislikevalue").text(dislike);
                        $("#likevalue").text(like);
                        $("#mobile-likevalue").text(like);
                        $("#mobile-dislikevalue").text(dislike);
                        if (view <= 1) {
                            $("#ViewsCount").html(view + " Play");
                        }
                        else {
                            $("#ViewsCount").html(view + " Plays");
                        }

                        //console.log("Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    VideoPauseActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoPauseActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("Pause Activity could not be logged");
                    }
                    else {
                        //console.log("Pause Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    VideoPlayActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoPlayActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("Play Activity could not be logged");
                    }
                    else {
                        //console.log("Play Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                MessageViewModel.CreateErrorMessage(data);
                MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    VideoStopActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoStopActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        // console.log("Stop Activity could not be logged");
                    }
                    else {
                        //console.log("Stop Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                MessageViewModel.CreateErrorMessage(data);
                MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    VideoLikeActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        var object = {
            Data: { "videoActivity": jsonData }
        };
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoLikeActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("Like Activity could not be logged");
                    }
                    else {
                        var like = data.ResultObject.Likes;
                        var dislike = data.ResultObject.DisLikes;
                        var view = data.ResultObject.Views;

                        var lastactivity = data.ResultObject.LastActivity;
                        $("#dislikevalue").text(dislike);
                        $("#likevalue").text(like);
                        $("#mobile-likevalue").text(like);
                        $("#mobile-dislikevalue").text(dislike);
                        if (view <= 1) {
                            $("#ViewsCount").html(view + " Play");
                        }
                        else {
                            $("#ViewsCount").html(view + " Plays");
                        }
                        //$("#ViewsCount").text(view + " View");
                        _this.ToggleLikeDislike("Like");

                        //console.log("Like Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },

    VideoDislikeActivity: function (jsonData) {
        var _this = this;
        if (_this.CanLikeDislike() == false) {
            return;
        }
        var object = {
            Data: { "videoActivity": jsonData }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/VideoDislikeActivity',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject == null) {
                        //console.log("DisLike Activity could not be logged");
                    }
                    else {
                        var like = data.ResultObject.Likes;
                        var dislike = data.ResultObject.DisLikes;
                        var view = data.ResultObject.Views;
                        var lastactivity = data.ResultObject.LastActivity;
                        $("#dislikevalue").text(dislike);
                        $("#likevalue").text(like);
                        $("#mobile-likevalue").text(like);
                        $("#mobile-dislikevalue").text(dislike);
                        if (view <= 1) {
                            $("#ViewsCount").html(view + " Play");
                        }
                        else {
                            $("#ViewsCount").html(view + " Plays");
                        }
                        _this.ToggleLikeDislike("Dislike");

                        //console.log("DisLike Activity was logged" + data.ResultObject);
                    }
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
                _this.MessageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data));
    },
    DisposePlayer: function () {
        if (myPlayer) {
            myPlayer.dispose();
        }
    },
    PlayVideo: function () {
        var _this = this;
        toggleSeriesVideoSectionVisibility();
    },

    ToggleLikeDislike: function (lastactivity) {
        var _this = this;
        if (lastactivity != "" || lastactivity != null) {
            if (lastactivity == "Like") {
                // $(".like").attr('disabled', true);
                //  $(".unlike").attr('disabled', false);
                $(".unlike").css('pointer-events', '');
                $(".like").css('pointer-events', 'none');
                $(".glyphicon-thumbs-down").css('pointer-events', '');
                $(".glyphicon-thumbs-up").css('pointer-events', 'none');
            }
            else if (lastactivity == "Dislike") {
                $(".glyphicon-thumbs-down").css('pointer-events', 'none');
                $(".glyphicon-thumbs-up").css('pointer-events', '');
                // $(".like").attr('disabled', false);
                ///$(".unlike").attr('disabled', true);
                $(".unlike").css('pointer-events', 'none');
                $(".like").css('pointer-events', '');
            }
        }
    },

    GetVideoIdByVideoNumber: function (videoFilter, routeCurrentContext) {
        var object = {
            Data: { "videoFilter": videoFilter }
        };
        Repository.LoadDataJSONFalseAjax(WebService.BaseURL + 'SeriesManagement/SeriesService.svc/GetVideoIdByVideoNumber',
            function (data, status, headers, config) {

                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    routeCurrentContext.attr("data-videoId", data.ResultObject.VideoId);
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
            }, JSON.stringify(object.Data));
    },

    GetSeriesFromVideoId: function (videoNumber, routeCurrentContext) {
        var object = {
            Data: { "videoId": videoNumber }
        };
        Repository.LoadDataJSONFalseAjax(WebService.BaseURL + 'SeriesManagement/SeriesService.svc/GetSeriesIdByVideoId',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    routeCurrentContext.attr("data-seriesId", data.ResultObject.SeriesId);
                }
            },
            function (data, status, headers, config) {
                _this.MessageViewModel.CreateErrorMessage(data);
            }, JSON.stringify(object.Data));
    }
};

function getRelatedSeriesVideoHTML(videoid, videoNo, channelName, videoTitle, videoimage, hasLock, channelId, SubscriptionType, Duration, IsSeries, seriesCount, seriesCreatedYear) {
    var accessbtn = '';

    if (channelId == null) {
        channelId = '';
    }
    if (channelName == null) {
        channelName = '';
    }
    var videoroute = '';
    var channelroute = '';
    //var channelHTMLCode = '';

    if (hasLock == false) {
        accessbtn = 'play.png';
    }
    else {
        accessbtn = 'lock.png';
    }

    var seriesOverlayData = "";
    if (videoid != "" && IsSeries == false) {
        videoroute = 'data-innerroutename=\"videoid\" data-videono=\"' + videoNo + '\" data-ChannelId=\"' + channelId + '\"  data-hasindex="true" data-videoId=\'' + videoid + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        channelroute = 'data-innerroutename="Channel" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\'';
        //  channelHTMLCode = '<div class=thumbnail-channel ' + channelroute + ' ><span>' + channelName + '</span></div>'
    }
    else if (IsSeries == true) {
        //var OrgVideoTitle = videoTitle;
        //videoTitle = videoTitle + " (" + seriesCreatedYear + ")";
        videoroute = 'data-innerroutename=\"series\" data-videono=\"' + videoNo + '\" data-ChannelId=\"' + channelId + '\"  data-hasindex="true" data-videoId=\'0\'  data-seriesid=\'' + videoid + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        seriesOverlayData = '<div class="series_overlay_content"> <div class="series_overlay_count">' + seriesCount + '</div> <div class="series_overlay_video_text">Videos</div> </div>';
        channelName = seriesCreatedYear;
        channelroute = 'style="cursor: default;"';
    }
    //else {
    //    videoroute = 'data-innerroutename=\"video\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\'';
    //    channelroute = 'data-innerroutename="Channel" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\'';
    //}

    //var addtionaVideoHTML = '<div class="twoColumnClearLeft col-md-6 col-xs-6 related-video-padding-alignment bottom-margin-15">' +
    var addtionaVideoHTML = '<div class="col-md-2 col-xs-6 related-videos_new">' +
        '<div class="bottom-margin-10 related-video-image-background">' +
        '<div class="thumbnail-background thumbnail-desktop-list border1px" ' + videoroute + ' style="background-image:url(\'' + videoimage + '\')">' +
        '<img class="playBtn-small playBtn-small-btn-content" src="Images/' + accessbtn + '">' +
        '</div>' +
        seriesOverlayData +
        '</div>' +
        '<div class="col-md-11 no-padding">' +
        '<span>' +
        '<div class="list-caption" ' + videoroute + ' title=\'' + videoTitle + '\'>' +
        truncateString(videoTitle, 15) +
        '</div>' +
        '</span>' +
        '</div>' +
        '<div class="col-md-11 no-padding">' +
        '<div class="list-channel" ' + channelroute + '>' +
        channelName +
        '</div>' +
        '</div>' +
        '</div>';

    return addtionaVideoHTML;
}

function SpeakerHTML(position, title, fname, lname, image) {
    var speakersectionhtml = "<div class='item active'>" +
        "<div class='col-md-6 no-padding col-sm-12 col-xs-12 user-block'>" +
        "<div class='thumbnail float-left margin-right-5'>" +
        "<img src='" + image + "' width='50' height='50' class='img-border'/>" +
        "</div>" +
        "<div class='padding-top-5 spkr-info padding-right-20'>" +
        "<div class='no-padding spkr-carousel'>" +
        "<span class='spkr-fname'>" + title + " </span><span class='spkr-fname word-wrap'>" + fname + " </span><span class='spkr-lname word-wrap'>" + lname + "</span>" +
        //"<span class='spkr-fname'>Noshank </span><span class='spkr-lname'>hgktlpanmgjtkloa</span>" +
        "</div>" +
        "<div class='spkr-bio'>" +
        "<a  class=\"text-color custom_pointer\" onClick=\"getSpeakerDetails(" + position + ", \'" + name + "\')\"> View Bio</a>" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</div>";

    return speakersectionhtml;
}

function KeywordHTML(keywordname, keywordId) {
    var keywordHtml = ' <button  data-innerroutename=\'searchResult\' data-hasIndex="true" class="btn badge badge-right-margin" id="keywordid_' + keywordId + '">' + keywordname + '</button>'
    return keywordHtml;
}

function ChannelHTML(channelName, channelId, channelIconImage) {
    var channelhtml = "";
    if (channelIconImage.toLowerCase().indexOf("default") > 0 || channelIconImage == "") {
        channelhtml = '<div class="float-left" style="margin-top: 4px;">' +
            '<a  class="custom_pointer" data-innerroutename="Channel"  data-channelId=\'' + channelId + '\' data-name=\'' + channelName + '\' data-hasindex="true">' +
            '<span class="right-margin-10 font-bold">' + channelName + ' </span>' +
            '</a></div>';
    }
    else {
        channelhtml = '<div class="float-left no-padding">' +
            '<a  class="custom_pointer" data-innerroutename="Channel"  data-channelId=\'' + channelId + '\' data-name=\'' + channelName + '\' data-hasindex="true">' +
            '<img src="' + channelIconImage + '" class="channel-img-bottom-padding" height="25px" width="25px"><span class="right-margin-10 font-bold">' + channelName + ' </span>' +
            '</a></div>';
    }

    return channelhtml;
}

function getSpeakerDetails(position, name) {
    var _this = this;
    if (CurrentVideoDetail.Speakers != null) {
        $.each(CurrentVideoDetail.Speakers, function (index, speaker) {
            if (index == position) {
                var SpeakerImage = '';
                if (speaker.PictureUrl.indexOf("$") != -1) {
                    SpeakerImage = speaker.PictureUrl.slice(0, speaker.PictureUrl.lastIndexOf("$"));
                }
                else {
                    SpeakerImage = CurrentVideoDetail.SpeakerImageSource + speaker.PictureUrl;
                }

                $('#speaker_image').attr("src", SpeakerImage);
                if (speaker.Title != '') {
                    $('#spkr_name').text(speaker.Title + " " + speaker.FirstName + " " + speaker.LastName);
                } else {
                    $('#spkr_name').text(speaker.FirstName + " " + speaker.LastName);
                }
                $('#spkr_jobtitle').text(speaker.JobTitle);
                $('#spkr_company_name').text(speaker.Organization);
                $('#spkr_affiliations').text(speaker.Affiliation);
                $('#spkr_biography').html(speaker.Biography)
                $("#viewBioPrompt").modal({
                    backdrop: 'static',
                    keyboard: false
                });
                $("#viewBioPrompt").modal('show');
                return false;
            }
        });
    }
}

//function postComments() {
//    var videoId = sessionStorage.getItem("VideoId");
//    var comment = $("#comment").val();
//    if (comment == "") {
//        var messageViewModel = new MessageViewModel();
//        messageViewModel.CreateInfoMessage("Please define the comment.", "overlayId", "okButtonId")
//        messageViewModel.ShowOverLay();
//        $('.overlay').addClass('display-block');
//        return false;
//    }

//    var data = {
//        VideoID: videoId,
//        LogonId: BrowserStorage.getLogonId(),
//        Comment: comment
//    };
//    $('#commentsubmit').attr('disabled', true);
//    var resposne = '';
//    var accessCodeUserName = '';
//    var commenttext = data.Comment.replace(/(['])/g, "''");
//    //var commenttext =data.Comment.replace(/'/g,/''/);
//    var accessCodeType = sessionStorage.getItem("accessCodeType");
//    if (accessCodeType == "2") {
//        accessCodeUserName = localStorage.getItem("Welcome");
//    }
//    else {
//        accessCodeUserName = sessionStorage.getItem("delegateName");
//    }
//    var req = {
//        LogonId: data.LogonId,
//        CommentText: data.Comment,
//        VedioId: data.VideoID,
//        AccessCode: sessionStorage.getItem("accessCode"),
//        AccessCodeType: sessionStorage.getItem("accessCodeType"),
//        AccessCodeUserName: accessCodeUserName
//    };
//    var object = {
//        Data: { "req": req }
//    };

//    Repository.LoadDataJSON(WebService.BaseURL + 'CommentsManagment/CommentsManagment.svc/PostVerifiedComment',
//    function (data, status, headers, config) {
//        if (ResultStatus.Successful == data.Status) {
//            var commentDetails = data.ResultObject;
//            VideoRepository.RenderComments(commentDetails, CommentsEnable);
//            $("#comment").val('');
//        }
//        else {
//            var messageViewModel = new MessageViewModel();
//            messageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId")
//            messageViewModel.ShowOverLay();
//            $("#comment").blur();
//            //alert(data.Message);
//            //alert("Error");
//        }
//        $('#commentsubmit').attr('disabled', false);
//    },
//    function (data, status, headers, config) {
//        var messageViewModel = new MessageViewModel();
//        messageViewModel.CreateInfoMessage(data.Message, "overlayId", "okButtonId")
//        messageViewModel.ShowOverLay();
//        //alert('error');
//        $('#commentsubmit').attr('disabled', false);
//    },
//    JSON.stringify(object.Data));

//}

function GetAttachmentImage(fileType) {

    var imageFile = '';
    if (fileType == "PPT") {
        imageFile = 'Images/temp/pp.png';
    }
    else if (fileType == "Pdf") {
        imageFile = 'Images/temp/pdf.png';
    }
    else if (fileType == "Word") {
        imageFile = 'Images/temp/msword.png';
    }
    else if (fileType == "Excel") {
        imageFile = 'Images/temp/pp2.png';
    }
    else {
        imageFile = 'Images/temp/Document icon_orange.png';
    }

    return imageFile;
}

//var jsCallbackReady = function () {
//    myPlayer = document.getElementById('player');
//    //myPlayer.addJsListener("playerUpdatePlayhead", "playerUpdatePlayheadHandler");
//    myPlayer.addJsListener("playerPlayed", "playerVideoPlayedHandler");
//    myPlayer.addJsListener("playerPlayEnd", "playerVideoStoppedHandler");
//    //myPlayer.addJsListener("playerPaused", "playerVideoPausedHandler");

//    //myPlayer.addJsListener("adStart", "adStartHandler");
//    //myPlayer.addJsListener("adClick", "adClickHandler");
//    //myPlayer.addJsListener("adEnd", "adEndHandler");

//};

//var playerVideoPausedHandler = function (playerid) {
//    disableSpinner = true;
//    var video = CurrentVideoDetail;
//    var data =
//    {
//        Action: "Pause",
//        VideoID: video.VideoId,
//        VideoTitle: video.Title,
//        ActionTime: GetCurrentDate(),
//        LogonId: BrowserStorage.getLogonId(),
//        IpAddress: "",
//        UserName: "",
//        Duration: video.Duration

//    };
//    SeriesRepository.VideoPauseActivity(data);
//};

function playerSeriesStoppedHandler() {
    myPlayer.exitFullscreen();
    disableSpinner = true;
    $("#player").addClass('hidden');
    $(".video-thumbnail-toggle-background").removeClass("display-none");

    $('.share-img-icon').addClass('disabledbutton');
    $('.myclips').addClass('disabledbutton');
    $('.share-img-icon').removeClass('selectedIcon');
    $('.myclips').removeClass('selectedIcon');
    played = 0;
    //console.log('stop');
    var video = CurrentVideoDetail;
    var data =
    {
        Action: "Stop",
        VideoID: video.VideoId,
        VideoTitle: video.Title,
        ActionTime: GetCurrentDate(),
        LogonId: BrowserStorage.getLogonId(),
        IpAddress: "",
        UserName: "",
        Duration: video.Duration
    };
    SeriesRepository.VideoStopActivity(data);
};

function playerSeriesPlayedHandler() {
    disableSpinner = true;
    var video = CurrentVideoDetail;
    var data =
    {
        Action: "Play",
        VideoID: video.VideoId,
        VideoTitle: video.Title,
        ChannelId: video.ChannelId,
        ActionTime: GetCurrentDate(),
        LogonId: BrowserStorage.getLogonId(),
        IpAddress: "",
        UserName: "",
        Duration: video.Duration
    };
    SeriesRepository.VideoPlayActivity(data);
};

function toggleSeriesVideoSectionVisibility() {
    //$(".video-thumbnail-toggle-background").toggleClass("display-none");
    //$("#player").removeClass('hidden');
    SeriesRepository.RenderPlayer();
}

function toogleReadMoreLess() {
    var moretext = "Show more";
    var lesstext = "Show less";
    if ($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
    } else {
        $(this).addClass("less");
        $(this).html(lesstext);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
}

function AddReadMore(text) {
    var showChar = 300; // How many characters are shown by default
    var ellipsestext = "...";
    var moretext = "Show more >";
    var lesstext = "Show less";
    var content = text;

    if (content.length > showChar) {
        var c = content.substr(0, showChar);
        var h = content.substr(showChar, content.length - showChar);

        var html = c + '<span class="moreellipses">' + ellipsestext + '&nbsp;</span><span class="morecontent"><span>' + h + '</span><a href="" class="morelink">' + moretext + '</a></span>';

        return html;
    }
    else {
        return text;
    }
}

function GetCurrentDate() {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    //var hour = today.getHour();
    //var minute = today.getMinutes();
    //var seconds = today.getSeconds();

    if (dd < 10) {
        dd = '0' + dd
    }

    if (mm < 10) {
        mm = '0' + mm
    }

    today = mm + '/' + dd + '/' + yyyy;// + ' ' + hour + ":" + minute + ":" + seconds;

    return today;
}

//function to display premium video text
function getDivHeight(premium_text_height) {
    return premium_text_height / 2;
}

function RenderScript() {
    SpeakerRenderScript();
    /*To toggle view of video description area*/ /*located in commonScripts.js*/
    //VideoViewMoreScript();
    /*located in commonScripts.js*/
    windowResizeactions();
}

function SpeakerRenderScript() {
    var run = true;
    isMobile = checkIsMobile();
    /*Calling checkIsMobile in window resize*/

    /*This function is used to check window size if window  size is less than 992 we are considering it as mobile*/
    function checkIsMobile() {
        if ($(window).width() < 992) {
            returnValue = 1;
        } else {
            returnValue = 0;
        }
        return returnValue;
    }

    var $carouselSpeaker = $("#speaker-carousel .carousel");

    /*by default stop carousel cycle*/
    $carouselSpeaker.carousel('pause');
    // get right & left controls
    var $rightSpeakerControl = $carouselSpeaker.find(".right.carousel-control");
    var $leftSpeakerControl = $carouselSpeaker.find(".left.carousel-control");

    var totContentSpeaker = $('#speaker-carousel .carousel-inner').children('.item').size();
    /*Hiding left and right controll if carousel item is 3 or less*/
    if (totContentSpeaker <= 2) {
        $leftSpeakerControl.css('display', 'none');
        $rightSpeakerControl.css('display', 'none');
    }

    // hide the left control (first slide) on load
    $leftSpeakerControl.hide();

    /* hide and show left and right arrow when carousel slide */
    $carouselSpeaker.on('slid.bs.carousel', function () {
        // get active slide
        var $activeSpeaker = $carouselSpeaker.find(".item.active");

        // if the last slide,

        rightArrowHide();

        // if the first slide,
        if (!$activeSpeaker.prev().length) {
            // hide the left control
            $leftSpeakerControl.css('display', 'none');
            // if not,
        } else {
            // show it
            $leftSpeakerControl.css('display', 'block');
        }
    });

    /*this function is used to show /hide right arrow */
    function rightArrowHide() {
        var showSpeaker;
        if (isMobile == 1) {
            showSpeaker = $carouselSpeaker.find(".item.active").next().length;
        } else {
            showSpeaker = $carouselSpeaker.find(".item.active").next().next().length;
        }
        if (!showSpeaker) {
            // hide the right control
            $rightSpeakerControl.css('display', 'none');
            // if not,
        } else {
            // show the right control
            $rightSpeakerControl.css('display', 'block');
        }
    }
    var flag = 0;
    $('#speaker-carousel .carousel .item').removeClass('active');
    $('#speaker-carousel .carousel .item').each(function () {
        /*Making first item active*/
        if (flag == 0) {
            $(this).addClass('active');
            flag = 1;
        }
    });

    /*This is used to show three images in speaker carousal */
    run = false;
    var multiple = function () {
        /*removeing active class*/
        $('#speaker-carousel .carousel .item').removeClass('active');

        var flagItemActiveFirst = 0;
        $('#speaker-carousel .carousel .item').each(function () {
            /*Making first item active*/
            if (flagItemActiveFirst == 0) {
                $(this).addClass('active');
                flagItemActiveFirst = 1;
            }
            var next = $(this).next();

            if (!next.length) {
                next = $(this).siblings(':first');
            }
            next.children(':first-child').clone().appendTo($(this));

            //next = next.next();

            //if (!next.length) {
            //    next = $(this).siblings(':first');
            //}
            //next.children(':first-child').clone().appendTo($(this));
            run = true;
        });

        // hiding left controll in this function to work it in window resize
        $leftSpeakerControl.hide();

        /* calling show / hide right arrow */
        rightArrowHide();
    };

    /*This function is used to remove last two images from each slide to show only one image in mobile view*/
    var undo = function () {
        $('#speaker-carousel .carousel .item').each(function () {
            //  $(this).children().last().remove();
            run = false;
        });
    };

    //ensuring proper arrangement on load
    if ($(window).width() > 992) {
        multiple();
    }

    $(window).resize(function () {
        if (run == false && $(window).width() > 992) {
            $('#speaker-carousel .carousel .item').each(function () {
                $(this).children().slice(1).remove();
            });
            multiple();
        } else if (run == true && $(window).width() < 992) {
            $('#speaker-carousel .carousel .item').each(function () {
                $(this).children().slice(1).remove();
            });
            undo();
        }
    });
}

///*This is used to show Search Embed buttons after speaker in mobile view*/
//function windowResizeactions() {
//    /*---------------Action for share and embed button's positioning START----------------*/
//    if ($(window).width() < 992) {
//        $(".share-embed-buttons").remove().appendTo(("#share-embed-mobile-screen-button"));
//    } else {
//        $(".share-embed-buttons").remove().appendTo(("#share-embed-full-screen-button"));
//        $("#share-embed-mobile-screen-button").empty();

//    }
//    /*---------------Action for share and embed button's positioning END----------------*/
//}
function searchSeriesVideos(videoId, videoNo, channelName, videoTitle, displayImage, hasLock, channelId, channelColor, channelMappingDetail, IsJisc, SubscriptionType, Duration, IsEvent, EventId, EventName, IsHideRecord, EventStatus, PublishStartDate, PublishStartTime, PublishExpiryDate, PublishExpiryTime, Speaker) {
    var accessbtn = '';
    if (hasLock == false) {
        accessbtn = 'play.png';
    }
    else {
        accessbtn = 'lock.png';
    }

    var channels = "";
    for (i = 0; i < channelMappingDetail.length; i++) {
        var channel = channelMappingDetail[i];

        if (channels.length > 0) {
            channels += ' , ';
        }
        channels += '<a class="text-uppercase font-size-12" style="cursor:pointer" data-innerroutename="Channel" data-hasindex="true" data-name="' + channel.ChannelDetail.Name + '"  data-channelId=\'' + channel.ChannelDetail.Id + '\'>' + channel.ChannelDetail.Name + '</a>';
    }

    var speakersdata = "";
    if (Speaker != null) {
        for (i = 0; i < Speaker.length; i++) {
            var speaker = Speaker[i];
            if (speakersdata.length > 0) {
                speakersdata += ' , ';
            }
            speakersdata += '<span class="spkr-fname word-wrap">' + speaker.Title + ' ' + speaker.FirstName + ' ' + speaker.LastName + '</span>';
        }
    }

    var seriesName = IsNullOrEmpty(sessionStorage.getItem("SeriesName")) ? "" : sessionStorage.getItem("SeriesName");
    var seriesID = IsNullOrEmpty(sessionStorage.getItem("SeriesId")) ? "" : sessionStorage.getItem("SeriesId");

    var routName = "";
    if (IsEvent) {
        routName = (IsJisc == true) ? 'JiscVideoSearch' : 'event';
    }
    else {
        routName = (IsJisc == true) ? 'JiscVideoSearch' : 'seriesvideoid';
    }

    var searchvideohtml = "";

    if (IsEvent) {
        var PublishStartDatetime = PublishStartDate != null ? toJSDate(PublishStartDate, PublishStartTime) : "";
        var CurrentDateTime = new Date();
        var PublishEpiryDatetime = PublishExpiryDate != null ? toJSDate(PublishExpiryDate, PublishExpiryTime) : "";

        if (IsHideRecord == true) {
            searchvideohtml = "";
        }
        else {
            if (EventStatus == 1) {
                if (PublishStartDatetime != null && PublishEpiryDatetime != null) {
                    if (PublishEpiryDatetime > CurrentDateTime) {
                        searchvideohtml = '<div class="col-md-6 col-xs-6 padding-bottom-5 no-padding bottom-margin-15 searchresultrecord">' +
                            '<div class="bottom-margin-10 pull-left image-width-100" style="cursor:pointer;margin-right:10px;" >' +
                            //'<div class="thumbnail-background thumbnail-desktop-list" style="background-image:url(\'Images/temp/rel-video2.png\')">'+
                            '<div  class="thumbnail-background thumbnail-desktop-list" ' +
                            'data-innerroutename=\"' + routName + '\" data-videoNo=\"' + videoNo + '\"  data-enablerefirect="false" data-redirectpage="View/Series.html" data-seriesid=\"' + seriesID + '\" data-hasindex="true" data-eventid=\"' + EventId + '\" data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\"' + videoId + '\"  data-videoNo=\"' + videoNo + '\" data-videoTitle=\'' + videoTitle + '\' data-channelId=\"' + channelId + '\"' +
                            ' style="border:3px solid ' + channelColor + '; background-image:url(\'' + displayImage + '\') "> ' +
                            '<img class="playBtn-small-search" src="Images/' + accessbtn + '">' +
                            '</div>' +
                            '</div>' +
                            '<div class="margin-left-148 margin-right">' +
                            '<span>' +
                            //'<span>' +
                            '<div  class="text-color font-bold custom_pointer" data-hasindex="true" data-innerroutename=\"' + routName + '\" data-enablerefirect="false" data-redirectpage="View/Series.html" data-seriesid=\"' + seriesID + '\" data-hasindex="true" data-eventid=\"' + EventId + '\" data-isSeriesVideoId="true" data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\'' + videoId + '\'  data-videoNo=\"' + videoNo + '\" data-channelId=\"' + channelId + '\"' + '>' +

                            truncateString(videoTitle, 50) +
                            '</div>' +
                            '</span>' +
                            //'<span class="text-color">' + seriesName +
                            '<span class="text-color">' +
                            '<br />' +
                            speakersdata +
                            '</span>' +
                            '</div>' +
                            '</div>';
                    }
                    if (PublishEpiryDatetime < CurrentDateTime) {
                        searchvideohtml = "";
                    }
                }
                else if (PublishStartDatetime != "" && PublishEpiryDatetime == "") {
                    searchvideohtml = '<div class="col-md-6 col-xs-6 padding-bottom-5 no-padding bottom-margin-15 searchresultrecord">' +
                        '<div class="bottom-margin-10 pull-left image-width-100" style="cursor:pointer;margin-right:10px;" >' +
                        //'<div class="thumbnail-background thumbnail-desktop-list" style="background-image:url(\'Images/temp/rel-video2.png\')">'+
                        '<div  class="thumbnail-background thumbnail-desktop-list" ' +
                        'data-innerroutename=\"' + routName + '\" data-videoNo=\"' + videoNo + '\"  data-enablerefirect="false" data-redirectpage="View/Series.html" data-seriesid=\"' + seriesID + '\" data-hasindex="true" data-eventid=\"' + EventId + '\" data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\"' + videoId + '\"  data-videoNo=\"' + videoNo + '\" data-videoTitle=\'' + videoTitle + '\' data-channelId=\"' + channelId + '\"' +
                        ' style="border:3px solid ' + channelColor + '; background-image:url(\'' + displayImage + '\') "> ' +
                        '<img class="playBtn-small-search" src="Images/' + accessbtn + '">' +
                        '</div>' +
                        '</div>' +
                        '<div class="margin-left-148 margin-right">' +
                        '<span>' +
                        //'<span>' +
                        '<div  class="text-color font-bold custom_pointer" data-hasindex="true" data-innerroutename=\"' + routName + '\" data-enablerefirect="false" data-redirectpage="View/Series.html" data-seriesid=\"' + seriesID + '\" data-hasindex="true" data-eventid=\"' + EventId + '\" data-isSeriesVideoId="true" data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\'' + videoId + '\'  data-videoNo=\"' + videoNo + '\" data-channelId=\"' + channelId + '\"' + '>' +

                        truncateString(videoTitle, 50) +
                        '</div>' +
                        '</span>' +
                        //'<span class="text-color">' + seriesName +
                        '<span class="text-color">' +
                        '<br />' +
                        speakersdata +
                        '</span>' +
                        '</div>' +
                        '</div>';
                    //}
                    //else if (PublishStartDatetime > CurrentDateTime) {
                    //    searchvideohtml = "";
                    //}
                }
            }
            else {
                searchvideohtml = "";
            }
        }
    }
    else {
        searchvideohtml = '<div class="col-md-6 col-xs-6 padding-bottom-5 no-padding bottom-margin-15 searchresultrecord">' +
            '<div class="bottom-margin-10 pull-left image-width-100" style="cursor:pointer;margin-right:10px;" >' +
            //'<div class="thumbnail-background thumbnail-desktop-list" style="background-image:url(\'Images/temp/rel-video2.png\')">'+
            '<div  class="thumbnail-background thumbnail-desktop-list" ' +
            'data-innerroutename=\"' + routName + '\" data-enablerefirect="false" data-redirectpage="View/Series.html" data-seriesid=\"' + seriesID + '\" data-hasindex="true" data-videoId=\"' + videoId + '\"  data-videono=\"' + videoNo + '\"   data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\'' + videoId + '\'  data-videoNo=\"' + videoNo + '\" data-channelId=\"' + channelId + '\"' +
            ' style="border:3px solid ' + channelColor + '; background-image:url(\'' + displayImage + '\') "> ' +
            '<img class="playBtn-small-search" src="Images/' + accessbtn + '">' +
            '</div>' +
            '</div>' +
            '<div class="margin-left-148 margin-right">' +
            '<span class=" ">' +
            //'<span>' +
            '<div  class="text-color font-bold custom_pointer" data-enablerefirect="false" data-redirectpage="View/Series.html" data-seriesid=\"' + seriesID + '\" data-hasindex="true" data-innerroutename=\"' + routName + '\" data-isSeriesVideoId="true" data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'  data-videoId=\'' + videoId + '\' data-videoNo=\"' + videoNo + '\" data-channelId=\"' + channelId + '\"' + '>' +

            truncateString(videoTitle, 50) +
            '</div>' +
            '</span>' +
            //'<span class="text-color">' + seriesName +
            '<span class="text-color">' +
            '<br />' +
            speakersdata +
            '</span>' +
            '</div>' +
            '</div>';
    }
    return searchvideohtml;
}
function CopyToClipboardSeries() {
    if ($('#embedcodeSeries').hasClass("DataTocopy")) {
        $("#embedcodeSeries").copymeSeries();
    } else if ($('#facebookcodeSeries').hasClass("DataTocopy")) {
        $("#facebookcodeSeries").copymeSeries()
    }

    var messageViewModel = new MessageViewModel();
    messageViewModel.CreateInfoMessage("Copied to clipboard successfully", "overlayId", "okButtonId");
    messageViewModel.ShowOverLay();
    $('#iframeEmbedSeries').prop('checked', true);
    $('#facebookTwitterEmbedSeries').prop('checked', false);
    $('#embedcodeSeries').addClass("DataTocopy");
}
function callDownloadVideo() {
    if (localStorage.getItem('AccountId') != 0) {
        //$('#helptext').text(CurrentVideoDetail.Title + " is about to download.<br/> ")
        if (!this.CurrentVideoDetail.HasLock) {
            $("#DownloadHelp").modal({
                backdrop: 'static',
                keyboard: false
            });
            $("#DownloadHelp").modal('show');
            $("#btnDownloadContinue").unbind();
            $("#btnDownloadContinue").bind("click", function (e) {
                $("#DownloadHelp").modal('hide');
                VideoRepository.DownloadVideo();
            });
        }
        else {
            var messageViewModel = new MessageViewModel();
            messageViewModel.CreateInfoMessage("Please subscribe to download the video.", "overlayId", "okButtonId");
            messageViewModel.ShowOverLay();
        }
    }
    else {
        var messageViewModel = new MessageViewModel();
        messageViewModel.CreateInfoMessage("Please login to download the video.", "overlayId", "okButtonId");
        messageViewModel.ShowOverLay();
    }
}

function getSeriesAddtionaVideoHTML(videoid, channelName, videoTitle, videoimage, hasLock, channelId, IsJisc, IsEvent, eventId, SubscriptionType, Duration) {
    var accessbtn = '';
    if (hasLock == false) {
        accessbtn = 'play.png';
    }
    else {
        accessbtn = 'lock.png';
    }

    if (IsEvent == true) {
        var videoroute = 'data-innerroutename=\"event\" data-enablerefirect="false" data-redirectpage="View/EventLiveLanding.html" data-eventid=\"' + eventId + '\" data-videoid=\"' + videoid + '\"  data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        var channelroute = 'data-innerroutename="Channel" data-hasindex="true" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
    }
    else if (videoid != "" && IsJisc == false) {
        var videoroute = 'data-innerroutename=\"videoid\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        var channelroute = 'data-innerroutename="Channel" data-hasindex="true" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
    }
    else if (videoid != "" && IsJisc == true) {
        var videoroute = 'data-innerroutename=\"JiscVideo\" data-ChannelId=\"' + channelId + '\"  data-videoId=\'' + videoid + '\' data-hasindex="true" data-isJisc=\'' + IsJisc + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
        var channelroute = 'data-innerroutename="Channel" data-name="' + channelName + '"  data-channelId=\'' + channelId + '\' data-videoTitle=\'' + videoTitle + '\' data-SubscriptionType=\'' + SubscriptionType + '\'data-Duration=\'' + Duration + '\'';
    }

    var addtionaVideoHTML = '<div class="float-left bottom-margin-20 video-thumbnail-container" cursor="pointer">' +
        '<div class="thumbnail-background thumbnail-desktop-list" ' + videoroute + ' style="background-image:url(\'' + videoimage + '\')">' +
        '<img class="playBtn-small" src="Images/' + accessbtn + '">' +
        '</div>' +
        '<div class="text-margin">' +
        '<div class="list-caption" ' + videoroute + ' >' + truncateString(videoTitle, 30) + '</div><br>' +
        '<div class="list-channel" ' + channelroute + ' >' + channelName + '</div>' +
        '</div>' +
        '</div>';
    //'<div class="clearfix"></div>'

    return addtionaVideoHTML;
}

var access_CodeTypeSeries = "";
var txtAccessCodeSeries = "";

function StoreAccessCodeInSeriesPage() {
    txtAccessCodeSeries = ($('#txtAccessCode').val().trim());
    var IsUserLoggedInSeriesPage = "0";

    if (document.getElementById("rdoSpeaker").checked) {
        sessionStorage.setItem("accessCode", txtAccessCodeSeries);
        sessionStorage.setItem("accessCodeType", SpeakerAccessCodeType);
        sessionStorage.setItem("accessCodeFlag", false);
    }
    else if (document.getElementById("rdoEvent").checked) {
        sessionStorage.setItem("accessCode", txtAccessCodeSeries);
        sessionStorage.setItem("accessCodeType", EventAccessCodeType);
        sessionStorage.setItem("accessCodeFlag", false);
        SetSeriesAccessCodeDetailsFromLocalStorage();
        location.href = window.location.href;
    }
    else if (document.getElementById("rdoVideo").checked) {
        localStorage.setItem("accessCode", txtAccessCodeSeries);
        localStorage.setItem("accessCodeType", VideoAccessCodeType);
        localStorage.setItem("accessCodeFlag", false);
        SetSeriesAccessCodeDetailsFromLocalStorage();
        location.href = window.location.href;       
    }
}

//This is the temp function
function SetSeriesAccessCodeDetailsFromLocalStorage() {
    var accessCode = "";
    var accessCodeType = "";
    var accessCodeFlag = "";
    var routeSeriesVideoId = "seriesvideoid";

    if (!IsNullOrEmpty(localStorage.getItem("accessCode"))) {
        accessCode = localStorage.getItem("accessCode");
        sessionStorage.setItem("accessCode", accessCode);
    }

    if (!IsNullOrEmpty(localStorage.getItem("accessCodeType"))) {
        accessCodeType = localStorage.getItem("accessCodeType");
        sessionStorage.setItem("accessCodeType", accessCodeType);
    }

    if (!IsNullOrEmpty(localStorage.getItem("accessCodeFlag"))) {
        accessCodeFlag = localStorage.getItem("accessCodeFlag");
        sessionStorage.setItem("accessCodeFlag", accessCodeFlag);
    }
   
    if (!IsNullOrEmpty(sessionStorage.getItem("RedirectFrom"))) {
        var redirectFrom = sessionStorage.getItem("RedirectFrom")
        if (redirectFrom == routeSeriesVideoId) {
            sessionStorage.setItem("RedirectLocation", routeSeriesVideoId)
        }
    }
}
function SetRedirectLocationToSeriesPage() {
    var routeName = sessionStorage.getItem("LastRouteName");
    BrowserStorage.setRedireceLocation(routeName);
    BrowserStorage.setRedireceFrom(routeName);
    sessionStorage.setItem("RedirectFromBeforeSSO", window.location.href);
    location.href = "view/" + Application.Login.BaseURL;
}

function WindowResizeForVideo() {
    if ($(window).width() < 992) {
        var responsiveHeight;
        if ($("#divVideoContainer").hasClass('premiumVideoWithBuyEvent')) {
            responsiveHeight = ((parseInt($(".video-container").css("width")) * 13) / 16);
        }
        else {
            responsiveHeight = ((parseInt($(".video-container").css("width")) * 9) / 16);
        }
        $('.video-sizer').css('height', responsiveHeight);
    }
    else {
        $('.video-sizer').css('height', '467px');
    }
}

function toJSDate(date, time) {
    var toDate = date.split("/");
    var toTime = time.split(":");

    //(year, month, day, hours, minutes, seconds, milliseconds)
    //subtract 1 from month because Jan is 0 and Dec is 11
    return new Date(toDate[2], (toDate[1] - 1), toDate[0], toTime[0], toTime[1], 0, 0);
}

function GetEventDetails(PublishStartDatetime, CurrentDateTime, PublishEpiryDatetime, IsHideRecord, EventStatus, eventVideoDetails, Title, messageParameter,dataMessage) {
    if (IsHideRecord == true) {
        var eventHTML = {
            premiumEventDetail: "",
            btnPurchaseEvent: ""
        }
        return eventHTML;
    }
    else {
        if (EventStatus == 1) {
            if (PublishStartDatetime != "" && PublishEpiryDatetime != "") {
                if (PublishEpiryDatetime >= CurrentDateTime) {
                    if (messageParameter == 'btnVisible') {
                        premiumEventDetail = 'This video is part of paid event ' + '<a href="#" data-toggle="modal" data-target="#premiumEventDetails">' + CurrentVideoDetail.EventDetails.Title + '</a>' + '. Please purchase the event to gain access to the video.';
                        btnPurchaseEvent = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                        var eventHTML = {
                            premiumEventDetail: premiumEventDetail,
                            btnPurchaseEvent: btnPurchaseEvent
                        }

                        return eventHTML;
                    }
                    else if (messageParameter == 'btnInvisible') {
                       
                        //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                        if (dataMessage != null && dataMessage != null) {
                            var messageViewModel = new MessageViewModel();
                            messageViewModel.CreateWarningMessage(dataMessage, "overlayId", "okButtonId");
                            messageViewModel.ShowOverLay();
                        }
                    //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end
                        videoType = ' This video is part of paid event ' + CurrentVideoDetail.EventDetails.Title + '. Kindly contact the IET Administrator to gain access to this event.';
                        var eventHTML = {
                            videoType: videoType
                        }
                        return eventHTML;
                    }
                    else if (messageParameter == 'EventPriced') {
                        videoType = ' This video is part of paid event ' + CurrentVideoDetail.EventDetails.Title + '. Please purchase the event to gain access to the video.';
                        btnPurchaseProduct = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                        var eventHTML = {
                            videoType: videoType,
                            btnPurchaseProduct: btnPurchaseProduct
                        }
                        return eventHTML;
                    }
                }
                else if (PublishEpiryDatetime < CurrentDateTime) {
                    var eventHTML = {
                        premiumEventDetail: "",
                        videoType: "",
                        btnPurchaseProduct: ""
                    }
                    return eventHTML;
                }
            }
            else if (PublishStartDatetime != "" && PublishEpiryDatetime == "") {
                if (messageParameter == 'btnVisible') {
                    premiumEventDetail = 'This video is part of paid event ' + '<a href="#" data-toggle="modal" data-target="#premiumEventDetails">' + CurrentVideoDetail.EventDetails.Title + '</a>' + '. Please purchase the event to gain access to the video.';
                    btnPurchaseEvent = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                    var eventHTML = {
                        premiumEventDetail: premiumEventDetail,
                        btnPurchaseEvent: btnPurchaseEvent
                    }

                    return eventHTML;
                }
                else if (messageParameter == 'btnInvisible') {
                   
                    //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user start
                    if (dataMessage != null && dataMessage != null) {
                        var messageViewModel = new MessageViewModel();
                        messageViewModel.CreateWarningMessage(dataMessage, "overlayId", "okButtonId");
                        messageViewModel.ShowOverLay();
                    }
                    //Added for PS - 1410: IET TV: Proper validation message should be displayed for buy event / video for a corporate user end
                    videoType = ' This video is part of paid event ' + CurrentVideoDetail.EventDetails.Title + '. Kindly contact the IET Administrator to gain access to this event.';
                    var eventHTML = {
                        videoType: videoType
                    }
                    return eventHTML;
                }
                else if (messageParameter == 'EventPriced') {
                    videoType = ' This video is part of paid event ' + CurrentVideoDetail.EventDetails.Title + '. Please purchase the event to gain access to the video.';
                    btnPurchaseProduct = '<div><button type="button" class="btn-default premium_video_btn" data-toggle="modal" data-target="#buyEventPrompt">Buy event</button></div>';
                    var eventHTML = {
                        videoType: videoType,
                        btnPurchaseProduct: btnPurchaseProduct
                    }
                    return eventHTML;
                }
            }
        }
        else {
            var eventHTML = {
                premiumEventDetail: "",
                videoType: "",
                btnPurchaseProduct: ""
            }
            return eventHTML;
        }
    }
}

//this.CurrentQuestionDetail = {};
//this.CurrentAnswerOptions = {};

var EventContentTypeId = 3;
var VideoContentTypeId = 2;


var PollRepository = function () {

    this.MessageViewModel = new MessageViewModel();

    this.SubmitPoll = function () {
        var logonId = BrowserStorage.getLogonId();
        var questionId = $('#QuestionId').val();
        var optionId = $('input[name=pollOption]:checked').val(); //$('QuestionId').val();

        if (IsNullOrEmpty(optionId)) {
            _this.MessageViewModel.CreateWarningMessage("Please select anyone option of your choice.", "overlayId", "okButtonId");
            _this.MessageViewModel.ShowOverLay();
            return false;
        }

        var accessCodeType;

        if(IsNullOrEmpty(sessionStorage.getItem("accessCodeType")))
        {
            accessCodeType = 0;
        }
        else
        {
            accessCodeType = sessionStorage.getItem("accessCodeType");
        }

        var object = {
            LogonId: logonId,
            QuestionId: questionId,
            OptionId: optionId,
            AccessCode: sessionStorage.getItem("accessCode"),
            AccessCodeType: accessCodeType
        }


        Repository.LoadDataJSON(WebService.BaseURL + 'PollManagement/PollService.svc/PostResponse',
           function (data, status, headers, config) {
               ///isvalid
               if (ResultStatus.Successful == data.Status && data.ResultObject) {
                   if (data.ResultObject == null) {
                       //no data
                       $('#NoRecordFound').html(data.Message);
                       $('#Table_Video').hide();
                   }
                   else {

                       ShowPollResult(data.ResultObject)

                       _this.MessageViewModel.CreateSuccessMessage("Your poll response has been posted successfully.", "overlayId", "okButtonId");
                       _this.MessageViewModel.ShowOverLay();
                   };
               }
               else {
                   _this.MessageViewModel.CreateErrorMessage(data.Message, "overlayId", "okButtonId");
                   _this.MessageViewModel.ShowOverLay();
               }
           }
               //notvalidate

               //$('#txtMessage').val('');
               //_this.GetMessagesForGroup(groupName);
          ,
            function (data, status, headers, config) {
                //console.log(data);

            }, JSON.stringify(object));



    }
    ,

        this.GetQuestionAndOptions = function (QnAArtifact) {

            var eventId = sessionStorage.getItem("EventId");
            var videoId = sessionStorage.getItem("VideoId");
            var logonId = BrowserStorage.getLogonId();
            //var videoId = sessionStorage.getItem("videoId");

            if (QnAArtifact == 'Event') {
                var object = {
                    ContentTypeId: EventContentTypeId,
                    ContentId: eventId,
                    LogonId: logonId
                }
            }
            else if (QnAArtifact == 'Video') {
                var object = {
                    ContentTypeId: VideoContentTypeId,
                    ContentId: videoId,
                    LogonId: logonId
                }
            }

            Repository.LoadDataJSONFalseAjax(WebService.BaseURL + 'PollManagement/PollService.svc/GetQuestionAndOptions',
               function (data, status, headers, config) {
                   ///isvalid
                   if (ResultStatus.Successful == data.Status && data.ResultObject) {
                       if (data.ResultObject == null) {
                           //no data
                           $('#NoRecordFound').html(data.Message);
                           $('#Table_Video').hide();
                       }
                       else {

                           var questionDetail = data.ResultObject;
                           //if (IsNullOrEmpty(questionDetail.QuestionText)) {
                           //    PollQuestionAvailable = 0;
                           //}
                           //else {
                           //    PollQuestionAvailable = 1;
                           //}

                           //This is to analyze the flow

                           
                           if (IsNullOrEmpty(questionDetail.QuestionText) && IsNullOrEmpty(questionDetail.pollResult)) {
                               return;
                           }
                           
                           
                           if (!IsNullOrEmpty(questionDetail.pollResult)) {
                               if (IsNullOrEmpty(questionDetail.pollResult.QuestionText)) return;
                               $('#QuestionId').val(questionDetail.pollResult.ParentQuestionId);
                               ShowPollResult(questionDetail.pollResult)
                               PollQuestionAvailable = 1;
                           } else {
                               $('.poll-results-container').addClass('display-none');
                               this.CurrentQuestionDetail = {
                                   QuestionId: questionDetail.QuestionId,
                                   QuestionText: questionDetail.QuestionText
                               }

                               PollQuestionAvailable = 1;

                               //$('#OptionsContainer').empty();
                               

                               $('#QuestionDiv').html(CurrentQuestionDetail.QuestionText);
                               $('#QuestionId').val(CurrentQuestionDetail.QuestionId);



                               if (!IsNullOrEmpty(questionDetail.PollingAnswerOptions)) {
                                   if (questionDetail.PollingAnswerOptions.length > 0) {

                                       for (q = 0; q < 7; q++) {
                                           var radioOption = $('#pollOption' + q);
                                           radioOption.addClass("display-none");
                                           radioOption.prop('checked', false);
                                           $('#poll-question-text' + q).addClass("display-none");
                                           $('#poll_total_responses').html('');
                                           
                                       }
                                      
                                       for (i = 0; i < questionDetail.PollingAnswerOptions.length; i++) {
                                           this.CurrentAnswerOptions = {
                                               OptionId: questionDetail.PollingAnswerOptions[i].OptionId,
                                               OptionText: questionDetail.PollingAnswerOptions[i].Options
                                           }

                                           //var OptionsFormat = '<div class="poll-option"><label><input type="radio" name="pollOption" value="{1}"/>{0}</label></div>';

                                           $('#pollOption' + i).val(CurrentAnswerOptions.OptionId);
                                           //$('#pollLabel' + i).html($('#pollLabel' + i).html() + '<span class="poll-question-text">' + CurrentAnswerOptions.OptionText + '</span>');
                                           $('#poll-question-text' + i).text(CurrentAnswerOptions.OptionText);
                                           $('#pollOption' + i).removeClass("display-none");
                                           $('#pollLabel' + i).removeClass("display-none");
                                           $('#poll-question-text' + i).removeClass("display-none");
                                           // $(OptionsFormat.format(this.CurrentAnswerOptions.OptionText,this.CurrentAnswerOptions.OptionId)).appendTo('#OptionsContainer');
                                       }
                                       //$('<button class="btn btn-primary btn-poll-submit" id="btnPollSubmit">Submit</button>').appendTo('#OptionsContainer');
                                   }
                               }

                               $('#QuestionContainer').removeClass('display-none');
                               $('#OptionsContainer').removeClass('display-none');

                           }

                           //console.log('pollrepo' + PollQuestionAvailable);
                       };
                   }
               }
                   //notvalidate

                   //$('#txtMessage').val('');
                   //_this.GetMessagesForGroup(groupName);
              ,
                function (data, status, headers, config) {
                    //console.log(data);

                }, JSON.stringify(object));
        }
}

function ShowPollResult(ResultObject) {

    //************************************
    
    var PollTotal = ResultObject.PollTotal;

    var NumericResult = new Array();

    NumericResult = ResultObject.NumericResult.split(',');

    var PercentageResult = new Array();

    PercentageResult = ResultObject.PercentageResult.split(',');

    for (q = 0; q < 7; q++) {
        $('#poll_result_border_' + q).addClass('display-none');
        $('#poll_option_' + q).addClass('display-none');
    }

    for (i = 0; i < PercentageResult.length; i++) {
        $('#poll_bar_' + i).width(PercentageResult[i] + '%');
        $('#poll_bar_' + i).html(PercentageResult[i] + '%');
        $('#poll_result_border_' + i).removeClass('display-none');
    }


    var OptionResult = new Array();

    OptionResult =ResultObject.OptionResult.split(',');

    for (i = 0; i < OptionResult.length; i++) {
        $('#poll_option_' + i).html(OptionResult[i] + '&nbsp;&nbsp;<span class="poll-total-responses">(' + NumericResult[i] + ')</span>');
        $('#poll_option_' + i).removeClass('display-none');
        $('#poll_total_responses').html(PollTotal + ' response(s)');
    }

    $('#QuestionDiv').html(ResultObject.QuestionText);

    $('.poll-options-container').addClass('display-none');
    $('.poll-results-container').removeClass('display-none');
    $('#QuestionContainer').removeClass('display-none');

    var QnAArtifact = sessionStorage.getItem('QnAArtifact');

    if (QnAArtifact.toLowerCase() == 'video') {
        handleVideoQnA();
    }
    else if (QnAArtifact.toLowerCase() == 'event') {
        handleEventQnA();
    }
}
var premiumVideoIds = [];
var channelCatalogList;

var MARCRepository = {
    
}
var OrderConfirmationRepository = function () {
    this.getOrderDetails = function () {
        var order = {
            "LogonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
            "OrderId": IsNullOrEmpty(sessionStorage.getItem("OrderId")) ? "" : sessionStorage.getItem("OrderId"),
            "OrderStatus": "InCheckout-OrderConfirmation"
        };

        var object = {
            Data: {
                "orderDetails": order
            }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'Transactions/WebPortalTransaction.svc/UpdateOrderTransactionStatus',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.LoginStatus) {
                    if (ResultStatus.Successful == data.Status && data.ResultObject) {
                        //Do nothing
                    }
                    else {
                        var messageViewModel = new MessageViewModel();
                        messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {

                        });
                        messageViewModel.ShowOverLay();
                    }
                }
                else {
                    var messageViewModel = new MessageViewModel();
                    messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {

                    });
                    messageViewModel.ShowOverLay();

                }
                if (!WebService.DisableGA) {
                    
                    storeurlDetailsInGA('orderconfirmation');
                }
            },
            function (data, status, headers, config) {
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();

            }, JSON.stringify(object.Data));

        var object1 = {
            Data: {
                "logonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
                "orderId": IsNullOrEmpty(sessionStorage.getItem("OrderId")) ? "" : sessionStorage.getItem("OrderId"),
                "isUpdateOrderCode": "true"
            }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'Transactions/WebPortalTransaction.svc/GetOrderDetails',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.LoginStatus) {
                    if (ResultStatus.Successful == data.Status && data.ResultObject) {                                                
                        $("#ordercode").text(data.ResultObject.OrderCode);                       
                        $("#subscriptionPeriod").text(data.ResultObject.Period);
                        $("#address1").html(data.ResultObject.UserAddressDetails.Address1);
                        $("#address2").html(data.ResultObject.UserAddressDetails.Address2);
                        $("#address3").html(data.ResultObject.UserAddressDetails.Address3);
                        $("#address4").html(data.ResultObject.UserAddressDetails.Address4);
                        $("#city").html(data.ResultObject.UserAddressDetails.City);
                        $("#state").text(data.ResultObject.UserAddressDetails.State);
                        $("#country").text(data.ResultObject.UserAddressDetails.Country);
                        $("#postcode").html(data.ResultObject.UserAddressDetails.Postcode);
                        $("#hdnIsMember").val(data.ResultObject.IsIndividualIETMember);                    
                       
                        if (data.ResultObject.SubscriptionPurchaseDetails.length != 0)
                        {
                            var strSubscriptionListTable = '<table class="col-md-11 form-group col-lg-12 table table-bordered" style="border:0 !important;" border="1">'

                            //For channel table
                            if (data.ResultObject.SubscriptionPurchaseType == "channel")
                            {
                                $("#Orderconfirmationtitle").text("Channel Details:")
                                strSubscriptionListTable += ' <thead style="background-color: rgb(229, 229, 229)"><tr  class="hidden-sm hidden-xs">' +
                                     '<th class="hidden-md hidden-lg mobileviewhead"></th>' +
                                   '<th class="col-md-3">Channel</th>' +
                                   '<th>Catalogue</th>' +
                                    '<th>Price</th>' +
                                    '<th>VAT (%)</th>' +
                                    '<th>VAT Price</th>' +
                                    '<th>Price including VAT</th>' +
                                    '<th>Start Date</th>' +
                                    '<th>End Date</th>';
                                strSubscriptionListTable += '</tr></thead>';
                                var totalPurchasedPrice = 0;
                                $.each(data.ResultObject.SubscriptionPurchaseDetails, function (index, data) {

                                    strSubscriptionListTable += '<tr>' +
                                    //For Mobile menu start
                                    '<td  class="hidden-md hidden-lg mobileviewdata">' +
                                   '<table class="table table-bordered inner_table_border">' +
                                   '<tbody><tr><td colspan="2" style="background-color: rgb(229, 229, 229);color: #333; font-weight:bold;">' + data.ChannelName + '</td></tr>' +
                                    '<tr> <td class="inner_table_td">Catalogue</td> <td>' + data.Catalogue + '</td></tr>  ' +
                                       '<tr> <td class="inner_table_td">Price</td> <td>' + data.Price + '</td></tr>  ' +
                                          '<tr> <td class="inner_table_td">VAT (%)</td> <td>' + data.SubscriptionVATPercentage + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">VAT Price</td> <td>' + data.SubscriptionVATPrice + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">Price including VAT</td> <td>' + data.SubscriptionFinalPrice + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">Start Date</td> <td>' + data.SubscriptionStartDateTime + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">End Date</td> <td>' + data.SubscriptionEndDateTime + '</td></tr>  ' +
                                    '</tbody> </table> </td>' +

                                      //For Mobile menu end

                                  
                                        '<td class="hidden-sm hidden-xs">' + data.ChannelName + '</td>' +
                                         '<td class="hidden-sm hidden-xs">' + data.Catalogue + '</td>' +
                                          '<td class="hidden-sm hidden-xs">' + data.Price + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionVATPercentage + "%" + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionVATPrice + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionFinalPrice + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionStartDateTime + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionEndDateTime + '</td>';

                       
                                  
                                    totalPurchasedPrice += parseFloat(Number(data.SubscriptionFinalPrice.replace(/[^0-9\.]+/g, "")));

                                    


                                });

                                var GrandTotalStr="";
                                GrandTotalStr ='<tr><td colspan="8"  class="purchase-final-total-size"><span style="float: right;" class="purchase-final-total-text"><strong>Grand Total: £</strong>'; 
                                GrandTotalStr = GrandTotalStr+ '<span class="purchase-final-total-value purchasedTotal"><strong>'+ totalPurchasedPrice.toFixed(2) +'</strong></span></span></td></tr>';
                                strSubscriptionListTable += GrandTotalStr;

                                strSubscriptionListTable += '</tr>';
                            }
                            if (data.ResultObject.SubscriptionPurchaseType == "video" || data.ResultObject.SubscriptionPurchaseType == "video live") {                             

                                $("#Orderconfirmationtitle").text("Video Details:")
                                strSubscriptionListTable += '<thead style="background-color: rgb(229, 229, 229)"><tr  class="hidden-sm hidden-xs">' +
                                    '<th class="hidden-md hidden-lg mobileviewhead"></th>' +
                                   '<th class="col-md-3">Video</th>' +                                   
                                    '<th>Price</th>' +
                                    '<th>VAT (%)</th>' +
                                    '<th>VAT Price</th>' +
                                    '<th>Discount (%)</th>' +
                                    '<th>Discount Price</th>' +
                                    '<th>Price including VAT</th>' +
                                    '<th>Start Date</th>' +
                                    '<th>End Date</th>';
                                strSubscriptionListTable += '</tr></thead>';
                                var totalPurchasedPrice = 0;
                                $.each(data.ResultObject.SubscriptionPurchaseDetails, function (index, data) {


                                    strSubscriptionListTable += '<tr>' +

                                         //For Mobile menu start
                                    '<td class="hidden-md hidden-lg mobileviewdata">' +
                                   '<table class="table table-bordered inner_table_border">' +
                                   '<tbody><tr><td colspan="2" style="background-color: rgb(229, 229, 229);color: #333; font-weight:bold;">' + data.ChannelName + '</td></tr>' +                                    
                                       '<tr> <td class="inner_table_td">Price</td> <td>' + data.Price + '</td></tr>  ' +
                                          '<tr> <td class="inner_table_td">VAT (%)</td> <td>' + data.SubscriptionVATPercentage + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">VAT Price</td> <td>' + data.SubscriptionVATPrice + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">Discount (%)</td> <td>' + data.SubscriptionDiscountInPercentage + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">Discount Price</td> <td>' + data.SubscriptionDiscountPrice + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">Price including VAT</td> <td>' + data.SubscriptionFinalPrice + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">Start Date</td> <td>' + data.SubscriptionStartDateTime + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">End Date</td> <td>' + data.SubscriptionEndDateTime + '</td></tr>  ' +
                                    '</tbody> </table> </td>' +

                                      //For Mobile menu end


                                        '<td class="hidden-sm hidden-xs">' + data.ChannelName + '</td>' +
                                          '<td class="hidden-sm hidden-xs">' + data.Price + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionVATPercentage + "%" + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionVATPrice + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionDiscountInPercentage + "%" + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionDiscountPrice + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionFinalPrice + '</td>' +
                                             '<td class="hidden-sm hidden-xs">' + data.SubscriptionStartDateTime + '</td>' +
                                             '<td class="hidden-sm hidden-xs">' + data.SubscriptionEndDateTime + '</td>';
                                  

                                    totalPurchasedPrice += parseFloat(Number(data.SubscriptionFinalPrice.replace(/[^0-9\.]+/g, "")));

                                    if (data.DiscountType != "")
                                    {
                                        $(".trVideoSubsDiscountType").show();
                                        $("#SubsDiscountType").text(data.DiscountType);
                                    }                                   

                                });

                                
                                var GrandTotalStr="";
                                GrandTotalStr = '<tr><td colspan="9"  class="purchase-final-total-size"><span style="float: right;" class="purchase-final-total-text"><strong>Grand Total: £</strong>';
                                GrandTotalStr = GrandTotalStr + '<span class="purchase-final-total-value purchasedTotal"><strong>' + totalPurchasedPrice.toFixed(2) + '</strong></span></span></td><tr>';
                                strSubscriptionListTable += GrandTotalStr;

                                strSubscriptionListTable += '</tr>';
                            }

                            if (data.ResultObject.SubscriptionPurchaseType == "event") {

                                $("#Orderconfirmationtitle").text("Event Details:")
                                strSubscriptionListTable += '<thead style="background-color: rgb(229, 229, 229)"><tr  class="hidden-sm hidden-xs">' +
                                    '<th class="hidden-md hidden-lg mobileviewhead"></th>' +
                                   '<th class="col-md-3">Event</th>' +
                                    '<th>Price</th>' +
                                    '<th>VAT (%)</th>' +
                                    '<th>VAT Price</th>' +
                                    '<th>Discount (%)</th>' +
                                    '<th>Discount Price</th>' +
                                    '<th>Price including VAT</th>' +
                                    '<th>Start Date</th>' +
                                    '<th>End Date</th>';
                                strSubscriptionListTable += '</tr></thead>';
                                var totalPurchasedPrice = 0;
                                $.each(data.ResultObject.SubscriptionPurchaseDetails, function (index, data) {


                                    strSubscriptionListTable += '<tr>' +

                                         //For Mobile menu start
                                    '<td class="hidden-md hidden-lg mobileviewdata">' +
                                   '<table class="table table-bordered inner_table_border">' +
                                   '<tbody><tr><td colspan="2" style="background-color: rgb(229, 229, 229);color: #333; font-weight:bold;">' + data.ChannelName + '</td></tr>' +
                                       '<tr> <td class="inner_table_td">Price</td> <td>' + data.Price + '</td></tr>  ' +
                                          '<tr> <td class="inner_table_td">VAT (%)</td> <td>' + data.SubscriptionVATPercentage + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">VAT Price</td> <td>' + data.SubscriptionVATPrice + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">Discount (%)</td> <td>' + data.SubscriptionDiscountInPercentage + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">Discount Price</td> <td>' + data.SubscriptionDiscountPrice + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">Price including VAT</td> <td>' + data.SubscriptionFinalPrice + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">Start Date</td> <td>' + data.SubscriptionStartDateTime + '</td></tr>  ' +
                                             '<tr> <td class="inner_table_td">End Date</td> <td>' + data.SubscriptionEndDateTime + '</td></tr>  ' +
                                    '</tbody> </table> </td>' +

                                      //For Mobile menu end


                                        '<td class="hidden-sm hidden-xs">' + data.ChannelName + '</td>' +
                                          '<td class="hidden-sm hidden-xs">' + data.Price + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionVATPercentage + "%" + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionVATPrice + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionDiscountInPercentage + "%" + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionDiscountPrice + '</td>' +
                                            '<td class="hidden-sm hidden-xs">' + data.SubscriptionFinalPrice + '</td>' +
                                             '<td class="hidden-sm hidden-xs">' + data.SubscriptionStartDateTime + '</td>' +
                                             '<td class="hidden-sm hidden-xs">' + data.SubscriptionEndDateTime + '</td>';


                                    totalPurchasedPrice += parseFloat(Number(data.SubscriptionFinalPrice.replace(/[^0-9\.]+/g, "")));

                                    if (data.DiscountType != "") {
                                        $(".trVideoSubsDiscountType").show();
                                        $("#SubsDiscountType").text(data.DiscountType);
                                    }

                                });


                                var GrandTotalStr = "";
                                GrandTotalStr = '<tr><td colspan="9"  class="purchase-final-total-size"><span style="float: right;" class="purchase-final-total-text"><strong>Grand Total: £</strong>';
                                GrandTotalStr = GrandTotalStr + '<span class="purchase-final-total-value purchasedTotal"><strong>' + totalPurchasedPrice.toFixed(2) + '</strong></span></span></td><tr>';
                                strSubscriptionListTable += GrandTotalStr;

                                strSubscriptionListTable += '</tr>';
                            }

                            strSubscriptionListTable += '</table>' +
                            $('.SubscriptionList').html(strSubscriptionListTable);
                           // $('.purchasedTotal').text(parseFloat(totalPurchasedPrice));
                            
                        }
                    }
                    else {
                        var messageViewModel = new MessageViewModel();
                        messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {

                        });
                        messageViewModel.ShowOverLay();
                    }
                }
                else {
                    var messageViewModel = new MessageViewModel();
                    messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
                        $("#okButtonId").click(function () {
                            location.href = "?home";
                        });
                    });
                    messageViewModel.ShowOverLay();

                }
            },
            function (data, status, headers, config) {
                Spinner.Stop();
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();

            }, JSON.stringify(object1.Data));
    },
    

    this.updateOrderTransactionStatus = function (orderstatus) {
        var order = {
            "LogonId": IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
            "OrderId": IsNullOrEmpty(sessionStorage.getItem("OrderId")) ? "" : sessionStorage.getItem("OrderId"),
            "OrderStatus": orderstatus
        };

        var object = {
            Data: {
                "orderDetails": order
            }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'Transactions/WebPortalTransaction.svc/UpdateOrderTransactionStatus',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.LoginStatus) {
                    if (ResultStatus.Successful == data.Status && data.ResultObject) {
                        //Do nothing
                    }
                    else {
                        var messageViewModel = new MessageViewModel();
                        messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {

                        });
                        messageViewModel.ShowOverLay();
                    }
                }
                else {
                    var messageViewModel = new MessageViewModel();
                    messageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId", function () {
                        $("#okButtonId").click(function () {
                            location.href = "?home";
                        });
                    });
                    messageViewModel.ShowOverLay();

                }
            },
            function (data, status, headers, config) {
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();

            }, JSON.stringify(object.Data));
    }
};
var ForgotPasswordRepository = {

    MessageViewModel: new MessageViewModel(),
    checkUserExists: function (user) {
        var _this = this;
        var object = {
            Data: {
                "user":
                    {
                        UserName: user.UserName,
                        requestUrl: location.href.toLocaleLowerCase().split('view')[0]
                    }
            }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/checkUserExists',
            function (data, status, headers, config) {
                if (data.ResultObject && data.Status == ResultStatus.Successful) {

                    //if it is corporate 
                    //if (data.ResultObject == 1) {
                        //Removing overlaySpinner
                        $('.custom_messages').animate({ 'top': '-100' }, 'fast');
                        $('#overlaySpinner').css("display", "none");

                        _this.MessageViewModel.CreateInfoMessage(data.Message);
                        _this.MessageViewModel.ShowOverLay();
                        $('#Username').val("");
                   // }
                    //else if (data.ResultObject == 2) {
                    //for individual
                    //    if (user.UserName.indexOf("@") < 0) {
                    //        $('form[name=ForgetPassword]').attr('action', WebService.ForgottenPasswordIETURL).attr('method', Method.POST).submit();
                    //    }

                    //}
                }
                else {
                    //Removing overlaySpinner
                    $('.custom_messages').animate({ 'top': '-100' }, 'fast');
                    $('#overlaySpinner').css("display", "none");

                    _this.MessageViewModel.CreateWarningMessage(data.Message, "overlayId", "okButtonId");
                    _this.MessageViewModel.ShowOverLay();
                    $('#Username').val("");

                }
            },


            function (data, status, headers, config) {

                //Removing overlaySpinner
                $('.custom_messages').animate({ 'top': '-100' }, 'fast');
                $('#overlaySpinner').css("display", "none");


                _this.MessageViewModel.CreateWarningMessage(data, "overlayId", "okButtonId", function () {
                    $("#okButtonId").unbind();
                    $("#okButtonId").bind("click", function (e) {
                        checkLoginStatus(data);
                    });
                });
                _this.MessageViewModel.ShowOverLay();
            },
            JSON.stringify(object.Data));
    }
};








var url = window.location.href;
var currentURL = url.substring(0, url.lastIndexOf('/') + 1);
var messageViewModel = new MessageViewModel();
var lastVisitedPage = 1;
var lastVisitedPlaylistPage = 1;
var RowNumber;
var SearchData = {};
var SearchDataPlaylist = {};
var DefaultDisplayPage = 3;
var DefaultDisplayPlsylistPage = 3;
var SearchDataClipView = {};
var DefaultDisplayClipView = 3;
var lastVisitedClipView = 1;
var ContentPerPage = 10;
var TableLastSortedColumn = -1;
var space = " ";

var ClippingRepository = {

    getAllMyClipsLoad: function (pageNumber) {

        var object = {
            Data: {
                'logonId': IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
                "pageNumber": pageNumber,
                "pageSize": ContentPerPage
            }
        };
        lastVisitedPage = pageNumber;
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetAllMyClips',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.LoginStatus) {
                    if (ResultStatus.Successful == data.Status && data.ResultObject != null) {

                        if (data.ResultObject.length > 0) {
                            var hdfPlaylistId = 0;
                            if ($("#hdPlaylistId").val() != '') {
                                hdfPlaylistId = $("#hdPlaylistId").val();
                            }
                            else {
                                hdfPlaylistId = 0;
                            }
                            var totalRecords;
                            var contentTableMob = '';
                            var contentTable = '<thead><tr  class="table-heading-background hidden-xs"> ' +
                                '<th style="width:6%;">Select</th>' +
                                '<th style="width:40%;"><span class="myclips-th">Clip Title</span></th>' +
                                '<th style="width:8%;"><span class="myclips-th">Length</span></th>' +
                                '<th style="width:10%;"><span class="myclips-th">Created</span></th>' +
                                '<th style="width:8%;"><span class="myclips-th">Details</span></th>' +
                                '<th style="width:6%;"><span class="myclips-th">Edit</span></th>' +
                                '<th style="width:8%;"><span class="myclips-th">Delete</span></th>' +
                                //'<th>Share</th>' +
                                '<th style="width:8%;text-align:left;"><span class="myclips-th">Email</span></th>';
                            contentTable += '</tr></thead>';
                            $.each(data.ResultObject, function (index, data) {
                                contentTable += '<tr><td class="hidden-xs"><label class="checkbox-container"><input type="checkbox" class="selectClip" id="' + data.ClipId + '" /><span class="myclips-checkbox"></span></label></td>' +
                                    '<td class="hidden-xs" style="text-align:left;padding-left:16px"><a class="text-color font-bold custom_pointer margin-right-15" data-hasindex="true" data-innerroutename="videoid" data-videono="' + data.VideoNo + '" data-clipid="' + data.ClipId + '" data-clip-play=true data-videoId="-1" data-channelid="0" data-videoTitle="" data-Duration="" data-SubscriptionType="" >' + data.Title + '</a></td>' +
                                    '<td class="hidden-xs" style="text-align:left;padding-left:16px">' + data.ClipLength + '</td>' +
                                    '<td class="hidden-xs" style="text-align:left;padding-left:16px">' + data.CreatedOn + '</td>' +
                                    '<td class="hidden-xs"> <a data-toggle="modal" data-target="#viewClipModel" onclick="getMyClipByIdClick(' + data.ClipId + ')"> <span aria-hidden="true" class="custom_pointer" title="View Clip Details"><img src="Images/Details.svg" class="table-icons"></span></a> </td>' +
                                    '<td class="hidden-xs"> <a data-toggle="modal" data-target="#editClipModel" onclick="editMyClipByIdClick(' + data.ClipId + ",'" + data.Title.replace("'", "#") + "'" + ')"> <span aria-hidden="true" class="custom_pointer" title="Edit Clip"><img src="Images/Edit.svg" class="table-icons"></span></a> </td>' +
                                    '<td class="hidden-xs"> <a onclick="deleteMyClipByIdClick(' + data.ClipId + ',' + hdfPlaylistId + ',' + true + ')"> <span aria-hidden="true" class="custom_pointer" title="Delete Clip" ><img src="Images/Closeicon.svg" class="table-icons"></span></a> </td>' +
                                    //'<td class="hidden-xs">  <a class="text-color font-bold custom_pointer margin-right-15" data-hasindex="true" data-innerroutename="videoid" data-videono="' + data.VideoNo + '" data-clipid="' + data.ClipId + '" data-clip-share=true data-videoId="-1" data-channelid="0" data-videoTitle="" data-Duration="" data-SubscriptionType=""><span aria-hidden="true" class="glyphicon glyphicon-share custom_pointer" title="Share Clip"></span> </a> </td>' +
                                    '<td class="hidden-xs">  <a data-toggle="modal" onclick="emailMyClipByIdClick(' + data.ClipId + ',' + true + ')"> <span aria-hidden="true" class="custom_pointer" title="Email Clip"><img src="Images/Email.svg" class="table-icons"></span></a></td>';
                                contentTable += '</tr>';


                                contentTableMob += '<tbody class="col-xs-12 p-0">  <tr class="col-xs-12 p-0 d-table"><td class="width-50"> <b>Select</b> </td> <td class="width-50"><label class="checkbox-container"><input type="checkbox" class="selectClip" id="' + data.ClipId + '" ><span class="myclips-checkbox"></span></label></td></tr>' +
                                    '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Clip Title </b></td><td class="width-50"><a class="text-color font-bold custom_pointer margin-right-15" data-hasindex="true" data-innerroutename="videoid" data-videono="' + data.VideoNo + '" data-clipid="' + data.ClipId + '" data-clip-play="true" data-videoid="-1" data-channelid="0" data-videotitle="" data-duration="" data-subscriptiontype="">' + data.Title + '</a></td> </tr>' +
                                    '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Length</b></td><td class="width-50">' + data.ClipLength + '</td></tr>' +
                                    '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Created</b></td><td class="width-50">' + data.CreatedOn + '</td></tr>' +
                                    '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Details</b> </td><td class="width-50"><a data-toggle="modal" data-target="#viewClipModel" onclick="getMyClipByIdClick(' + data.ClipId + ')"> <span aria-hidden="true" class="custom_pointer" title="View Clip Details"><img src="Images/Details.svg" class="table-icons"></span></a></td></tr>' +
                                    '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Edit</b> </td><td class="width-50"><a data-toggle="modal" data-target="#editClipModel" onclick="editMyClipByIdClick(' + data.ClipId + ",'" + data.Title.replace("'", "#") + "'" + ')"> <span aria-hidden="true" class="custom_pointer" title="Edit Clip"><img src="Images/Edit.svg" class="table-icons"></span></a></td></tr>' +
                                    '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Delete</b></td><td class="width-50"><a onclick="deleteMyClipByIdClick(' + data.ClipId + ',' + hdfPlaylistId + ',' + true + ')"> <span aria-hidden="true" class="custom_pointer" title="Delete Clip"><img src="Images/Closeicon.svg" class="table-icons"></span></a></td></tr>' +
                                    //'<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Share</b></td><td class="width-50"><a class="text-color font-bold custom_pointer margin-right-15" data-hasindex="true" data-innerroutename="videoid"  data-videono="' + data.VideoNo + '" data-clipid="' + data.ClipId + '" data-clip-share="true" data-videoid="-1" data-channelid="0" data-videotitle="" data-duration="" data-subscriptiontype=""><span aria-hidden="true" class="glyphicon glyphicon-share custom_pointer" title="Share Clip"></span> </a></td></tr>' +
                                    '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Email</b></td><td class="width-50"><a data-toggle="modal" onclick="emailMyClipByIdClick(' + data.ClipId + ',' + true + ')"> <span aria-hidden="true" class="custom_pointer" title="Email Clip"><img src="Images/Email.svg" class="table-icons"></span></a></td></tr>';
                                contentTableMob += '</tbody>';

                                totalRecords = data.TotalRecords;
                                RowNumber = data.RowNumber;
                            });
                            $('#myClipsTable thead').remove();
                            $('#myClipsTable tbody').remove();
                            $('#myClipsTable').append(contentTable);
                            $('#myClipsTable').tablesorter().trigger('updateAll');

                            $('#myClipsTableMob thead').remove();
                            $('#myClipsTableMob tbody').remove();
                            $('#myClipsTableMob').append(contentTableMob);
                            $('#myClipsTableMob').tablesorter().trigger('updateAll');

                            RemoveHeaderSorting();

                            $("#btnAddToPlaylist").show();
                            SearchData = {
                                TotalRecords: totalRecords,
                                DisplayPages: totalRecords / ContentPerPage
                            }
                            if (SearchData.TotalRecords <= 10 && SearchData.TotalRecords >= 1) {
                                DefaultDisplayPage = 1;
                            }
                            else if (SearchData.TotalRecords > 10 && SearchData.TotalRecords <= 20) {
                                DefaultDisplayPage = 2;
                            }
                            else if (SearchData.TotalRecords > 20) {
                                DefaultDisplayPage = 3;
                            }
                            $("#pagenoClip").html("<p>page " + pageNumber + " of " + Math.ceil(SearchData.DisplayPages) + "</p>");

                            if (localStorage.getItem("IsRecordFirstLoaded") == "0") {
                                $(".pageNavigation").twbsPagination({
                                    totalPages: Math.ceil(SearchData.DisplayPages),
                                    start: 1,
                                    visiblePages: DefaultDisplayPage,
                                    onPageClick: function (event, page) {
                                        TableLastSortedColumn = -1;
                                        localStorage.setItem("IsRecordFirstLoaded", "1");
                                        ClippingRepository.getAllMyClipsLoad(page);
                                    }
                                });
                            }

                            RouteProvider.bindInnerRoutes();
                        }
                        else {
                            $('#myClipsTable').removeClass("tablesorter-default");//Fix for PS - 1362: IET TV: After deleting a record from playlist, the No Record found text is visible with a white background:Remove table-sorter class.
                            $('#myClipsTable').append("No records found.");
                            $("#btnAddToPlaylist").hide();
                        }
                    }
                    else {
                        $('#myClipsTable').removeClass("tablesorter-default");//Fix for PS - 1362: IET TV: After deleting a record from playlist, the No Record found text is visible with a white background:Remove table-sorter class.
                        $('#myClipsTable').append("No records found.");
                        $("#btnAddToPlaylist").hide();
                    }
                }
            },
            function (data, status, headers, config) {
                $('#myClipsTable').removeClass("tablesorter-default");//Fix for PS - 1362: IET TV: After deleting a record from playlist, the No Record found text is visible with a white background:Remove table-sorter class.
                $('#myClipsTable').append("No records found.");
                $("#btnAddToPlaylist").hide();
            }, JSON.stringify(object.Data));

    },
    saveClip: function (object) {
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/SaveMyClipById',
            function (data, status, headers, config) {
                if (data.ResultObject != null && data.ResultObject == true) {
                    ClippingRepository.getAllMyClipsLoad(lastVisitedPage);
                    ClippingRepository.getAllMyPlaylistLoad(true, lastVisitedPlaylistPage);
                    $('#editClipModel').modal('hide');
                    messageViewModel.CreateSuccessMessage(space +"Clip title updated successfully", "overlayId", "okButtonId");
                    messageViewModel.ShowOverLay();
                }

            }, function (data, status, headers, config) {
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data))
    },

    addToMyPlaylist: function (object) {
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/AddToMyPlaylist',
            function (data, status, headers, config) {
                if (data.ResultObject != null && data.ResultObject > 0) {
                    ClippingRepository.getAllMyPlaylistLoad(true, lastVisitedPlaylistPage);
                    messageViewModel.CreateSuccessMessage(space +"Clip(s) added to playlist successfully", "overlayId", "okButtonId");
                    messageViewModel.ShowOverLay();
                    $('#playlist').modal('hide');
                }
                else if (data.ResultObject != null && data.ResultObject == -1) {
                    messageViewModel.CreateWarningMessage(space +"Clip(s) added to playlist successfully and duplicates have been eliminated.", "overlayId", "okButtonId");
                    messageViewModel.ShowOverLay();
                    $('#playlist').modal('hide');
                }
                else if (data.ResultObject != null && data.ResultObject == -2) {
                    messageViewModel.CreateErrorMessage(space +"Playlist name already exists. Please enter new playlist name.");
                    messageViewModel.ShowOverLay();
                    $('#playlist').modal('hide');
                }

            }, function (data, status, headers, config) {
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data))
    },

    getAllMyPlaylistLoad: function (isPlaylistTab, pageNumber) {
        var object = {
            Data: {
                'logonId': IsNullOrEmpty(sessionStorage.getItem("LogonId")) ? GUID() : sessionStorage.getItem("LogonId"),
                "pageNumber": pageNumber,
                "pageSize": ContentPerPage,
                "isPlaylistTab": isPlaylistTab
            }
        };
        lastVisitedPlaylistPage = pageNumber;
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetMyPlaylist',
            function (data, status, headers, config) {
                if (isPlaylistTab == true) {
                    if (ResultStatus.Successful == data.LoginStatus) {
                        if (ResultStatus.Successful == data.Status && data.ResultObject != null) {
                            if (data.ResultObject.length > 0) {
                                //Fix for PS - 1307: IET TV: "No records" label is displayed in playlist tab if a new user adds a clip in a newly created playlist first time start
                                $('#myPlaylistTable,#myPlaylistTableMob,#myPlaylistTableDetailsEdit').html("");//Remove "No records" text from playlist table
                                //PS - 1307: IET TV: "No records" label is displayed in playlist tab if a new user adds a clip in a newly created playlist first time End
                                var totalRecords;
                                var contentTableMob = '';
                                var contentTable = '<thead><tr class="table-heading-background hidden-xs">' +
                                    '<th style="width:30%;">Playlist Name</th>' +
                                    '<th style="width:30%;">No Of Videos </th>' +
                                    '<th style="width:10%;">Details</th>' +
                                    '<th style="width:10%;">Edit</th>' +
                                    '<th style="width:10%;">Delete</th>' +
                                    '<th style="width:10%;">Email Playlist</th>';
                                contentTable += '</tr></thead>';
                                $.each(data.ResultObject, function (index, data) {
                                    contentTable +=
                                        '<tr><td class="hidden-xs" style="text-align:left;padding-left:16px">' + data.PlaylistName + '</td>' +
                                        '<td class="hidden-xs" style="text-align:left;padding-left:16px">' + data.NoOfVideos + '</td>' +
                                        '<td class="hidden-xs"> <a href="#tabMyPlaylistDetailsView" data-toggle="tab" onclick="getMyClipsByPlaylistIdClick(' + data.PlaylistId + ",'" + data.PlaylistName + "'" + ", false, 1, true" + ')"> <span aria-hidden="true" class="custom_pointer" title="View Playlist Details"><img src="Images/Details.svg" class="table-icons"></span></a></td>' +
                                        '<td class="hidden-xs"> <a href="#tabMyPlaylistDetailsEdit" data-toggle="tab" onclick="getMyClipsByPlaylistIdClick(' + data.PlaylistId + ",'" + data.PlaylistName + "'" + ", true, 1, true" + ')">  <span aria-hidden="true" class="custom_pointer" title="Edit Playlist"><img src="Images/Edit.svg" class="table-icons"></span></a> </td>' +
                                        '<td class="hidden-xs">  <a href="javascript:void()" onclick="deleteMyPlaylistClick(' + data.PlaylistId + ')"> <span aria-hidden="true" class="custom_pointer" title="Delete Playlist"><img src="Images/Closeicon.svg" class="table-icons"></span> </a> </td>' +
                                        '<td class="hidden-xs"><a data-toggle="modal" onclick="emailMyClipByIdClick(' + data.PlaylistId + ',' + false + ')"> <span aria-hidden="true" class="custom_pointer" title="Email Playlist"><img src="Images/Email.svg" class="table-icons"></span></a> </td>';
                                    contentTable += '</tr>';

                                    contentTableMob += '<tbody class="col-xs-12 p-0"> <tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Playlist Name</b></td><td class="width-50">' + data.PlaylistName + '</td></tr>' +
                                        '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>No Of Videos</b></td><td class="width-50">' + data.NoOfVideos + '</td></tr>' +
                                        '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Details</b></td><td class="width-50"><a data-toggle="tab" href="#tabMyPlaylistDetailsView" onclick="getMyClipsByPlaylistIdClick(' + data.PlaylistId + ",'" + data.PlaylistName + "'" + ", false, 1, true" + ')"> <span aria-hidden="true" class="custom_pointer" title="View Playlist Details"><img src="Images/Details.svg" class="table-icons"></span></a></td></tr>' +
                                        '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Edit</b></td><td class="width-50"><a  href="#tabMyPlaylistDetailsEdit" data-toggle="tab" onclick="getMyClipsByPlaylistIdClick(' + data.PlaylistId + ",'" + data.PlaylistName + "'" + ", true, 1, true" + ')"> <span aria-hidden="true" class="custom_pointer" title="Edit Playlist"><img src="Images/Edit.svg" class="table-icons"></span></a></td></tr>' +
                                        '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Delete</b></td><td class="width-50"><a href="javascript:void()" onclick="deleteMyPlaylistClick(' + data.PlaylistId + ')"> <span aria-hidden="true" class="custom_pointer" title="Delete Playlist"><img src="Images/Closeicon.svg" class="table-icons"></span></a></td></tr>' +
                                        '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Email Playlist</b></td><td class="width-50"><a data-toggle="modal" onclick="emailMyClipByIdClick(' + data.PlaylistId + ',' + false + ')"> <span aria-hidden="true" class="custom_pointer" title="Email Playlist"><img src="Images/Email.svg" class="table-icons"></span></a></td></tr>';
                                    contentTableMob += '</tbody>';

                                    totalRecords = data.TotalRecords;
                                    RowNumber = data.RowNumber;
                                });
                                RouteProvider.bindInnerRoutes();

                                $('#myPlaylistTable thead').remove();
                                $('#myPlaylistTable tbody').remove();
                                $('#myPlaylistTable').append(contentTable);
                                $('#myPlaylistTable').tablesorter().trigger('updateAll');

                                $('#myPlaylistTableMob thead').remove();
                                $('#myPlaylistTableMob tbody').remove();
                                $('#myPlaylistTableMob').append(contentTableMob);
                                $('#myPlaylistTableMob').tablesorter().trigger('updateAll');

                                RemoveHeaderSorting();

                                SearchDataPlaylist = {
                                    TotalRecords: totalRecords,
                                    DisplayPages: totalRecords / ContentPerPage
                                }
                                if (SearchDataPlaylist.TotalRecords <= 10 && SearchDataPlaylist.TotalRecords >= 1) {
                                    DefaultDisplayPlsylistPage = 1;
                                }
                                else if (SearchDataPlaylist.TotalRecords > 10 && SearchDataPlaylist.TotalRecords <= 20) {
                                    DefaultDisplayPlsylistPage = 2;
                                }
                                else if (SearchDataPlaylist.TotalRecords > 20) {
                                    DefaultDisplayPlsylistPage = 3;
                                }
                                $("#pagenoPlaylist").html("<p>page " + pageNumber + " of " + Math.ceil(SearchDataPlaylist.DisplayPages) + "</p>");

                                if (localStorage.getItem("IsRecordFirstLoaded") == "0") {
                                    $(".pageNavigationPlaylist").twbsPagination({
                                        totalPages: Math.ceil(SearchDataPlaylist.DisplayPages),
                                        start: 1,
                                        visiblePages: DefaultDisplayPlsylistPage,
                                        onPageClick: function (event, page) {
                                            TableLastSortedColumn = -1;
                                            localStorage.setItem("IsRecordFirstLoaded", "1");
                                            ClippingRepository.getAllMyPlaylistLoad(true, page);
                                        }
                                    });
                                }
                            }
                            else {
                                $('#myPlaylistTable').removeClass("tablesorter-default");//Fix for PS - 1362: IET TV: After deleting a record from playlist, the No Record found text is visible with a white background:Remove table-sorter class.
                                $('#myPlaylistTable,#myPlaylistTableMob').html("No records found.");
                            }
                        }
                        else {
                            $('#myPlaylistTable').removeClass("tablesorter-default");//Fix for PS - 1362: IET TV: After deleting a record from playlist, the No Record found text is visible with a white background:Remove table-sorter class.
                            $('#myPlaylistTable, #myPlaylistTableMob').html("No records found.");
                        }
                    }
                }
                else {
                    $('#ddlPlaylist').empty();
                    if (data.ResultObject != null) {
                        $('#ddlPlaylist').append($('<option>', {
                            value: 0,
                            text: 'Select Playlist'
                        }));
                        $.each(data.ResultObject, function (i, item) {
                            $('#ddlPlaylist').append($('<option>', {
                                value: item.PlaylistId,
                                text: item.PlaylistName
                            }));
                        });
                    }
                    else {
                        $('#ddlPlaylist').append($('<option>', {
                            value: 0,
                            text: 'Select Playlist'
                        }));
                    }
                }
            }, function (data, status, headers, config) {
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data))
    },

    savePlaylist: function (object) {
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/SaveMyPlaylistByPlaylistId',
            function (data, status, headers, config) {
                if (data.ResultObject != null && data.ResultObject == true) {
                    $('#txtPlaylistNameEdit').removeClass('required-field');
                    messageViewModel.CreateSuccessMessage(space +" Playlist saved successfully", "overlayId", "okButtonId");
                    messageViewModel.ShowOverLay();
                    ClippingRepository.getAllMyPlaylistLoad(true, lastVisitedPlaylistPage);
                    $("#hdPlaylistName").val(object.Data.playlist.PlaylistName);
                    $('#txtPlaylistNameEdit').val(object.Data.playlist.PlaylistName);
                }
            }, function (data, status, headers, config) {
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data))
    },

    sendEmail: function (clipId, playlistId, lstuser) {
        var object = {
            Data: {
                'useremailId': lstuser,
                'clipId': clipId,
                'playlistId': playlistId,
                'userName': localStorage.getItem("UserName"),
                'portalUrl': currentURL
            }
        };

        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/SendEmailNotificationForClip',
            function (data, status, headers, config) {
                if (data.ResultObject != null && data.ResultObject == true) {
                    messageViewModel.CreateSuccessMessage(space +"Mail sent successfully.", "overlayId", "okButtonId");
                    messageViewModel.ShowOverLay();
                }
                else if (data.ResultObject != null && data.ResultObject == false) {
                    messageViewModel.CreateInfoMessage(space +"There are no clips in this playlist to email.", "overlayId", "okButtonId");
                    messageViewModel.ShowOverLay();
                }
            }, function (data, status, headers, config) {
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify(object.Data))
    }
}

function getMyClipByIdClick(clipId) {
    var object = {
        Data: {
            'clipId': clipId
        }
    };

    Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetMyClipById',
        function (data, status, headers, config) {
            if (ResultStatus.Successful == data.LoginStatus) {
                if (ResultStatus.Successful == data.Status && data.ResultObject != null) {
                    var videoLink = currentURL + "EmbedPlayer.aspx?videoid=" + data.ResultObject.VideoNo + "&st=" + data.ResultObject.StartTime + "&et=" + data.ResultObject.EndTime;

                    var playlistName = '';
                    if (data.ResultObject.PlaylistName != null) {
                        playlistName = data.ResultObject.PlaylistName;
                    }
                    var embedLink = embedLink = '<iframe width="550" height="310" class="embedLink" name="azuremediaplayer" src="' + videoLink + '" allowfullscreen></iframe>';;
                    embedLink = embedLink.replace('<', '&lt;');
                    embedLink = embedLink.replace('>', '/&gt;');

                    var contentTable =
                        '<tr><td><b>Clip Title:</b></td> <td> ' + data.ResultObject.Title + '</td></tr>' +
                        '<tr><td><b>Duration:</b></td> <td> ' + data.ResultObject.Duration + '</td></tr>' +
                        '<tr><td><b>Start Time:</b></td> <td> ' + data.ResultObject.StartTime + '</td></tr>' +
                        '<tr><td><b>End Time:</b></td> <td>' + data.ResultObject.EndTime + ' </td></tr>' +
                        '<tr><td><b>Playlist Name:</b></td> <td> ' + playlistName + ' </td></tr>' +
                        '<tr><td><b>Video Link:</b></td> <td>' + videoLink + '  </td></tr>' +
                        '<tr><td><b>Embed Link:</b></td>  <td>' + embedLink + '</td></tr>';

                    $('#tableClipDetails').html(contentTable);
                }
            }
        },
        function (data, status, headers, config) {

        }, JSON.stringify(object.Data));


}

function editMyClipByIdClick(clipId, clipTitle) {
    
    $('#txtclipTitle').removeClass('required-field');
    clipTitle = clipTitle.replace("#", "'");
    $("#txtclipTitle").val(clipTitle);
    $("#hdClipId").val(clipId);
}

function deleteMyClipByIdClick(clipId, playlistId, flag) {
    var object = {
        Data: {
            'clipId': clipId, 'playlistId': playlistId, 'flag': flag
        }
    };
    if (flag == false) {
        messageViewModel.CreateConfirmationMessageWithOKCancel("Are you sure you want to delete clip from the playlist?", "overlayId", "okButtonId", "cancelButtonId", function () {
            $('#okButtonId').unbind('click');
            $('#okButtonId').bind('click', function () {
                //$("#cancelButtonId").click();
                deleteMyClip(object.Data);
                getMyClipsByPlaylistIdClick($("#hdPlaylistId").val(), $("#hdPlaylistName").val(), true, lastVisitedClipView, false);
                ClippingRepository.getAllMyPlaylistLoad(true, lastVisitedPlaylistPage);
            });
        });
        messageViewModel.ShowOverLay();
    }
    else {
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/checkClipExistsInPlaylistByClipId',
            function (data, status, headers, config) {
                if (data.ResultObject != null && data.ResultObject > 0) {
                    //if clip exists in playlist
                    messageViewModel.CreateConfirmationMessageWithOKCancel("This clip exists in playlist, are you sure you still want to delete clip?", "overlayId", "okButtonId", "cancelButtonId", function () {
                        $('#okButtonId').unbind('click');
                        $('#okButtonId').bind('click', function () {
                            //$("#cancelButtonId").click();
                            deleteMyClip(object.Data);
                            ClippingRepository.getAllMyClipsLoad(lastVisitedPage);
                            ClippingRepository.getAllMyPlaylistLoad(true, lastVisitedPlaylistPage);
                        });
                    });

                }
                else {
                    //if clip does not exists in playlist
                    messageViewModel.CreateConfirmationMessageWithOKCancel("Are you sure you want to delete the clip?", "overlayId", "okButtonId", "cancelButtonId", function () {
                        $('#okButtonId').unbind('click');
                        $('#okButtonId').bind('click', function () {
                            //$("#cancelButtonId").click();
                            deleteMyClip(object.Data);
                            ClippingRepository.getAllMyClipsLoad(lastVisitedPage);
                        });
                    });
                }
                messageViewModel.ShowOverLay();
            }, function (data, status, headers, config) {
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            }, JSON.stringify({ 'clipId': clipId }))
    }
}

function deleteMyClip(data) {
    Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/DeleteMyClip',
        function (data, status, headers, config) {
            if (data.ResultObject != null && data.ResultObject == true) {
                messageViewModel.CreateSuccessMessage(space +"Clip deleted successfully", "overlayId", "okButtonId");
                messageViewModel.ShowOverLay();
            }

        }, function (data, status, headers, config) {
            messageViewModel.CreateErrorMessage(data);
            messageViewModel.ShowOverLay();
        }, JSON.stringify(data))

}

function getMyClipsByPlaylistIdClick(playlistId, playlistName, isEdit, pageNumber, reloadPage) {
    if (reloadPage) {
        localStorage.setItem("IsRecordFirstLoaded", "0");
    }
    var object = {
        Data: {
            'playlistId': playlistId,
            "pageNumber": pageNumber,
            "pageSize": ContentPerPage
        }
    };
    lastVisitedClipView = pageNumber;

    $('#txtPlaylistNameEdit').removeClass('required-field');
    $("#hdPlaylistId").val(playlistId);
    $("#hdPlaylistName").val(playlistName);
    Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetMyClipByPlaylistId',
        function (data, status, headers, config) {
            if (data.ResultObject != null && data.ResultObject.length > 0) {
                var totalRecords;
                var hdfPlaylistId = 0;
                if ($("#hdPlaylistId").val() != '') {
                    hdfPlaylistId = $("#hdPlaylistId").val();
                }
                else {
                    hdfPlaylistId = 0;
                }
                var tableName = "";
                if (isEdit)
                    tableName = "'myPlaylistTableDetailsEdit'";
                else
                    tableName = "'myPlaylistTableDetailsView'";
                var contentTableMob = '';
                var contentTable = '<thead><tr class="table-heading-background hidden-xs">' +
                    '<th>Clip Title  </th>' +
                    '<th>Video No</th>' +
                    '<th>Video Link</th>'
                if (isEdit) {
                    contentTable += '<th>Remove</th>';
                }
                contentTable += '</tr></thead>';


                $.each(data.ResultObject, function (index, data) {
                    var videoLink = currentURL + "EmbedPlayer.aspx?videoid=" + data.VideoNo + "&st=" + data.StartTime + "&et=" + data.EndTime;
                    contentTable += '<tr>' +
                        '<td class="hidden-xs"> <a class="text-color font-bold custom_pointer margin-right-15" data-hasindex="true" data-innerroutename="videoid" data-videono="' + data.VideoNo + '" data-clipid="' + data.ClipId + '" data-clip-play=true data-videoId="-1" data-channelid="0" data-videoTitle="" data-Duration="" data-SubscriptionType="" >' + data.Title + '</a></td>' +
                        '<td class="hidden-xs">' + data.VideoNo + '</td>' +
                        '<td class="hidden-xs">' + videoLink + '</td>'

                    contentTableMob += '<tbody class="col-xs-12 p-0">' +
                        '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Clip Title </b></td><td class="width-50"><a class="text-color font-bold custom_pointer margin-right-15" data-hasindex="true" data-innerroutename="videoid" data-videono="' + data.VideoNo + '" data-clipid="' + data.ClipId + '" data-clip-play="true" data-videoid="-1" data-channelid="0" data-videotitle="" data-duration="" data-subscriptiontype="">' + data.Title + '</a></td> </tr>' +
                        '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Video No</b></td><td class="width-50">' + data.VideoNo + '</td></tr>' +
                        '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Video Link</b></td><td class="width-50 word-break">' + videoLink + '</td></tr>';
                    if (isEdit) {
                        contentTable += '<td class="hidden-xs"> <span><a href="javascript:void()" onclick="deleteMyClipByIdClick(' + data.MappingId + ',' + hdfPlaylistId + ',' + false + ')"><span aria-hidden="true" class="" title="Remove Clip"><img src="Images/Closeicon.svg" class="table-icons"></span></a></span></td>'
                        contentTableMob += '<tr class="col-xs-12 p-0 d-table"><td class="width-50"><b>Remove</b></td><td class="width-50"><span><a href="javascript:void()" onclick="deleteMyClipByIdClick(' + data.MappingId + ',' + hdfPlaylistId + ',' + false + ')"><span aria-hidden="true" class="" title="Remove Clip"><img src="Images/Closeicon.svg" class="table-icons"></span></a></span></td></tr>';
                    }
                    contentTable += '</tr>';
                    contentTableMob += '</tbody>';

                    totalRecords = data.TotalRecords;
                    RowNumber = data.RowNumber;
                });
                SearchDataClipView = {
                    TotalRecords: totalRecords,
                    DisplayPages: totalRecords / ContentPerPage
                }
                if (SearchDataClipView.TotalRecords <= 10 && SearchDataClipView.TotalRecords >= 1) {
                    DefaultDisplayClipView = 1;
                }
                else if (SearchDataClipView.TotalRecords > 10 && SearchDataClipView.TotalRecords <= 20) {
                    DefaultDisplayClipView = 2;
                }
                else if (SearchDataClipView.TotalRecords > 20) {
                    DefaultDisplayClipView = 3;
                }
                if (isEdit) {
                    $('#myPlaylistTableDetailsEdit thead').remove();
                    $('#myPlaylistTableDetailsEdit tbody').remove();
                    $('#myPlaylistTableDetailsEdit').append(contentTable);
                    $('#myPlaylistTableDetailsEdit').tablesorter().trigger('updateAll');

                    $('#myPlaylistTableDetailsEditMob thead').remove();
                    $('#myPlaylistTableDetailsEditMob tbody').remove();
                    $('#myPlaylistTableDetailsEditMob').append(contentTableMob);
                    $('#myPlaylistTableDetailsEditMob').tablesorter().trigger('updateAll');


                    $("#pgPlaylistDetailEdit").addClass("pagination-panel");
                    $("#pagenoClipEdit").html("<p>page " + pageNumber + " of " + Math.ceil(SearchDataClipView.DisplayPages) + "</p>");
                    if (localStorage.getItem("IsRecordFirstLoaded") == "0") {
                        $(".pageNavigationClipsEdit").twbsPagination({
                            totalPages: Math.ceil(SearchDataClipView.DisplayPages),
                            start: 1,
                            visiblePages: DefaultDisplayClipView,
                            onPageClick: function (event, page) {
                                TableLastSortedColumn = -1;
                                localStorage.setItem("IsRecordFirstLoaded", "1");
                                $('#txtPlaylistNameEdit').val($("#hdPlaylistName").val());
                                getMyClipsByPlaylistIdClick(playlistId, $("#hdPlaylistName").val(), isEdit, page, false);

                            }
                        });
                    }
                    // $("#dvplaylistheaderEdit").show();
                    // $("#btnSavePlaylist").show();
                } else {
                    $('#myPlaylistTableDetailsView thead').remove();
                    $('#myPlaylistTableDetailsView tbody').remove();
                    $('#myPlaylistTableDetailsView').append(contentTable);
                    $('#myPlaylistTableDetailsView').tablesorter().trigger('updateAll');

                    $('#myPlaylistTableDetailsViewMob thead').remove();
                    $('#myPlaylistTableDetailsViewMob tbody').remove();
                    $('#myPlaylistTableDetailsViewMob').append(contentTableMob);
                    $('#myPlaylistTableDetailsViewMob').tablesorter().trigger('updateAll');

                    $("#pgPlaylistDetailView").addClass("pagination-panel");
                    $("#pagenoClipView").html("<p>page " + pageNumber + " of " + Math.ceil(SearchDataClipView.DisplayPages) + "</p>");
                    if (localStorage.getItem("IsRecordFirstLoaded") == "0") {
                        $(".pageNavigationClipsView").twbsPagination({
                            totalPages: Math.ceil(SearchDataClipView.DisplayPages),
                            start: 1,
                            visiblePages: DefaultDisplayClipView,
                            onPageClick: function (event, page) {
                                TableLastSortedColumn = -1;
                                localStorage.setItem("IsRecordFirstLoaded", "1");
                                getMyClipsByPlaylistIdClick(playlistId, playlistName, isEdit, page, false);
                            }
                        });
                    }
                    // $("#dvplaylistheaderView").show();
                }
                RemoveHeaderSorting();
                RouteProvider.bindInnerRoutes();
            }
            else {
                if (isEdit) {
                    $('#myPlaylistTableDetailsEdit').removeClass("tablesorter-default");//Fix for PS - 1362: IET TV: After deleting a record from playlist, the No Record found text is visible with a white background:Remove table-sorter class.
                    $('#myPlaylistTableDetailsEdit').html("No records found.");
                    $('#myPlaylistTableDetailsEditMob').html("");
                    $(".pageNavigationClipsEdit").html("");
                    $("#pgPlaylistDetailEdit").removeClass("pagination-panel");
                    $("#pagenoClipEdit").html("");
                    //$("#dvplaylistheaderEdit").hide();
                    // $("#btnSavePlaylist").hide();
                } else {
                    $('#myPlaylistTableDetailsView').removeClass("tablesorter-default");//Fix for PS - 1362: IET TV: After deleting a record from playlist, the No Record found text is visible with a white background:Remove table-sorter class.
                    $('#myPlaylistTableDetailsView').html("No records found.");
                    $('#myPlaylistTableDetailsViewMob').html("");
                    $(".pageNavigationClipsView").html("");
                    $("#pgPlaylistDetailView").removeClass("pagination-panel");
                    $("#pagenoClipView").html("");
                    // $("#dvplaylistheaderView").hide();
                }
            }
            if (isEdit) {
                $("#txtPlaylistNameEdit").val(playlistName);
            }
            else {
                $("#lblPlaylistName").html(playlistName);
            }
            $("#btnPlaylistDetails").removeClass("hidden");
            $("#btnMyPlaylist").removeClass("active");
            $("#btnPlaylistDetails").addClass("active");
            BindMyClipsClick();
            BindMyPlaylistClick();
        }, function (data, status, headers, config) {
            messageViewModel.CreateErrorMessage(data);
            messageViewModel.ShowOverLay();
        }, JSON.stringify(object.Data))
}

function deleteMyPlaylistClick(playlistId) {
    var object = {
        Data: { 'playlistId': playlistId }
    };
    Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetClipsCountInPlaylistById',
        function (data, status, headers, config) {
            if (data.ResultObject != null && data.ResultObject > 0) {
                //if there are clips inside the playlist
                messageViewModel.CreateConfirmationMessageWithOKCancel("There are clips inside this playlist, are you sure you still want to delete playlist?", "overlayId", "okButtonId", "cancelButtonId", function () {
                    $('#okButtonId').unbind('click');
                    $('#okButtonId').bind('click', function () {
                        //$("#cancelButtonId").click();
                        deleteMyPlaylist(object.Data);
                        ClippingRepository.getAllMyPlaylistLoad(true, lastVisitedPlaylistPage);
                    });
                });
            }
            else {
                messageViewModel.CreateConfirmationMessageWithOKCancel("Are you sure you want to delete playlist?", "overlayId", "okButtonId", "cancelButtonId", function () {
                    $('#okButtonId').unbind('click');
                    $('#okButtonId').bind('click', function () {
                        //$("#cancelButtonId").click();
                        deleteMyPlaylist(object.Data);
                        ClippingRepository.getAllMyPlaylistLoad(true, lastVisitedPlaylistPage);
                    });
                });
            }
            messageViewModel.ShowOverLay();
        }, function (data, status, headers, config) {
            messageViewModel.CreateErrorMessage(data);
            messageViewModel.ShowOverLay();
        }, JSON.stringify(object.Data))

}

function deleteMyPlaylist(data) {
    Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/DeleteMyPlaylist',
        function (data, status, headers, config) {
            if (data.ResultObject != null && data.ResultObject == true) {
                messageViewModel.CreateSuccessMessage(space +"Playlist deleted successfully", "overlayId", "okButtonId");
                messageViewModel.ShowOverLay();
            }
        }, function (data, status, headers, config) {
            messageViewModel.CreateErrorMessage(data);
            messageViewModel.ShowOverLay();
        }, JSON.stringify(data))

}

function emailMyClipByIdClick(Id, isClip) {
    //var check = $('input[type=checkbox]:checked').length;
    //var checkedIds = $(".selectClip:checked").map(function () {
    //    return this.id;
    //}).toArray();

    //if (check == 1) {
    //    if (checkedIds != clipId) {
    //        messageViewModel.CreateErrorMessage("Please select the clip that you want to email.");
    //        messageViewModel.ShowOverLay();
    //        return false;
    //    }
    $("#hdEmailClipId").val(0);
    $("#hdEmailPlaylistId").val(0)

    $('#emailModel').modal('show');
    if (isClip)
        $("#hdEmailClipId").val(Id);
    else
        $("#hdEmailPlaylistId").val(Id);

    $('#txtemail').removeClass('required-field');
    $("#listView").empty();
    $("#txtemail").val('');
    BindAddEmailAddressClick();
    //}
    //else {
    //    if (check == 0) {
    //        messageViewModel.CreateErrorMessage("Please select at least one clip to email.");
    //        messageViewModel.ShowOverLay();
    //    }
    //    else {
    //        messageViewModel.CreateErrorMessage("Please select any one clip to email.");
    //        messageViewModel.ShowOverLay();
    //    }
    //}
}

function RemoveHeaderSorting() {
    $("th:contains(Select)").removeClass("tablesorter-header");
    $("th:contains(Length)").removeClass("tablesorter-header");
    $("th:contains(Details)").removeClass("tablesorter-header");
    $("th:contains(Edit)").removeClass("tablesorter-header");
    $("th:contains(Delete)").removeClass("tablesorter-header");
    $("th:contains(Email)").removeClass("tablesorter-header");
    $("th:contains(Video Link)").removeClass("tablesorter-header");
    $("th:contains(Video No)").removeClass("tablesorter-header");
    $("th:contains(Remove)").removeClass("tablesorter-header");



}



var LandingPageRepository = function () {
    this.GetVideoAndTranscriptVideoCount = function (currentRouteSetting, routeProvider, routeCurrentContext) {
        //alert('Hi');
        var logonId = BrowserStorage.getLogonId();
        Repository.LoadDataJSON(WebService.BaseURL + 'VideoManagement/VideoService.svc/GetVideoAndTranscriptVideoCount',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    $("#searchtextbox").val('');
                    $('#searchtextbox').datepicker('destroy');
                    $('#mobsearchtxtbox').datepicker('destroy');
                    $("#mobsearchtxtbox").val('');
                    $("#TotalVideoCount").text(data.ResultObject.VideoCount);
                    $("#TranscriptVideoCount").text(data.ResultObject.TranscriptVideoCount);
                    localStorage.setItem("eviSearchRoute", false);

                    if (!WebService.DisableGA) {
                        storeurlDetailsInGA('Home');
                    }
                }
            }
            ,
                function (data, status, headers, config) {
                    Spinner.Stop();
                    var messageViewModel = new MessageViewModel();
                    messageViewModel.CreateErrorMessage(data);
                    messageViewModel.ShowOverLay();

                }, JSON.stringify(''));

        var IsEmergencyShown = IsNullOrEmpty(sessionStorage.getItem("IsEmergencyShown")) ? false : sessionStorage.getItem("IsEmergencyShown");
        var EmergencyId = IsNullOrEmpty(sessionStorage.getItem("EmergencyId")) ? 0 : sessionStorage.getItem("EmergencyId")

        if (IsEmergencyShown == false || EmergencyId != 0) {
            var objLoginRepository = new LoginRepository();
            objLoginRepository.EmergencyInformation();
        }
        //New Login message code
        this.loginMessage = function (jsonData) {
            var object = {
                Data: { "logonId": BrowserStorage.getLogonId() }
            };
            var enablePopup = BrowserStorage.getLoginPopup();
            if (localStorage.getItem("IsTermsAndConditionsAccepted") != true && (sessionStorage.getItem("IsIPLogin") == "true")) {
                object.Data = { "logonId": sessionStorage.getItem("LogonId") };
            }
            Repository.LoadDataJSON(WebService.BaseURL + 'LogonService.svc/CorporateInstitutionLogo',
                       function (data, status, headers, config) {
                           if (data.Status == ResultStatus.Successful && data.LoginStatus == ResultStatus.Successful && data.ResultObject != null) {
                               var logindetails = data.ResultObject;
                               this.CurrentLoginDetails = {
                                   EmailAddress: logindetails.EmailAddress,
                                   filepath: logindetails.filepath,
                                   AccountName: logindetails.AccountName,
                                   welcomeNotification: logindetails.welcomeNotification,
                                   FirstName: logindetails.FirstName,
                                   LastName: logindetails.LastName,
                                   SubscriptionCount: logindetails.SubscriptionCount,
                                   IsIETMember: logindetails.IsIETMember,
                                   AccountTypeId: logindetails.AccountTypeId
                               };

                               if (localStorage.getItem("AccountType") == "Corporate" || localStorage.getItem("AccountType") == "Institution") {
                                   if (sessionStorage.getItem("IsIPLogin") == "false" || sessionStorage.getItem("IsIPLogin") == null) {
                                       if (localStorage.getItem("CorporateUserType") == 0 || localStorage.getItem("CorporateUserType") == 2) {
                                           _this.getwelcomeTextAndLogo(CurrentLoginDetails.filepath, CurrentLoginDetails.EmailAddress);
                                           _this.welcomeNotification(CurrentLoginDetails.welcomeNotification);
                                           $('#btn_access_details').hide();
                                           if (!enablePopup || enablePopup == false || typeof enablePopup === 'undefined') {
                                               _this.showLoginPopUp(CurrentLoginDetails.EmailAddress);
                                           }
                                       }//end of corporate/inst non admin

                                           //for admin user
                                       else if (localStorage.getItem("CorporateUserType") == 1) {
                                           _this.getwelcomeTextAndLogo(CurrentLoginDetails.filepath, CurrentLoginDetails.EmailAddress);
                                           _this.welcomeNotification(CurrentLoginDetails.welcomeNotification);
                                           _this.accessDetailButton(CurrentLoginDetails.SubscriptionCount);
                                           if (!enablePopup || enablePopup == false || typeof enablePopup === 'undefined') {
                                               _this.showLoginPopUp(CurrentLoginDetails.EmailAddress);
                                           }
                                       }//end of admin
                                   }//end of non ip

                                       //for ip
                                   else if (sessionStorage.getItem("IsIPLogin") == "true") {
                                       _this.getwelcomeTextAndLogo(CurrentLoginDetails.filepath, localStorage.getItem("Welcome"));
                                       _this.welcomeNotification(CurrentLoginDetails.welcomeNotification);
                                       $('#btn_access_details').hide();
                                       if (!enablePopup || enablePopup == false || typeof enablePopup === 'undefined') {
                                           _this.showLoginPopUp(localStorage.getItem("Welcome"));
                                       }

                                   }//end of ip
                               }//end of corporate/institution

                                   //for individual
                               else if (localStorage.getItem("IsIndividualUser") == "true") {
                                   $('#message_head').text('You have logged in as: ' + CurrentLoginDetails.FirstName + " " + CurrentLoginDetails.LastName);
                                   $('#user_logo').hide();
                                   _this.welcomeNotification(CurrentLoginDetails.welcomeNotification);
                                   _this.accessDetailButton(CurrentLoginDetails.SubscriptionCount);
                                   if (!enablePopup || enablePopup == false || typeof enablePopup === 'undefined') {
                                       _this.showLoginPopUp(CurrentLoginDetails.FirstName + " " + CurrentLoginDetails.LastName);
                                   }
                               }//end of individual

                               _this.BindHelpPageClick();
                           }
                       },
                       function (data, status, headers, config) {

                       }, JSON.stringify(object.Data));
        },

        this.getwelcomeTextAndLogo = function (logo, username) {
            $('#message_head').text('You have logged in as: ' + username);
            if (!IsNullOrEmpty(CurrentLoginDetails.filepath)) {
                $('#user_logo').attr("src", logo);
                $('#user_logo').show();
                $('.access-provided-container').removeClass("display-none");
                $('.access-provided-container-mobile').removeClass("display-none");
                $('#institutionLogoDesktop').attr("src", CurrentLoginDetails.filepath);
                $('#institutionLogoMobile').attr("src", CurrentLoginDetails.filepath);
                $('#institutionLogoDesktop').removeClass("display-none");
                $('#institutionLogoMobile').removeClass("display-none");
                $('#access-provided-by-desktop').removeClass("display-none");
                $('#access-provided-by-mobile').removeClass("display-none");
                $('#account-name-desktop').addClass("display-none");
                $('#account-name-mobile').addClass("display-none");
            }
            else {
                $('#user_logo').hide();
                $('.access-provided-container').removeClass("display-none");
                $('.access-provided-container-mobile').removeClass("display-none");
                if (!IsNullOrEmpty(CurrentLoginDetails.AccountName)) {
                    $('#account-name-desktop').text(CurrentLoginDetails.AccountName);
                    $('#account-name-mobile').text(CurrentLoginDetails.AccountName);
                }
                $('#institutionLogoDesktop').addClass("display-none");
                $('#institutionLogoMobile').addClass("display-none");
                $('#access-provided-by-desktop').removeClass("display-none");
                $('#access-provided-by-mobile').removeClass("display-none");
                $('#account-name-desktop').removeClass("display-none");
                $('#account-name-mobile').removeClass("display-none");
            }

        };

        this.welcomeNotification = function (welcomemessage) {
            if (!IsNullOrEmpty(CurrentLoginDetails.welcomeNotification)) {
                $('#brk').show();
                $('#welcome_notification').text(CurrentLoginDetails.welcomeNotification);
                $('#welcome_notification').show();
            } else {
                $('#brk').hide();
                $('#welcome_notification').hide();
            }
        };

    }
}
var ErrorRepository = function (currentRouteSetting, routeProvider, routeCurrentContext) {
	this.ThrowNotFoundError = function (currentRouteSetting, routeProvider, routeCurrentContext) {
		Repository.LoadDataWithGet("/api/error/NotFound",
			function (data, status, headers, config) {
			},
			function (data, status, headers, config) {
				location.href = "Errors/404.html";
			});
	}
}
var GlobalAssetsRepository = function () {
    this.GetHeaderAndFooter = function () {
        Repository.LoadDataWithGet(WebService.BaseURL + 'GlobalAssets/GlobalAssetsService.svc/GetHeaderAndFooter',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject != null) {
                        var script = document.createElement('script');
                        script.type = "text/javascript";
                        script.append(data.ResultObject.Scripts);
                        document.body.appendChild(script);

                        var style = document.createElement('style');
                        style.type = "text/css";
                        style.append(data.ResultObject.Styles);
                        document.body.appendChild(style);

                        $(".top_nav_master_float_left").append(data.ResultObject.Header);
                        $("iet-user-panel").remove();
                        $("iet-global-search").remove();
                        $(".universal-footer").append(data.ResultObject.Footer);
                        var BTP = '<div><div class="container"><div class="row col-md-12 column"><a href="#" class="back-to-top js-scrollto back-top" data-target="body" title="Back to top">Back to top</a></div></div></div>';
                        $(".iet-purple-dark-100 .umb-grid .grid-section:first").prepend(BTP);
                        response = data.ResultObject;
                    }
                }
            }, function (data, status, headers, config) {
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            });
    }

    //for fetching response for cookies panel implementation..

    this.GetSiteCookies = function () {
        Repository.LoadDataWithGet(WebService.BaseURL + 'GlobalAssets/GlobalAssetsService.svc/GetSiteCookies',
            function (data, status, headers, config) {
                if (ResultStatus.Successful == data.Status && data.ResultObject) {
                    if (data.ResultObject != null) {
                        
                        $.getScript(data.ResultObject.CookieUrl, function () {
                            var script = document.createElement('script');
                            script.type = "text/javascript";
                            script.src = data.ResultObject.CookieUrl;
                            document.body.appendChild(script);
                            //for setting the cookie control data..
                            var formName = localStorage.getItem("FormName");
                            var scriptC = document.createElement('script');
                            scriptC.type = "text/javascript";
                            if (formName == "Index") {
                                scriptC.src = "Script/common/CookieControl.js";
                            }
                            else {
                                scriptC.src = "/Script/common/CookieControl.js";
                            }
                            document.head.appendChild(scriptC);

                            //for setting the cookie config data into local storage..
                            var cookieconfig = data.ResultObject.CookieConfig;
                            cookieconfig.apiKey = "";
                            localStorage.setItem("cookieconfigvalue", JSON.stringify(cookieconfig));
                        });          
                    }
                }
            }, function (data, status, headers, config) {
                var messageViewModel = new MessageViewModel();
                messageViewModel.CreateErrorMessage(data);
                messageViewModel.ShowOverLay();
            });
    }
  
}
