/* Minification failed. Returning unminified contents.
(1806,143-144): run-time error JS1010: Expected identifier: .
(1806,143-144): run-time error JS1195: Expected expression: .
(1813,76-77): run-time error JS1010: Expected identifier: .
(1813,76-77): run-time error JS1195: Expected expression: .
(1813,89-93): run-time error JS1034: Unmatched 'else'; no 'if' defined: else
 */
var IusInfoUIDocument = function () {

    var g_content = "";
    var g_isHeaderAdded = false;
    var g_reArticlePanel = /<div[\s\S]*id=.?divArticlePanel[\s\S]*<\/div>/gi; //regular expresion for panel with article
    var g_reArticleAncor = /<span[\s\S]*id=.?spnArticle[\s\S]*<\/span>/gi; //regular expresion for article anchor
    var articleNum = "";
    var g_hideDocInfoOnce = false;

    var g_scrollHistoryTimer;

    function CreateUiComponentsEvent() {

        //move to segment
        $("body").on("click", ".address-index", function () {

            $(".tab-content-close-panel").click();

            var Address = $(this).attr("address-index-data");
            var HierarchyTypeName = $(this).attr("hierarchy-type-name");

            MoveToSegmentAddress(Address, HierarchyTypeName, false);

        })

        //notes
        $("body").on("click", "a.toggle-notes", function () {
            var id = $(this).attr('id');
            $("div.note" + id).parent().toggle();
            if ($("div.note" + id).is(":visible"))
                $(this).text("« " + labelLessNotes);
            else
                $(this).text(labelMoreNotes + " »");
        });

        //table grade
        $("body").on("click", ".tabela-grande-link", function () {

            if ($(this).hasClass("tabela-grande-link-closed")) {

                $(this).parent().find("div.tabela-grande").show();
                $(this).removeClass("tabela-grande-link-closed");
                $(this).addClass("tabela-grande-link-opened");
            }
            else {
                $(this).parent().find("div.tabela-grande").hide();
                $(this).addClass("tabela-grande-link-closed");
                $(this).removeClass("tabela-grande-link-opened");
            }
        })

        //commentaries footnote
        $("body").on("click", ".iuscomment-footnote-text", function () {

            var el = $(this);
            var tagId = el.attr('tagid');
            $(".document-content-wrapper").find("a[tagid='" + tagId + "']").each(function (key, value) {
                var item = $(value);
                if (item.offset().top != el.offset().top) {

                    item.parent().css('background-color', '#FFFC77');
                    $('html,body').animate({ scrollTop: item.parent().offset().top - $("#UIDocumentToolbar").outerHeight() - 4 }, 'slow', function () {

                        setTimeout(
                            function () {
                                item.parent().css('background-color', '#fff');
                            }
                            , 2000);
                    });

                    return false; //break
                }
            });

        })

        $("body").on("click", ".iuscomment-footnote-foot", function () {
            var Tagedata = $(this).attr('tagid');
            var toGo = $(".iuscomment-footnote-text[tagid=" + Tagedata + "]");

            $(toGo).parent().css('background-color', '#FFFC77');

            $('html,body').animate({ scrollTop: $(toGo).parent().offset().top - $("#UIDocumentToolbar").outerHeight() - 4 }, 'slow', function () {

                setTimeout(
                    function () {
                        $(toGo).parent().css('background-color', '#fff');
                    }
                    , 2000);
            });
        })

        $("body").on("click", ".page-number-nav", function () {
            var pageNumToGo = $(this).attr('nav-id').replace('bkpn', 'pagenum');
            var toGo = $("span#" + pageNumToGo);

            var toGoChild = $(toGo).children("span.page-number").css('background-color', '#FFFC77');

            $('html,body').animate({ scrollTop: $(toGo).offset().top - 50 }, 'slow', function () {

                setTimeout(
                    function () {
                        $(toGoChild).animate({ 'background-color': '#fff' }, 400);
                    }
                    , 1300);
            });
        })

        $("body").on("click", ".page-number-index", function () {
            var pageNumToGo = $(this).attr('nav-id').replace('bkpn', 'pagenum');
            var toGo = $("span#" + pageNumToGo);

            var toGoChild = $(toGo).children("span.page-number").css('background-color', '#FFFC77');

            $('html,body').animate({ scrollTop: $(toGo).offset().top - 265 }, 'slow', function () {
                setTimeout(
                    function () {
                        $(toGoChild).animate({ 'background-color': '#fff' }, 400);
                    }
                    , 2000);
            });
        })

        $("body").on("click", ".attachment-index", function () {
            var attIdToGo = $(this).attr('id').replace('fai', 'fa');
            var toGo = $("#" + attIdToGo);

            if ($(toGo).offset() === undefined) {
                var Parameters = GetGetSegmentParameters();
                Parameters._t = $('input[name=__RequestVerificationToken]').val();

                //block
                $(Parameters.ResultElementId, ".content-doc-frame").block();

                $.ajax({
                    dataType: 'html',
                    contentType: 'application/json; charset=utf-8',
                    type: "GET",
                    url: "/Document/DocumentUISegmentAll/",
                    data: Parameters,
                    cache: false,
                    success: function (data) {

                        $(Parameters.ResultElementId, ".content-doc-frame").html(data);

                        //Move info segment to info panel
                        $("#DocumentInfoContainer").html($("#document-info-content").html());
                        $("#document-info-content").remove();
                        setTimeout(function () {
                            //Show if not mobile
                            var docInfo = document.getElementById("DocumentInfoContainer");
                            if (docInfo && docInfo.innerText.trim().length > 0 && window.matchMedia("(min-width: 768px)").matches) {
                                $("#Info").addClass("active");
                                $("#info_tab").addClass("active");
                                g_hideDocInfoOnce = true;
                            }
                        }, 0);
                        $("#DocumentPriorityInfoContainer").html($("#document-priorityinfo-content").html());
                        $("#document-priorityinfo-content").remove();
                        var docToolsMeta = document.getElementById("DocumentToolsMeta");
                        if (docToolsMeta) {
                            docToolsMeta.style.display = docToolsMeta.innerText.trim().length == 0 ? "none" : "block";
                        }

                        //hide show entire document content
                        $("#ShowEntireDocumentContainer").hide();

                        var toGo = $("#" + attIdToGo);
                        if ($(toGo).offset() !== undefined) {
                            $('html,body').animate({ scrollTop: $(toGo).offset().top - 50 }, 'slow', function () {
                                setTimeout(
                                    function () {
                                        $(toGo).animate({ 'background-color': '#fff' }, 'fast');
                                    }
                                    , 2000);
                            });
                        }
                    },
                    complete: function () {
                        //unblock
                        $(Parameters.ResultElementId, ".content-doc-frame").unblock();
                    }
                })

            }
            else {
                $('html,body').animate({ scrollTop: $(toGo).offset().top - 50 }, 'slow', function () {
                    setTimeout(
                        function () {
                            $(toGo).animate({ 'background-color': '#fff' }, 'fast');
                        }
                        , 2000);
                });
            }
        })

        navTopToolbar = $('#UIDocumentToolbarContainer').length > 0 ? $('#UIDocumentToolbarContainer').offset().top : 0;
        navTopLinks = $('#UIDocumentLinksContainer').length > 0 ? $('#UIDocumentLinksContainer').offset().top : 0;

        //resize
        $(window).on('resize', function () {
            if ($('#UIDocumentToolbar').length > 0) {
                var toolbarWidth = $('.document-title-column').width();
                $('#UIDocumentToolbar').width(toolbarWidth);
            }

            if ($('#UIDocumentLinksContainer').length > 0 && $(window).width() >= 992) {
                var mh = window.innerHeight;
                $('#UIDocumentLinksContainer').css("max-height", mh + "px");
            }            

            if ($('#UIDocumentToolbarContainer').length > 0 && !$('#UIDocumentToolbarContainer').hasClass("goToTop"))
                navTopToolbar = $('#UIDocumentToolbarContainer').offset().top;
            if ($('#UIDocumentLinksContainer').length > 0 && !$('#UIDocumentLinksContainer').hasClass("goToTop"))
                navTopLinks = $('#UIDocumentLinksContainer').offset().top;

            scrollHideHeaderSetInterval();
        });

        scrollHideHeaderSetInterval();

        //scroll
        $(window).bind('scroll', function () {

            $(window).resize();
            let scrollTop = $(window).scrollTop();
            didScroll = true;
            
            //var navTopToolbar = $('#UIDocumentToolbarContainer').offset().top;
            var UIDocumentContent = $('#UIDocumentContent').length <= 0 ? -1 : $('#UIDocumentContent').height();

            if ($('#UIDocumentToolbarContainer').offset() !== undefined) {
                if (scrollTop > navTopToolbar && (UIDocumentContent < 0 || UIDocumentContent > 600)) {
                    $('#UIDocumentToolbar').addClass('goToTop');
                    $(".ico-document-toolbar-go-up").removeClass("ico-document-toolbar-go-up-disabled");
                    $(".ico-document-toolbar-go-up").attr("goup", "true")
                    $('#UIDocumentToolbarContainer').css("height", $('#UIDocumentToolbar').height() + "px");
                }
                else {
                    $('#UIDocumentToolbar').removeClass('goToTop');
                    $(".ico-document-toolbar-go-up").addClass("ico-document-toolbar-go-up-disabled");
                    $(".ico-document-toolbar-go-up").attr("goup", "false")
                    $('#UIDocumentToolbarContainer').css("height", "");
                }
            }

            if ($('#UIDocumentLinksContainer').offset() !== undefined) {
                if (scrollTop > navTopLinks && (UIDocumentContent < 0 || UIDocumentContent > 600)) {
                    $('#UIDocumentLinksContainer').css("left", $('#UIDocumentLinksContainer').offset().left + "px");
                    $('#UIDocumentLinksContainer').css("width", $('#UIDocumentLinksContainer').css("width"));
                    $('#UIDocumentLinksContainer').addClass('goToTop');
                    $('#UIDocumentLinksContainer').css("height", $('#UIDocumentLinks').height() + "px");
                }
                else {
                    $('#UIDocumentLinksContainer').css("left", "");
                    $('#UIDocumentLinksContainer').css("width", "");
                    $('#UIDocumentLinksContainer').removeClass('goToTop');
                    $('#UIDocumentLinksContainer').css("height", "");
                }
            }

            if (scrollTop > navTopToolbar && g_hideDocInfoOnce === true) {
                var h = $(".tab-content").height();
                var t = $(".tab-content").offset().top;
                $(".tab-content-close-panel").click();
                let scrollTopBody = $("html, body").scrollTop();
                if (scrollTopBody > t) {
                    $("html, body").scrollTop(scrollTopBody - h);
                }
                g_hideDocInfoOnce = false;
            }

            if (window.history.replaceState) {
                //Delay, because the search function could be intensive in a long document
                if (g_scrollHistoryTimer) {
                    window.clearTimeout(g_scrollHistoryTimer);
                }
                g_scrollHistoryTimer = window.setTimeout(function () {
                    //Determine current article position (first article that is below the top browser client line)
                    let curarticle;
                    $(".document-content-wrapper").find(".article-number").each(function (index) {
                        if ($(this).offset().top > scrollTop) {
                            curarticle = $(this);
                            return false;
                        }
                    });

                    //console.log(curarticle);

                    if (curarticle && curarticle.data("uri-address") && curarticle.data("uri-address").lastIndexOf("clen-", 0) === 0) {
                        let currentUrl = window.location.href.replace(/clen-.*/ig, "");
                        if (currentUrl.indexOf('?') > 0) {
                            currentUrl = currentUrl.substr(0, currentUrl.indexOf('?'));
                        }
                        if (currentUrl[currentUrl.length - 1] !== "/")
                            currentUrl += "/";

                        currentUrl += curarticle.data("uri-address");
                        window.history.replaceState(window.history.state, window.document.title, currentUrl);
                    }
                }, 200);
            }
        });

        $("body").on("click", ".ico-document-toolbar-go-up", function (e) {
            if ($(this).attr('goup') == "true") {
                $("html, body").animate({ scrollTop: 0 }, "slow");
                return false;
            }
        });

        //toolbar tabs
        $("body").on("click", ".tab-tab", function (e) {

            e.preventDefault();

            if ($(this).parent().hasClass('active')) {
                $('.tab-content-close-panel').click();
            }
            else {
                $(this).tab('show');
            }
        });

        $("body").on("click", ".tab-content-close-panel", function (e) {

            e.preventDefault()

            var TabToClose = $(this).parent().attr("id");

            $('a[href="#' + TabToClose + '"]').parent().removeClass('active');
            $(this).parent().removeClass('active');
        });
    }

    var navTopToolbar, navTopLinks;

    //Show/hide menu depending on the direction of the scroll
    var scrollInterval;
    var scrollIntervalSet = false;
    var $header = $('#UIDocumentToolbar'), //Initializing on Index will probably not work
        headerHeight = $header.outerHeight(),
        lastScrollTop = 0,
        offset = 5,
        didScroll;

    function scrollHideHeaderReset() {
        $header = $('#UIDocumentToolbar');
        headerHeight = $header.outerHeight();
    }

    function setScrollInterval() {
        if (didScroll) {
            hasScrolled();
            didScroll = false;
        }
    }

    function ParseLinks(categoryAddress) {
        if (categoryAddress.indexOf("Zakonodaja") != -1) {
            var reSelect = /(\b\d+\.[\s\S]?člen[^\s<]*\b)(?! [A-Z]|[^>]*<\/)/g;
            var replaceString = "<a onclick=\"IusInfoUIDocument.showArticle(this, 0);\" style=\"cursor:pointer;\">$1</a>";
            $('.article-paragraph').each(function () {
                //transform result into link
                $(this)[0].innerHTML = $(this)[0].innerHTML.replace(reSelect, replaceString);
            });
        }
    }

    function ShowArticle(trigger, level) {

        //if the article already displayed -> hide it end exit
        if ($(trigger).next('[id^="divArticlePanel"]').get(0) !== undefined) {
            $(trigger).next('[id^="divArticlePanel"]').remove();
            return;
        }

        //read (parse) article number
        articleNum = trigger.innerHTML.substring(0, trigger.innerHTML.indexOf("."));

        //find row where the selected article starts
        var tableRow = $('h4[data-uri-address|="clen-' + articleNum + '"]').parent();

        //if no results -> exit
        if ($(tableRow).size() == 0)
            return;

        //regex for replace: ShowArticle(this, 0) -> ShowArticle(this, X)   
        var iLevel = level + 1;

        g_content = "";
        g_isHeaderAdded = false;

        //create panel to display content
        var panelID = Math.floor(Math.random() * 100000001);
        var panelTitle = $(".document-title a").html(); //document title
        if (panelTitle.length > (level * -5) + 65)
            panelTitle = panelTitle.substr(0, (level * -5) + 65) + "... ";

        var panelStart = "";
        panelStart += "<div id=\"divArticlePanel" + panelID + "\" class=\"article-links-panel\">";
        panelStart += "  <span class=\"article-links-close\">";
        panelStart += "    <a href=\"javascript:void(0);\" onclick=\"$('#divArticlePanel" + panelID + "').remove();\">Zapri</a>";
        panelStart += "  </span>";
        panelStart += "  <span class=\"article-links-title\">";
        panelStart += "    <span>" + panelTitle + "</span>";
        panelStart += "  </span>";
        panelStart += "  <span class=\"article-links-text\">";
        panelStart += "    <h4>...</h4>";

        //read article content
        $("div[ta='" + articleNum + "']").each(function (index) {
            g_content += $(this).html();
        });

        var panelEnd = "";
        panelEnd += "      <h4>...</h4>";
        panelEnd += "    </span>";
        panelEnd += "  </div>";

        //put everything together
        var panelArticle = panelStart + g_content + panelEnd;

        //add to html right after the clicked link
        $(trigger).after(panelArticle);

        //remove article icons
        $(".article-links-panel .articleIcons").empty();
    }

    function ShowPopupArticle(trigger, level, link, params) {

        //if the article already displayed -> hide it end exit
        var next = $(trigger).next('[id^="divArticlePanel"]');
        if (next.length > 0) {
            if (next.data("loading") !== "true") {
                next.remove();
            }
            return;
        }

        //create panel to display content
        var panelID = $('[id^="divArticlePanel"]').length + 1;

        var panel = "";
        panel += "<div id=\"divArticlePanel" + panelID + "\" class=\"article-links-panel\" data-loading=\"true\">";
        panel += "  <span class=\"article-links-close\">";
        panel += "    <a href=\"javascript:void(0);\" onclick=\"$('#divArticlePanel" + panelID + "').remove();\">Zapri</a>";
        panel += "  </span>";
        panel += "  <span class=\"article-links-text\">";
        panel += "    <span class=\"article-links-text-actual\"></span>";
        panel += "    <h4 class=\"doc_h4\">...</h4><br/>Povezava do celotnega <a target='_blank' href='" + link + "'>prečiščenega besedila predpisa</a> za FinD-INFO naročnike.<br/><br/>";
        panel += "  </span>";
        panel += "</div>";

        //add to html right after the clicked link
        $(trigger).after(panel);
        var $articlePanel = $("#divArticlePanel" + panelID);
        $articlePanel.block();

        var Parameters = {};
        Parameters._Params = params;
        Parameters._t = $('input[name=__RequestVerificationToken]').val();

        $.ajax({
            dataType: 'html',
            contentType: 'application/json; charset=utf-8',
            type: "GET",
            url: "/Document/DocumentUISegmentBySegmentAddress/",
            data: Parameters,
            cache: false,
            success: function (data) {
                $articlePanel.find(".article-links-text-actual").html(data);
            },
            error: function () {
                $articlePanel.find(".article-links-text-actual").html("");
            },
            complete: function () {
                $articlePanel.data("loading", "").unblock();
            }
        })
    }

    function AddComment(Title, Article, Text, Public, Sopi, Classification) {

        var Parameters = {};
        Parameters._Title = Title;
        Parameters._COTA = Article;
        Parameters._Content = Text;
        Parameters._Public = Public;
        Parameters._SegmentKey = "0";
        Parameters._SOPI = Sopi;
        Parameters._DocName = "";
        Parameters._Classification = Classification;

        $.ajax({
            type: "POST",
            url: "/Document/AddComment",
            timeout: 10000,
            data: JSON.stringify(Parameters),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                // update total (in icon) and set input form fields
                if (Article == "0") {
                    if ($(".content-doc-header-comments").is(":visible")) {
                        var iComments = $(".content-doc-header-comments").text();
                        $(".content-doc-header-comments").text(parseInt(iComments) + 1);
                    }
                    else {
                        $(".content-doc-header-comments").css("display", "");
                        $("#lnkShowComments").addClass("tab-tab-comments");
                        $(".content-doc-header-comments").text("1");
                    }
                } else {
                    var count = $(".row[article='" + Article + "']").length;
                    if (!$("div[articleicon='" + Article + "']").is(":visible")) {
                        $("div[articleicon='" + Article + "']").css("display", "");
                        $("div[articleicon='" + Article + "']").attr("parent", "true");
                    }
                    $("div[articleicon='" + Article + "']").children(".content-doc-links-comments").text(parseInt(count) + 1);
                }
                //if ($(".txtAddComment").hasClass("txtAddComment_small"))
                //    $(".txtAddComment[article='" + Article + "']").val('Dodaj nov komentar...');
                //else
                    $(".txtAddComment[article='" + Article + "']").val('Dodaj novo opombo...');
                    $(".txtAddComment[article='" + Article + "']").css({ 'color': '#D2CECC' });
                    $(".txtAddComment[article='" + Article + "']").css({ 'font-weight': 'bold' });

                    $(".chkPublicComment[article='" + Article + "']").prop('checked', false);
                    $(".chkPublicComment[article='" + Article + "']").parent().removeClass('active');
                    $(".chkPublicComment[article='" + Article + "']").parent().parent().parent().removeClass('dynatree-selected');

                //if (sQueryStringID == false)
                //    $(".divAddComment[article='" + Article + "'] input:checkbox").prop('checked', false);

                // remove all previously newly added attributes, in order to blink the last one
                $("div").removeAttr("newlyadded");
                $("img").removeAttr("newlyadded");

                // change content, replace links
                var str = data.Content;
                var regex = /((www\.|(http|https)+\:\/\/)[&#95;.a-z0-9-]+[iusinfo|findinfo|edusinfo|insolvinfo|pravnapraksa]\.[a-zA-Z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])/ig
                var replaced_text = str.replace(regex, "<a href='$1'>$1</a>");

                // create html to append to list of comments
                var status = "personal";
                var image = "1";
                if (Public == true) {
                    status = "public";
                    image = "3";
                }
                var html = "<div class='row' commentid='" + data.CommentId + "' article='" + Article + "' public='" + Public + "' newlyadded='true'>";
                html += "<div class='col-xs-12'>";
                html += "<div id='" + data.CommentId + "' class='content-doc-comment-back comment-back-" + status + "' article='" + Article + "'>";
                html += "<span><b>" + data.FullName + "</b> <span class='MyHistoryTimeStamp'>(" + data.TimeStamp + ")</span></span>";
                html += "<a id='" + data.CommentId + "' class='lnkEditComment'>";
                //if ($(".txtAddComment").hasClass("txtAddComment_small"))
                //    html += "<img src='/images/Portal_Common/edit_comment.png' alt='Uredi komentar' title='Uredi komentar' style='position: absolute; margin-left: 3px;' /></a>&nbsp;";
                //else
                html += "<img src=\"/Content/images/edit.svg\" width=\"20\" alt='Uredi opombo' title='Uredi opombo'></a>&nbsp;";
                html += "<a id='" + data.CommentId + "' class='lnkDeleteComment'>";
                //if ($(".txtAddComment").hasClass("txtAddComment_small"))
                //    html += "<img src='/images/Portal_Common/delete_comment.png' alt='Briši komentar' title='Briši komentar' style='position: absolute; margin-left: 20px;' /></a>";
                //else
                html += "<img src='/Content/images/x.png' alt='Briši opombo' title='Briši opombo' /></a>";
                if (Public == true) {
                    html += "<div class=\"MyHistoryTimeStamp content-doc-comment-public\">Javna opomba</div>";
                }
                html += "<div class='divListCommentEditableContent'>" + replaced_text + "</div>";
                html += "</div>";
                html += "<img src='/Content/Images/pasica-izsek-prikaz-opombe_" + image + ".svg' class='content-doc-comment-fold' />";
                html += "</div>";
                html += "</div>";

                // if first comment, change icon
                if (!$(".divAddComment[article='" + Article + "']").parent().children(".row").length) {
                    if (Article == "0") {
                        $("#UIDocumentContentComments").prepend("<div class='divListComments'></div>");
                    } else {
                        //$(".divAddComment[article='" + Article + "']").parent().prepend("<div class='divListComments'></div>");
                        //$(".clenright[article='" + Article + "'] .imgComment").remove();
                        //$(".clenright[article='" + Article + "']").first().children("div").last().append("<img class='imgComments' style='position: absolute; margin: -12px 0 0 9px;' alt='Preglej opombe k " + Article + ". členu' title='Preglej opombe k " + Article + ". členu' src=\"/images/Portal_Common/comment.png\" /><div class='divCommentCircle'>1</div>");

                        ////duration of the scrolling animation (in ms)
                        //var scroll_duration = 700,
                        //    $list_comments = $(".clenright[article='" + Article + "'] .imgComments"),
                        //    $list_comments_circle = $(".clenright[article='" + Article + "'] .divCommentCircle");

                        ////smooth scroll to list of comments
                        //$list_comments.on('click', function (event) {
                        //    event.preventDefault();
                        //    $("div[article='" + Article + "']").toggle();
                        //    $('body,html').animate({
                        //        scrollTop: $(".divListComments").children("div[article='" + Article + "']").offset().top - 50,
                        //    }, scroll_duration
                        //    );
                        //});
                        //$list_comments_circle.on('click', function (event) {
                        //    event.preventDefault();
                        //    $("div[article='" + Article + "']").toggle();
                        //    $('body,html').animate({
                        //        scrollTop: $(".divListComments").children("div[article='" + Article + "']").offset().top - 50,
                        //    }, scroll_duration
                        //    );
                        //});
                    }
                }
                $(html).insertBefore(".divAddComment[article='" + Article + "']");

                // blink the last comment
                for (i = 0; i < 3; i++) {
                    $("div[newlyadded='true']").fadeTo('fast', 0.5).fadeTo('fast', 1.0);
                    $("img[newlyadded='true']").fadeTo('fast', 0.5).fadeTo('fast', 1.0);
                }
            },
            error: function (e) {
                var test = 1;
            }
        });
    }

    function UpdateComment(ID, Article, Text, Public, Sopi) {

        var commentid = 0;
        var Parameters = {};
        Parameters._CommentID = ID;
        Parameters._Content = Text;
        Parameters._Public = Public;
        Parameters._SOPI = Sopi;

        $.ajax({
            type: "POST",
            url: "/Document/UpdateComment",
            timeout: 10000,
            data: JSON.stringify(Parameters),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                // set input form fields
                //if ($(".txtAddComment").hasClass("txtAddComment_small"))
                //    $(".txtAddComment[article='" + Article + "']").val('Dodaj nov komentar...');
                //else
                    $(".txtAddComment[article='" + Article + "']").val('Dodaj novo opombo...');
                $(".txtAddComment[article='" + Article + "']").css({ 'color': '#D2CECC' });
                $(".txtAddComment[article='" + Article + "']").css({ 'font-weight': 'bold' });
                $(".txtAddComment[article='" + Article + "']").parent().children("div").last().children(".btnAddComment").val("Shrani");
                $(".txtAddComment[article='" + Article + "']").parent().children("div").last().children(".btnAddComment").text("Shrani");
                $(".txtAddComment[article='" + Article + "']").removeAttr("commentid");

                $(".chkPublicComment[article='" + Article + "']").prop('checked', false);
                $(".chkPublicComment[article='" + Article + "']").parent().removeClass('active');
                $(".chkPublicComment[article='" + Article + "']").parent().parent().parent().removeClass('dynatree-selected');

                // remove all previously newly added attributes, in order to blink the last one
                $("div").removeAttr("newlyadded");
                $("img").removeAttr("newlyadded");

                // change content, color and add newlyadded attribute
                $("div[commentid='" + ID + "']").attr("newlyadded", "true");

                var status = "personal";
                var image = "1";
                if (Public == true) {
                    image = "3";
                    status = "public";
                    $("div[commentid='" + ID + "']").attr("public", "true");
                } else {
                    $("div[commentid='" + ID + "']").attr("public", "false");
                }
                $("div[commentid='" + ID + "']").children("div").children().first().attr("class", "content-doc-comment-back comment-back-" + status);
                $("div[commentid='" + ID + "']").children("div").children().last().attr("src", "/Content/Images/pasica-izsek-prikaz-opombe_" + image + ".svg");
                if (Public == true) {
                    if (!$("div[commentid='" + ID + "']").children("div").children().first().children(".content-doc-comment-public").length) {
                        $("<div class=\"MyHistoryTimeStamp content-doc-comment-public\">Javna opomba</div>").insertBefore($("div[commentid='" + ID + "']").children("div").children().first().children(".divListCommentEditableContent"));
                    }
                } else {
                    if ($("div[commentid='" + ID + "']").children("div").children().first().children(".content-doc-comment-public").length) {
                        $("div[commentid='" + ID + "']").children("div").children().first().children(".content-doc-comment-public").remove();
                    }
                }

                // change content, replace links
                var str = data.Content;
                var regex = /((www\.|(http|https)+\:\/\/)[&#95;.a-z0-9-]+[iusinfo|findinfo|edusinfo|insolvinfo|pravnapraksa]\.[a-zA-Z0-9\/&#95;:@=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])/ig
                var replaced_text = str.replace(regex, "<a href='$1'>$1</a>");
                $("div[commentid='" + ID + "']").children("div").first().children().children(".divListCommentEditableContent").html(replaced_text);

                // blink the modified comment
                for (i = 0; i < 3; i++) {
                    $("div[newlyadded='true']").fadeTo('fast', 0.5).fadeTo('fast', 1.0);
                    $("img[newlyadded='true']").fadeTo('fast', 0.5).fadeTo('fast', 1.0);
                }

                ScrollToSelector("div[newlyadded='true']");
            },
            error: function (e) {
                var test = 1;
            }
        });
    }

    function DeleteComment(ID, Article) {

        var Parameters = {};
        Parameters._CommentID = ID;

        $.ajax({
            type: "POST",
            url: "/Document/DeleteComment",
            timeout: 10000,
            data: JSON.stringify(Parameters),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {

                // update total (in icon) and set input form fields
                if (Article == "0") {
                    var count = $(".content-doc-header-comments").text();
                    $(".content-doc-header-comments").text(parseInt(count) - 1);
                } else {
                    var count = $(".row[article='" + Article + "']").length;
                    if (!$("div[articleicon='" + Article + "']").is(":visible")) {
                        $("div[articleicon='" + Article + "']").css("display", "");
                        $("div[articleicon='" + Article + "']").attr("parent", "true");
                    }
                    $("div[articleicon='" + Article + "']").children(".content-doc-links-comments").text(parseInt(count) - 1);
                }
                $(".txtAddComment[article='" + Article + "']").val('Dodaj novo opombo...');
                $(".txtAddComment[article='" + Article + "']").css({ 'color': '#D2CECC' });
                $(".txtAddComment[article='" + Article + "']").css({ 'font-weight': 'bold' });
                $(".txtAddComment[article='" + Article + "']").parent().children("div").last().children(".btnAddComment").val("Shrani");
                $(".txtAddComment[article='" + Article + "']").parent().children("div").last().children(".btnAddComment").text("Shrani");

                $(".chkPublicComment[article='" + Article + "']").prop('checked', false);
                $(".chkPublicComment[article='" + Article + "']").parent().removeClass('active');
                $(".chkPublicComment[article='" + Article + "']").parent().parent().parent().removeClass('dynatree-selected');

                // remove comment from the list of comments
                $(".row[commentid='" + ID + "']").remove();

                // if last comment, change icon
                if (count == "1") {
                    if (Article == "0") {
                        if ($(".content-doc-header-comments").length) {
                            var iComments = $(".content-doc-header-comments").text();
                            $(".content-doc-header-comments").text(parseInt(iComments) - 1);
                            $("#lnkShowComments").removeClass("tab-tab-comments");
                            $(".content-doc-header-comments").css("display", "none");
                        }
                    }
                    else {
                        $("div[articleicon='" + Article + "']").css("display", "none");
                        $("div[articleicon='" + Article + "']").removeAttr("parent");
                        $(".divAddComment[article='" + Article + "']").remove();
                    }
                }
            },
            error: function (e) {
                var test = 1;
            }
        });
    }

    //On scroll set interval
    function scrollHideHeaderSetInterval() {
        if ($(window).width() < 992 && !scrollIntervalSet) {
            scrollInterval = setInterval(setScrollInterval, 500);
            scrollIntervalSet = true;
        } else if ($(window).width() >= 992 && scrollIntervalSet) {
            clearInterval(scrollInterval);
            scrollIntervalSet = false;
            $header.show();//.removeClass('header-scroll-show header-scroll-hide'); //just in case
        }
    }

    function hasScrolled() {
        var st = $(this).scrollTop();

        if (Math.abs(lastScrollTop - st) <= offset ||
            $header.length <= 0) {
            return;
        }

        var visible = $header.css('display') != 'none';
        if ($header.hasClass("goToTop")) { //change classes only if sticky
            if (st > lastScrollTop && st > (navTopToolbar + headerHeight) && $header.find("img[src='/Content/Images/uparrow.svg']").length == 0 && visible) {
                // Scroll down
                $header.fadeOut();//.removeClass('header-scroll-show').addClass('header-scroll-hide');
            }
            else if (st < lastScrollTop && !visible) {
                // Scroll up
                $header.fadeIn();//.removeClass('header-scroll-hide').addClass('header-scroll-show');
            }
        }
        else if (!visible) {
            $header.show();//.removeClass('header-scroll-show header-scroll-hide'); //just in case
        }

        lastScrollTop = st;
    }

    function MoveToSegmentAddress(Address, HierarchyTypeName, PlainView) {

        //console.log(Address);
        //console.log(HierarchyTypeName);

        IusInfoUIDocument.AllowScroll = 0;

        var ContentData = $("[address-content-data=" + Address + "][hierarchy-type-name=" + HierarchyTypeName + "]");

        if (ContentData.offset() === undefined) {
            var Parameters = GetGetSegmentParameters();
            Parameters._t = $('input[name=__RequestVerificationToken]').val();

            //block
            $(Parameters.ResultElementId, ".content-doc-frame").block();

            $.ajax({
                dataType: 'html',
                contentType: 'application/json; charset=utf-8',
                type: "GET",
                url: "/Document/DocumentUISegmentAll/",
                data: Parameters,
                cache: false,
                success: function (data) {
                    $(Parameters.ResultElementId, ".content-doc-frame").html(data);

                    //hide show entire document content
                    $("#ShowEntireDocumentContainer").hide();

                    OnSegmentLoad();

                    //Scroll
                    ScrollToSelector("[address-content-data=" + Address + "][hierarchy-type-name=" + HierarchyTypeName + "]");

                    //Hide header on scroll down
                    scrollHideHeaderReset();
                },
                complete: function () {
                    //unblock
                    $(Parameters.ResultElementId, ".content-doc-frame").unblock();
                }
            })

        }
        else {
            ScrollToSelector(ContentData);
        }

        if (ContentData.length > 0 && ContentData[0].dataset.uriAddress != null && typeof (history.pushState) != "undefined") {
            window.history.pushState({}, 'foo', DocumentUrl + '/' + ContentData[0].dataset.uriAddress);
        }
    }

    // Event after segments are loaded
    function OnSegmentLoad() {

        //Move chapter index from content to toolbar
        if ($("#DocumentToolbarChapterIndexContainer") &&
            $("#DocumentContentChapterIndexContainer")) {

            $("#DocumentToolbarChapterIndexContainer").html($("#DocumentContentChapterIndexContainer").html());
            $("#DocumentContentChapterIndexContainer").remove();
        }

        //Move article index from content to toolbar
        if ($("#DocumentToolbarArticleIndexContainer") &&
            $("#DocumentContentArticleIndexContainer")) {

            $("#DocumentToolbarArticleIndexContainer").html($("#DocumentContentArticleIndexContainer").html());
            $("#DocumentContentArticleIndexContainer").remove();
        }

        //Move attachment index from content to toolbar
        if ($("#DocumentToolbarAttachmentIndexContainer") &&
            $("#DocumentContentAttachmentIndexContainer")) {

            $("#DocumentToolbarAttachmentIndexContainer").html($("#DocumentContentAttachmentIndexContainer").html());
            $("#DocumentContentAttachmentIndexContainer").remove();
        }

        //Move info segment to info panel
        if ($("#DocumentInfoContainer") &&
            $("#document-info-content")) {

            $("#DocumentInfoContainer").html($("#document-info-content").html());
            $("#document-info-content").remove();
            setTimeout(function () {
                //Show if not mobile
                var docInfo = document.getElementById("DocumentInfoContainer");
                if (docInfo && docInfo.innerText.trim().length > 0 && window.matchMedia("(min-width: 768px)").matches) {
                    $("#Info").addClass("active");
                    $("#info_tab").addClass("active");
                    g_hideDocInfoOnce = true;
                }
            }, 0);
        }

        // Move priority info container to top of the document
        if ($("#DocumentPriorityInfoContainer") &&
            $("#document-priorityinfo-content")) {

            $("#DocumentPriorityInfoContainer").html($("#document-priorityinfo-content").html());
            $("#document-priorityinfo-content").remove();
            var docToolsMeta = document.getElementById("DocumentToolsMeta");
            if (docToolsMeta) {
                docToolsMeta.style.display = docToolsMeta.innerText.trim().length == 0 ? "none" : "block";
            }
        }

        //highlight
        Highlighter.DoHighlight($('#highlightText').val(), false);
    }

    function ScrollToId(id) {
        ScrollToSelector("#" + id);
    }

    function ScrollToSelector(id) {
        var $el = $(id);
        if ($el.length > 0) {
            setTimeout(function () {
                //console.log("Toolbar height: " + $("#UIDocumentToolbar").height());
                var toolbarActualHeight =
                    $("#docToolsContainer").outerHeight() +
                    $("#docToolsContainerOriginal").outerHeight() +
                    $(".tab-content").outerHeight() + //If info or any other tab is open
                    $("#linksMainContainerParent").outerHeight() + //Right side links on mobile
                    $("#DocumentToolsMeta").outerHeight() + //Meta info about document
                    $("#DocumentToolsHeaderStatusSticky").outerHeight(); //Status text about document

                //console.log("Toolbar height actual: " + toolbarActualHeight);
                $("html,body").animate({ scrollTop: $el.offset().top - toolbarActualHeight - 8 }, "fast"); //8 px for clearance
            }, 0);
        }
    }

    function DocumentUISegmentAll() {
        var Parameters = GetGetSegmentParameters();
        Parameters._t = $('input[name=__RequestVerificationToken]').val();

        //block
        $(Parameters.ResultElementId, ".content-doc-frame").block();

        $.ajax({
            dataType: 'html',
            contentType: 'application/json; charset=utf-8',
            type: "GET",
            url: "/Document/DocumentUISegmentAll/",
            data: Parameters,
            cache: false,
            success: function (data) {
                $(Parameters.ResultElementId, ".content-doc-frame").html(data);

                IusInfoUIDocument.AllowScroll = 0;

                //hide show entire document content
                $("#ShowEntireDocumentContainer").hide();

                OnSegmentLoad();


                //Hide header on scroll down
                scrollHideHeaderReset();

                var hash = window.location.hash.substr(1);
                if (hash.length > 0) {
                    ScrollToSelector("[address-content-data='" + hash + "']");
                }
            },
            complete: function () {
                //unblock
                $(Parameters.ResultElementId, ".content-doc-frame").unblock();
            }
        });
    }

    function GetGetSegmentParameters() {
        var Parameters = {};

        Parameters.SOPI = IusInfoUIDocument.Sopi;
        Parameters.CategoryAddress = IusInfoUIDocument.CategoryAddress;
        Parameters.MajorVersion = IusInfoUIDocument.MajorVersion;
        Parameters.ResultElementId = "#UIDocumentContent";

        return Parameters;
    }

    function GetDocumentUILinkListings(Sopi, ListingType, CategoryAddress, SegmentAddress, MajorVersion, SegmentHierarchyTypeName, LinkTypeCollection, Direction, IncludeEmbedded, CategoryAddressGroup, DocumentHistoryLevel, DocumentUri, ShowOnlyImportant) {

        //Get document register listings
        var Parameters = {};

        Parameters.Sopi = Sopi;
        Parameters.ListingType = ListingType;
        Parameters.CategoryAddress = CategoryAddress;
        Parameters.Packages = Packages;
        Parameters.SegmentAddress = SegmentAddress;
        Parameters.Append = 0;
        Parameters.MajorVersion = MajorVersion;
        Parameters.SegmentHierarchyTypeName = SegmentHierarchyTypeName;
        Parameters.LinkTypeCollection = LinkTypeCollection;
        Parameters.Direction = Direction;
        Parameters.IncludeEmbedded = IncludeEmbedded;
        Parameters.CategoryAddressGroup = CategoryAddressGroup;
        Parameters.DocumentHistoryLevel = DocumentHistoryLevel;
        Parameters.DocumentUri = DocumentUri;
        Parameters.MaintenanceEditionStatus = IusInfoUIDocument.MaintenanceEditionStatus;
        Parameters.ShowOnlyImportant = ShowOnlyImportant;

        Parameters.ResultElementId = "#UIDocumentContent";

        IusInfoUILink.documentLinkListings(Parameters);
        IusInfoUIDocument.AllowScroll = 0;
    }

    function ResetIndex() {
        IusInfoUIDocument.CurrentAddressIndex = 0;
    }

    function ResetListingType(listingType) {
        ListingType = listingType;
    }

    function GetLinkCountersRegister(Title, Sopi, MajorVersion, Packages, CategoryAddressGroup, CategoryAddress, ListingType, Selected, DocumentUri) {

        var Params = {};

        Params.ResultElementId = "#UILinkCounters_Register";
        Params.Title = Title;
        Params.Sopi = Sopi;
        Params.MajorVersion = MajorVersion;
        Params.Packages = Packages;
        Params.CategoryAddressGroup = CategoryAddressGroup;
        Params.CategoryAddress = CategoryAddress;
        Params.ListingType = ListingType;
        Params.Selected = Selected;
        Params.DocumentUri = DocumentUri;

        IusInfoUILink.documentLinkCounters(Params);

    }

    function GetLinkCountersDocument(Title, Sopi, MajorVersion, Packages, CategoryAddressGroup, CategoryAddress, ListingType, Selected, DocumentUri) {

        var Params = {};

        Params.Title = Title;
        Params.ResultElementId = "#UILinkCounters_Document";
        Params.Sopi = Sopi;
        Params.MajorVersion = MajorVersion;
        Params.Packages = Packages;
        Params.CategoryAddressGroup = CategoryAddressGroup;
        Params.CategoryAddress = CategoryAddress;
        Params.ListingType = ListingType;
        Params.Selected = Selected;
        Params.DocumentUri = DocumentUri;

        IusInfoUILink.documentLinkCounters(Params);

    }

    function GetLinkListingsMiniCrissCross(Sopi, MajorVersion, Packages, CategoryAddressGroup, CategoryAddress, ListingType, LinkTypeCollection, Direction, IncludeEmbedded, Selected, DocumentUri) {

        var Params = {};

        Params.ResultElementId = "#UILinkListings_MiniCrissCross";
        Params.Sopi = Sopi;
        Params.MajorVersion = MajorVersion;
        Params.Packages = Packages;
        Params.CategoryAddressGroup = CategoryAddressGroup;
        Params.CategoryAddress = CategoryAddress;
        Params.ListingType = ListingType;
        Params.LinkTypeCollection = LinkTypeCollection;
        Params.Direction = Direction;
        Params.IncludeEmbedded = IncludeEmbedded;
        Params.Selected = Selected;
        Params.Append = 0
        Params.DocumentUri = DocumentUri;

        IusInfoUILink.documentLinkListings(Params);

    }

    function GetDocumentPageNumIndex(sopi) {

        $.ajax({
            dataType: 'html',
            contentType: 'application/json; charset=utf-8',
            type: "GET",
            url: "/Document/DocumentPageNumIndex",
            data: {
                _sSOPI: sopi
            },
            cache: false,
            success: function (data) {

                $("#DocumentPageNumIndexContainer").html(data);

            }
        });
    }

    function Redirect2SiblingDocument(Identifier, SearchModel, Direction) {
        var link = $('#back-link-href').attr('href');

        $.ajax({
            dataType: 'html',
            contentType: 'application/json; charset=utf-8',
            type: "GET",
            url: "/Document/GetSiblingDocument",
            data: {
                Identifier: Identifier,
                SearchModel: SearchModel,
                Direction: Direction,
                BackLink: link
            },
            cache: false,
            success: function (data) {
                if (data.length > 0) {
                    window.location.href = data;
                }
                //alert('ale');

            }
        });
    }

    function OpenCitationCopyDialog(elemid, DialogTitle, docTitle) {

        var ajaxCallParams = {};
        ajaxCallParams._sopi = IusInfoUIDocument.Sopi;
        ajaxCallParams._title = docTitle;
        ajaxCallParams._majorVersion = IusInfoUIDocument.MajorVersion;
        ajaxCallParams._categoryAddress = IusInfoUIDocument.CategoryAddress;
        ajaxCallParams._documentValidFrom = IusInfoUIDocument.DocumentValidFromDate;
        ajaxCallParams._inForceStartDate = IusInfoUIDocument.DocumentInUseStartDate;
        ajaxCallParams._publicationType = IusInfoUIDocument.PublicationType;
        ajaxCallParams._publicationKey = IusInfoUIDocument.PublicationKey;
        ajaxCallParams._publishedDate = IusInfoUIDocument.PublishedDateTime;
        ajaxCallParams._publicationDescription = IusInfoUIDocument.PublicationDescription;

        
        var params = {};
        params.dialogId = "diaCopyDocumentCitations";
        params.height = "auto";
        params.width = "600";
        params.title = DialogTitle,
            params.url = "/Document/DocumentToolsCitation/";
        params.type = "GET";
        params.data = (ajaxCallParams);

        AppUtils.openDialog(params);
    }

    var downloadingFiles = []; //array of string keys, which documents are preparing to be downloaded
    function PdfDownload(IconId, Sopi, url, params) {
        
        //Check if already preparing the download:
        var fileKey = IconId + Sopi;
        if (downloadingFiles.indexOf(fileKey) >= 0) { //Prevent another download, as this one is already in progress
            console.log("File is already preparing to be downloaded");
            return;
        }
        var downloadingFilesIndex = downloadingFiles.push(fileKey) - 1;
        
        //Set as busy:
        var icon = $("#" + IconId);
        var iconOriginalSrc = icon.attr("src");
        icon.attr("src", "/Content/Images/time_animation_trans.gif");

        //Run:
        $.ajax({
            dataType: 'json',
            type: 'POST',
            url: url,
            data: params,
            success: function (result) {
                if (result.success) {
                    window.location.href = "/Print/Fetch" + "?sFileId=" + result.fileId;
                }
            },
            complete: function () {
                downloadingFiles.splice(downloadingFilesIndex, 1); //Remove from prep
                icon.attr("src", iconOriginalSrc); //Change back the src to its original value
            }
        });
    }

    function PdfDocDownload(e, IconId, Sopi, MajorVersion, ShowChanges, ShowAttachments) {
        e = e || window.event;
        e.preventDefault();
        
        //Generate parameters:
        var params = {
            Sopi: Sopi
        };
        if (MajorVersion != null) {
            params.MajorVersion = MajorVersion;
            params.ShowChanges = ShowChanges;
            params.ShowAttachments = ShowAttachments;
        }

        PdfDownload(IconId, Sopi, "/Print/PDF", params);
    }

    function PdfECistopisDownload(e, IconId, Sopi, DocumentUri) {
        e = e || window.event;
        e.preventDefault();

        //Generate parameters:
        var params = {
            Sopi: Sopi,
            DocumentUri: DocumentUri
        };

        PdfDownload(IconId, Sopi, "/Print/PrintECistopisAction", params);
    }

    function PdfCompareDownload(e, IconId, Sopi, MajorVersion, CompareToMajorVersion, Address, ShowAllSegments) {
        e = e || window.event;
        e.preventDefault();

        //Generate parameters:
        var params = {
            Sopi: Sopi,
            MajorVersion: MajorVersion,
            CompareToMajorVersion: CompareToMajorVersion,
            Address: Address,
            ShowAllSegments: ShowAllSegments
        };

        PdfDownload(IconId, Sopi, "/Print/PDF", params);
    }

    function PdfCompanyAnalysisDownload(e, IconId, entityId) {
        e = e || window.event;
        e.preventDefault();

        //Generate parameters:
        var params = {
            entityId: entityId
        };

        PdfDownload(IconId, entityId, "/Print/PDFCompanyAnalysis", params);
    }

    return {
        init: function (segmentCount, currentAddressIndex, listingType, initSegmentCount, sopi, documentType, categoryAddress, documentTypeName, maintenanceEditionStatus, majorVersion, documentUri, documentValidFromDate, documentValidStartDate, documentInUseStartDate, documentInUseEndDate, editionValidStartDate, editionValidEndDate, latestModifierValidStartDate, publishedDateTime, publicationKey, publicationType, publicationDescription, publicationFriendlyName, isPagePreview, isDocumentPayable) {
            this.SegmentCount = segmentCount;
            this.CurrentAddressIndex = currentAddressIndex;
            this.AllowScroll = 1;
            this.ListingType = listingType;
            this.InitSegmentCount = initSegmentCount;
            this.FullSegementsInCache = 0;
            this.Sopi = sopi;
            this.DocumentType = documentType;
            this.CategoryAddress = categoryAddress;
            this.DocumentTypeName = documentTypeName;
            this.MaintenanceEditionStatus = maintenanceEditionStatus;
            this.MajorVersion = majorVersion;
            this.DocumentUri = documentUri;
            this.DocumentValidFromDate = documentValidFromDate;
            this.DocumentValidStartDate = documentValidStartDate;
            this.DocumentInUseStartDate = documentInUseStartDate;
            this.DocumentInUseEndDate = documentInUseEndDate;
            this.LatestModifierValidStartDate = latestModifierValidStartDate;
            this.EditionValidEndDate = editionValidEndDate;
            this.EditionValidStartDate = editionValidStartDate;
            this.PublishedDateTime = publishedDateTime;
            this.PublicationKey = publicationKey;
            this.PublicationType = publicationType;
            this.PublicationDescription = publicationDescription;
            this.PublicationFriendlyName = publicationFriendlyName;
            this.IsPagePreview = isPagePreview;
            this.IsDocumentPayable = isDocumentPayable;

            CreateUiComponentsEvent();

            if (sopi != null && sopi != '')
            {
                $.ajax({
                    dataType: 'html',
                    contentType: 'application/json; charset=utf-8',
                    type: "POST",
                    url: "/AppUtils/CreateDisplaySettings/",
                    data: JSON.stringify({
                        _sopi: sopi
                    }),
                    cache: false,
                    success: function (data) {
                    }
                });
            }

        },
        initTehsis: function () {
            $("a.show-tezler-search").click(function () {
                var tezId = $(this).attr('id');
                var form = $(document.createElement('form'));
                $(form).attr("action", "https://tez.yok.gov.tr/UlusalTezMerkezi/SearchTez");
                $(form).attr("method", "POST");
                $(form).attr("id", "tezform");
                $(form).attr("name", "GForm");
                $(form).attr("target", "_blank");
                $(form).hide();

                var input = $("<input>").attr("type", "hidden").attr("name", "TezNo").val(tezId);
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "Universite").val("0");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "Tur").val("0");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "yil1").val("0");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "yil2").val("0");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "Enstitu").val("0");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "izin").val("0");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "ABD").val("0");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "Durum").val("3");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "BilimDali").val("0");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "Dil").val("0");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "islem").val("2");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "Bolum").val("0");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "-find").val("  Bul  ");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "ensad");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "abdad").val("");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "TezAd").val("");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "bilim").val("");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "AdSoyad").val("");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "Konu").val("");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "DanismanAdSoyad").val("");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "EnstituGrubu").val("");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "Dizin").val("");
                $(form).append($(input));
                input = $("<input>").attr("type", "hidden").attr("name", "Metin").val("");
                $(form).append($(input));

                $("body").append(form);

                $(form).submit();

                $("body").remove(form);

            });
        }
        ,
        getDocumentUILinkListings: function (Sopi, ListingType, CategoryAddress, SegmentAddress, MajorVersion, SegmentHierarchyTypeName, LinkTypeCollection, Direction, IncludeEmbedded, CategoryAddressGroup, DocumentHistoryLevel, DocumentUri, ShowOnlyImportant) {

            GetDocumentUILinkListings(Sopi, ListingType, CategoryAddress, SegmentAddress, MajorVersion, SegmentHierarchyTypeName, LinkTypeCollection, Direction, IncludeEmbedded, CategoryAddressGroup, DocumentHistoryLevel, DocumentUri, ShowOnlyImportant);
        },
        resetIndex: function () {
            ResetIndex();
        },
        resetListingType: function () {
            ResetListingType();
        },
        moveToSegmentAddress: function (Address, HierarchyTypeName, isPlainView) {
            return MoveToSegmentAddress(Address, HierarchyTypeName, isPlainView);
        },
        scrollToId: function (id) {
            ScrollToId(id);
        },
        parseLinks: function (categoryAddress) {
            ParseLinks(categoryAddress);
        },
        showArticle: function (trigger, level) {
            ShowArticle(trigger, level);
        },
        showPopupArticle: function (trigger, level, link, params) {
            ShowPopupArticle(trigger, level, link, params)
        },
        getContent: function (tableRow, reSelect, replaceString) {
            GetContent(tableRow, reSelect, replaceString)
        },
        addComment: function (Title, Article, Text, Public, Sopi, Classification) {
            AddComment(Title, Article, Text, Public, Sopi, Classification)
        },
        updateComment: function (ID, Article, Text, Public, Sopi) {
            UpdateComment(ID, Article, Text, Public, Sopi)
        },
        deleteComment: function (ID, Article) {
            DeleteComment(ID, Article)
        },
        getLinkCountersRegister: function (Title, Sopi, DocumentUri, MajorVersion, Packages, CategoryAddressGroup, CategoryAddress, ListingType, Selected, DocumentUri) {
            GetLinkCountersRegister(Title, Sopi, DocumentUri, MajorVersion, Packages, CategoryAddressGroup, CategoryAddress, ListingType, Selected, DocumentUri);
        },
        getLinkCountersDocument: function (Title, Sopi, MajorVersion, Packages, CategoryAddressGroup, CategoryAddress, ListingType, Selected, DocumentUri) {

            GetLinkCountersDocument(Title, Sopi, MajorVersion, Packages, CategoryAddressGroup, CategoryAddress, ListingType, Selected, DocumentUri);
        },
        getLinkListingsMiniCrissCross: function (Sopi, MajorVersion, Packages, CategoryAddressGroup, CategoryAddress, ListingType, LinkTypeCollection, Direction, IncludeEmbedded, Selected) {

            GetLinkListingsMiniCrissCross(Sopi, MajorVersion, Packages, CategoryAddressGroup, CategoryAddress, ListingType, LinkTypeCollection, Direction, IncludeEmbedded, Selected);
        },
        getDocumentPageNumIndex: function (sopi) {
            return GetDocumentPageNumIndex(sopi);
        },
        getDocumentUISegmentAll: DocumentUISegmentAll,
        redirect2SiblingDocument: function (Identifier, SearchModel, Direction) {
            Redirect2SiblingDocument(Identifier, SearchModel, Direction);
        },
        openCitationCopyDialog: function (elemid, DialogTitle, title) {
            OpenCitationCopyDialog(elemid, DialogTitle, title);
        },
        PdfDocDownload: PdfDocDownload,
        PdfECistopisDownload: PdfECistopisDownload,
        PdfCompareDownload: PdfCompareDownload,
        PdfCompanyAnalysisDownload: PdfCompanyAnalysisDownload
    }
}();


/*SLOVAR*/
var Highlighter = Highlighter ? Highlighter : {

    g_highlighterBesediloDivID: "#UIDocumentContent",

    g_Enabled: 0, //hit navigation enabled or disabled
    g_SelectedHitIndex: 0,

    g_btnSelectPrev: "#highlightSearchPrev",
    g_btnSelectNext: "#highlightSearchNext",

    g_LastSearchText: "",

    DoHighlight: function (searchText, selectFirst) {

        if (searchText === Highlighter.g_LastSearchText &&
            selectFirst) {
            // if search text is equal to the last one and if user wanted to re-highlight the same text, then jsut move to the next hit
            // selectFirst is false when segments are reloaded, so we should highlight as usual
            Highlighter.SelectNextHit();
        }
        else {
            //če je besedilo na strani -> sprožimo highlight
            if ($(Highlighter.g_highlighterBesediloDivID)[0] != undefined) {

                //prikažemo loader
                Highlighter.HighlightStarted();

                //označimo besede
                setTimeout(function () { Highlighter.Highlight(searchText, selectFirst); }, 1);
            }
        }
    },

    HighlightStarted: function () {
        //Toolbar.ShowStatus("&nbsp;&nbsp;Highlighting ...&nbsp;"); //&nbsp; da izenačimo dolžino besedila (zaradi IE7 in float bug)
    },

    HighlightCompleted: function () {
        //Toolbar.HideStatus();
        //$(Slovar.g_iskanjeFieldID).focus();
    },

    HighlightCompletedNoMatch: function () {
        //brez zadetkov
        //setTimeout(function () { Highlighter.HighlightCompleted(); }, 2000);
    },

    ShowHitNavigation: function () {
        Highlighter.g_Enabled = 1;
        Highlighter.g_SelectedHitIndex = 0;

        $(Highlighter.g_btnSelectPrev).removeClass("li-disabled");
        $(Highlighter.g_btnSelectNext).removeClass("li-disabled");

    },

    HideHitNavigation: function () {
        Highlighter.g_Enabled = 0;
        Highlighter.g_SelectedHitIndex = 0;

        $(Highlighter.g_btnSelectPrev).addClass("li-disabled");
        $(Highlighter.g_btnSelectNext).addClass("li-disabled");
    },

    SelectPreviousHit: function () {

        if (Highlighter.g_jumpToFirst) {
            Highlighter.g_SelectedHitIndex = 0;
            Highlighter.g_jumpToFirst = false;
        }
        else
            Highlighter.g_SelectedHitIndex--;

        Highlighter.Select();
    },

    SelectNextHit: function () {

        if (Highlighter.g_jumpToFirst) {
            Highlighter.g_SelectedHitIndex = 0;
            Highlighter.g_jumpToFirst = false;
        }
        else
            Highlighter.g_SelectedHitIndex++;

        Highlighter.Select();
    },

    SelectText: function (elemnt) {
        var doc = document
            , element = elemnt
            , range, selection
        ;
        if (doc.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(element);
            range.select();
        } else if (window.getSelection) {
            selection = window.getSelection();
            range = document.createRange();
            range.selectNodeContents(element);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    },
    Select: function () {

        var highlightedCount = $('.highlighted').size();
        if (highlightedCount == 0) {
            Highlighter.HideHitNavigation();
            return;
        }

        if (highlightedCount == 1 || highlightedCount <= Highlighter.g_SelectedHitIndex)
            Highlighter.g_SelectedHitIndex = 0; //reset
        else if (Highlighter.g_SelectedHitIndex < 0)
            Highlighter.g_SelectedHitIndex = highlightedCount - 1; //Marry go round

        var element = $('.highlighted')[Highlighter.g_SelectedHitIndex];
        //element.scrollIntoView();
        Highlighter.SelectText(element)
        //document.body.scrollTop -= 50;

        var el = $(element);
        var elOffset = el.offset().top;
        var elHeight = el.height();
        var windowHeight = $(window).height();
        var offset;

        if (elHeight < windowHeight) {
            offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
        }
        else {
            offset = elOffset;
        }
        var speed = 700;
        $('html, body').animate({ scrollTop: offset }, speed);

        if (highlightedCount == 1) {
            //Disable next/prev
            $(Highlighter.g_btnSelectPrev).addClass("li-disabled");
            $(Highlighter.g_btnSelectNext).addClass("li-disabled");
        }
        else {
            $(Highlighter.g_btnSelectPrev).removeClass("li-disabled");
            $(Highlighter.g_btnSelectNext).removeClass("li-disabled");
        }
    },

    g_jumpToFirst: false, //if true, it will jump to first hit no matter the button (prev/next)
    HighlightReplace: function (searchTextFromUser) {
        searchTextFromUser = searchTextFromUser.replace(/([|()\[{.+*?^$\\\/])/g, "\\$1"); //replace regex characters to have the escape char
        searchTextFromUser = searchTextFromUser.replace(/[Iİı]/g, 'i'); //replace turkish i specialties
        searchTextFromUser = searchTextFromUser.replace(/ ((and)|(or)|(not)) /gi, ' '); //replace search commands
        return searchTextFromUser;
    },

    g_unicodeChars: "\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC",
    Highlight: function (searchText, jumpToFirst) {

        /*//timing
        var start = new Date().getTime();*/

        //če je beseda podana -> označimo, 
        //če ni -> odznačimo
        var found = false;
        if (searchText.length > 0) {

            searchText = Highlighter.HighlightReplace(searchText);

            // List of words to search for
            var list = [];
            // Regex builder for matches
            var regexBuilder = "";

            //First, lets find the text between "
            var regexExplicit = new RegExp("(\"[^\"]+\")|('[^']+')", "g");
            var match = regexExplicit.exec(searchText);
            while (match != null) {

                var matchValue = match[0];
                matchValue = matchValue.substring(1,matchValue.length - 1); // remove leading and ending " or '

                //Check for duplicates:
                var isDuplicate = false;
                var matchValueLower = matchValue.toLowerCase();
                for (var j = 0; j < list.length; ++j) {
                    if (list[j] == matchValueLower) {
                        isDuplicate = true;
                        break;
                    }
                }

                if (!isDuplicate) {
                    //Build a regex with all matches
                    if (regexBuilder.length > 0)
                        regexBuilder += "|";

                    regexBuilder += "(" + matchValue + ")"; //no need to escape, we're only looking for alphabet and numbers

                    //for checking with duplicates:
                    list.push(matchValueLower);
                }

                //Next match
                match = regexExplicit.exec(searchText);
            }

            // Remove explicit items
            searchText = searchText.replace(/("[^"]*")|('[^']*')/g, ' ').trim(); // Note: it's different than above (* and +)
            
            //To split the search string into smaller bits (only alphanum characters)
            //This unicode mess below is the equivalent of .NETs \p{L} (unicode letters, upper and lower case), https://github.com/danielberndt/babel-plugin-utf-8-regex/blob/master/src/transformer.js
            regexSplit = new RegExp("([" + Highlighter.g_unicodeChars + "]+)|(\\d+)", "gi");
            //Find all matches in the search string
            match = regexSplit.exec(searchText);
            while (match != null) {

                var matchValue = match[0];

                //Check for duplicates:
                var isDuplicate = false;
                var matchValueLower = matchValue.toLowerCase();
                for (var j = 0; j < list.length; ++j) {
                    if (list[j] == matchValueLower) {
                        isDuplicate = true;
                        break;
                    }
                }

                if (!isDuplicate) {
                    //Build a regex with all matches
                    if (regexBuilder.length > 0)
                        regexBuilder += "|";

                    regexBuilder += "(" + matchValue + ")"; //no need to escape, we're only looking for alphabet and numbers

                    //for checking with duplicates:
                    list.push(matchValueLower);
                }

                //Next match
                match = regexSplit.exec(searchText);
            }

            //Build Regex, and be sure to unescape searchtext so that regex won't fail, was: ?![a-z0-9]{0,4};
            if (regexBuilder.length > 0) {
                if (searchText.length > 0) {
                    regexBuilder = "(^|[^" + Highlighter.g_unicodeChars + "0-9])((" + searchText + ")|" + regexBuilder + ")(?![^<]*>)";
                }
                else {
                    regexBuilder = "(^|[^" + Highlighter.g_unicodeChars + "0-9])(" + regexBuilder + ")(?![^<]*>)";
                }

                //Run
                found = Highlighter.HighlightSearch(regexBuilder, 2);
            }
        }

        if (found) {
            Highlighter.g_LastSearchText = searchText;
            Highlighter.g_SelectedHitIndex = 0;
            Highlighter.g_jumpToFirst = !jumpToFirst;
            if (jumpToFirst)
                Highlighter.Select();
        }
        else {
            Highlighter.g_LastSearchText = "";
            Highlighter.UnHighlight();
        }

        /*//timing
        var end = new Date().getTime();
        var time = end - start;
        alert('Execution time: ' + time);*/
    },

    HighlightSearch: function (regexSelect, rexGroup) {

        rexGroup = typeof rexGroup !== 'undefined' ? rexGroup : 0;

        var found = false;

        Highlighter.UnHighlightInternal();
        if (regexSelect != '') {
            found = Highlighter.HighlightInternal($(Highlighter.g_highlighterBesediloDivID), regexSelect, 'highlighted', rexGroup);

            if (found) {
                Highlighter.HighlightCompleted();
            }
            else {
                Highlighter.HighlightCompletedNoMatch();
            }

            Highlighter.g_Enabled = 1;
        }

        return found;
    },

    UnHighlight: function () {
        Highlighter.UnHighlightInternal();
        Highlighter.HighlightCompleted();
    },

    HighlightInternal: function (nodes, pattern, className, rexGroup) {
        /* http://beatgates.blogspot.com/2011/07/extend-jqueryhighlight-to-highlight.html */
        var regex = typeof (pattern) === "string" ? new RegExp(pattern, "i") : pattern; // assume very LOOSELY pattern is regexp if not string
        var found = false;
        className = typeof className !== 'undefined' ? className : 'highlighted';
        rexGroup = typeof rexGroup !== 'undefined' ? rexGroup : 0;

        function innerHighlight(node) {
            var skip = 0;
            if (node.nodeType === 3) { // 3 - Text node
                var pos = node.data.replace(/[Iİı]/g, 'i').search(regex);
                if (pos >= 0 && node.data.length > 0) { // .* matching "" causes infinite loop
                    var match = node.data.replace(/[Iİı]/g, 'i').match(regex); // first replace some turkish specialities, then get the match(es), but we would only handle the 1st one, hence /g is not recommended
                    if (rexGroup > 0 && match[rexGroup] != null && match[0].length > match[rexGroup].length)
                        pos += (match[0].length - match[rexGroup].length); //Offset
                    var spanNode = document.createElement('span');
                    spanNode.className = className; // set css
                    var middleBit = node.splitText(pos); // split to 2 nodes, node contains the pre-pos text, middleBit has the post-pos
                    var endBit = middleBit.splitText(match[rexGroup].length); // similarly split middleBit to 2 nodes
                    var middleClone = middleBit.cloneNode(true);
                    spanNode.appendChild(middleClone);
                    // parentNode ie. node, now has 3 nodes by 2 splitText()s, replace the middle with the highlighted spanNode:
                    middleBit.parentNode.replaceChild(spanNode, middleBit);
                    skip = 1; // skip this middleBit, but still need to check endBit

                    if (!found) { //So that the code below is executed only once
                        Highlighter.ShowHitNavigation();
                        found = true;
                    }
                }
            } else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { // 1 - Element node
                for (var i = 0; i < node.childNodes.length; i++) { // highlight all children
                    i += innerHighlight(node.childNodes[i], pattern); // skip highlighted ones
                }
            }
            return skip;
        }

        nodes.each(function () {
            innerHighlight(this);
        });

        return found;
    },
    UnHighlightInternal: function () {
        /* http://beatgates.blogspot.com/2011/07/extend-jqueryhighlight-to-highlight.html */
        var nodes = $(Highlighter.g_highlighterBesediloDivID);
        nodes.find("span.highlighted").each(function () {
            this.parentNode.firstChild.nodeName;
            with (this.parentNode) {
                replaceChild(this.firstChild, this);
                normalize();
            }
        }).end();

        Highlighter.HideHitNavigation();
    }
};;
/*
    PDFObject v2.0.201604172
    https://github.com/pipwerks/PDFObject
    Copyright (c) 2008-2016 Philip Hutchison
    MIT-style license: http://pipwerks.mit-license.org/
    UMD module pattern from https://github.com/umdjs/umd/blob/master/templates/returnExports.js
*/
(function(root,factory){if(typeof define==="function"&&define.amd){define([],factory)}else if(typeof module==="object"&&module.exports){module.exports=factory()}else{root.PDFObject=factory()}})(this,function(){"use strict";if(typeof window==="undefined"||typeof navigator==="undefined"){return false}var pdfobjectversion="2.0.201604172",supportsPDFs,createAXO,isIE,supportsPdfMimeType=typeof navigator.mimeTypes["application/pdf"]!=="undefined",supportsPdfActiveX,buildFragmentString,log,embedError,embed,getTargetElement,generatePDFJSiframe,isIOS=function(){return/iphone|ipad|ipod/i.test(navigator.userAgent.toLowerCase())}(),generateEmbedElement;createAXO=function(type){var ax;try{ax=new ActiveXObject(type)}catch(e){ax=null}return ax};isIE=function(){return!!(window.ActiveXObject||"ActiveXObject"in window)};supportsPdfActiveX=function(){return!!(createAXO("AcroPDF.PDF")||createAXO("PDF.PdfCtrl"))};supportsPDFs=supportsPdfMimeType||isIE()&&supportsPdfActiveX();buildFragmentString=function(pdfParams){var string="",prop;if(pdfParams){for(prop in pdfParams){if(pdfParams.hasOwnProperty(prop)){string+=encodeURIComponent(prop)+"="+encodeURIComponent(pdfParams[prop])+"&"}}if(string){string="#"+string;string=string.slice(0,string.length-1)}}return string};log=function(msg){if(typeof console!=="undefined"&&console.log){console.log("[PDFObject] "+msg)}};embedError=function(msg){log(msg);return false};getTargetElement=function(targetSelector){var targetNode=document.body;if(typeof targetSelector==="string"){targetNode=document.querySelector(targetSelector)}else if(typeof jQuery!=="undefined"&&targetSelector instanceof jQuery&&targetSelector.length){targetNode=targetSelector.get(0)}else if(typeof targetSelector.nodeType!=="undefined"&&targetSelector.nodeType===1){targetNode=targetSelector}return targetNode};generatePDFJSiframe=function(targetNode,url,pdfOpenFragment,PDFJS_URL,id){var fullURL=PDFJS_URL+"?file="+encodeURIComponent(url)+pdfOpenFragment;var scrollfix=isIOS?"-webkit-overflow-scrolling: touch; overflow-y: scroll; ":"overflow: hidden; ";var iframe="<div style='"+scrollfix+"position: absolute; top: 0; right: 0; bottom: 0; left: 0;'><iframe  "+id+" src='"+fullURL+"' style='border: none; width: 100%; height: 100%;' frameborder='0'></iframe></div>";targetNode.className+=" pdfobject-container";targetNode.style.position="relative";targetNode.style.overflow="auto";targetNode.innerHTML=iframe;return targetNode.getElementsByTagName("iframe")[0]};generateEmbedElement=function(targetNode,targetSelector,url,pdfOpenFragment,width,height,id){var style="";if(targetSelector&&targetSelector!==document.body){style="width: "+width+"; height: "+height+";"}else{style="position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 100%; height: 100%;"}targetNode.className+=" pdfobject-container";targetNode.innerHTML="<embed "+id+" class='pdfobject' src='"+url+pdfOpenFragment+"' type='application/pdf' style='overflow: auto; "+style+"'/>";return targetNode.getElementsByTagName("embed")[0]};embed=function(url,targetSelector,options){if(typeof url!=="string"){return embedError("URL is not valid")}targetSelector=typeof targetSelector!=="undefined"?targetSelector:false;options=typeof options!=="undefined"?options:{};var id=options.id&&typeof options.id==="string"?"id='"+options.id+"'":"",page=options.page?options.page:false,pdfOpenParams=options.pdfOpenParams?options.pdfOpenParams:{},fallbackLink=typeof options.fallbackLink!=="undefined"?options.fallbackLink:true,width=options.width?options.width:"100%",height=options.height?options.height:"100%",forcePDFJS=typeof options.forcePDFJS==="boolean"?options.forcePDFJS:false,PDFJS_URL=options.PDFJS_URL?options.PDFJS_URL:false,targetNode=getTargetElement(targetSelector),fallbackHTML="",pdfOpenFragment="",fallbackHTML_default="<p>This browser does not support inline PDFs. Please download the PDF to view it: <a href='[url]'>Download PDF</a></p>";if(!targetNode){return embedError("Target element cannot be determined")}if(page){pdfOpenParams.page=page}pdfOpenFragment=buildFragmentString(pdfOpenParams);if(forcePDFJS&&PDFJS_URL){return generatePDFJSiframe(targetNode,url,pdfOpenFragment,PDFJS_URL,id)}else if(supportsPDFs){return generateEmbedElement(targetNode,targetSelector,url,pdfOpenFragment,width,height,id)}else{if(PDFJS_URL){return generatePDFJSiframe(targetNode,url,pdfOpenFragment,PDFJS_URL,id)}else if(fallbackLink){fallbackHTML=typeof fallbackLink==="string"?fallbackLink:fallbackHTML_default;targetNode.innerHTML=fallbackHTML.replace(/\[url\]/g,url)}return embedError("This browser does not support embedded PDFs")}};return{embed:function(a,b,c){return embed(a,b,c)},pdfobjectversion:function(){return pdfobjectversion}(),supportsPDFs:function(){return supportsPDFs}()}});;
/*!
 * clipboard.js v1.7.1
 * https://zenorocha.github.io/clipboard.js
 *
 * Licensed MIT © Zeno Rocha
 */
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.Clipboard=t()}}(function(){var t,e,n;return function t(e,n,o){function i(a,c){if(!n[a]){if(!e[a]){var l="function"==typeof require&&require;if(!c&&l)return l(a,!0);if(r)return r(a,!0);var s=new Error("Cannot find module '"+a+"'");throw s.code="MODULE_NOT_FOUND",s}var u=n[a]={exports:{}};e[a][0].call(u.exports,function(t){var n=e[a][1][t];return i(n||t)},u,u.exports,t,e,n,o)}return n[a].exports}for(var r="function"==typeof require&&require,a=0;a<o.length;a++)i(o[a]);return i}({1:[function(t,e,n){function o(t,e){for(;t&&t.nodeType!==i;){if("function"==typeof t.matches&&t.matches(e))return t;t=t.parentNode}}var i=9;if("undefined"!=typeof Element&&!Element.prototype.matches){var r=Element.prototype;r.matches=r.matchesSelector||r.mozMatchesSelector||r.msMatchesSelector||r.oMatchesSelector||r.webkitMatchesSelector}e.exports=o},{}],2:[function(t,e,n){function o(t,e,n,o,r){var a=i.apply(this,arguments);return t.addEventListener(n,a,r),{destroy:function(){t.removeEventListener(n,a,r)}}}function i(t,e,n,o){return function(n){n.delegateTarget=r(n.target,e),n.delegateTarget&&o.call(t,n)}}var r=t("./closest");e.exports=o},{"./closest":1}],3:[function(t,e,n){n.node=function(t){return void 0!==t&&t instanceof HTMLElement&&1===t.nodeType},n.nodeList=function(t){var e=Object.prototype.toString.call(t);return void 0!==t&&("[object NodeList]"===e||"[object HTMLCollection]"===e)&&"length"in t&&(0===t.length||n.node(t[0]))},n.string=function(t){return"string"==typeof t||t instanceof String},n.fn=function(t){return"[object Function]"===Object.prototype.toString.call(t)}},{}],4:[function(t,e,n){function o(t,e,n){if(!t&&!e&&!n)throw new Error("Missing required arguments");if(!c.string(e))throw new TypeError("Second argument must be a String");if(!c.fn(n))throw new TypeError("Third argument must be a Function");if(c.node(t))return i(t,e,n);if(c.nodeList(t))return r(t,e,n);if(c.string(t))return a(t,e,n);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function i(t,e,n){return t.addEventListener(e,n),{destroy:function(){t.removeEventListener(e,n)}}}function r(t,e,n){return Array.prototype.forEach.call(t,function(t){t.addEventListener(e,n)}),{destroy:function(){Array.prototype.forEach.call(t,function(t){t.removeEventListener(e,n)})}}}function a(t,e,n){return l(document.body,t,e,n)}var c=t("./is"),l=t("delegate");e.exports=o},{"./is":3,delegate:2}],5:[function(t,e,n){function o(t){var e;if("SELECT"===t.nodeName)t.focus(),e=t.value;else if("INPUT"===t.nodeName||"TEXTAREA"===t.nodeName){var n=t.hasAttribute("readonly");n||t.setAttribute("readonly",""),t.select(),t.setSelectionRange(0,t.value.length),n||t.removeAttribute("readonly"),e=t.value}else{t.hasAttribute("contenteditable")&&t.focus();var o=window.getSelection(),i=document.createRange();i.selectNodeContents(t),o.removeAllRanges(),o.addRange(i),e=o.toString()}return e}e.exports=o},{}],6:[function(t,e,n){function o(){}o.prototype={on:function(t,e,n){var o=this.e||(this.e={});return(o[t]||(o[t]=[])).push({fn:e,ctx:n}),this},once:function(t,e,n){function o(){i.off(t,o),e.apply(n,arguments)}var i=this;return o._=e,this.on(t,o,n)},emit:function(t){var e=[].slice.call(arguments,1),n=((this.e||(this.e={}))[t]||[]).slice(),o=0,i=n.length;for(o;o<i;o++)n[o].fn.apply(n[o].ctx,e);return this},off:function(t,e){var n=this.e||(this.e={}),o=n[t],i=[];if(o&&e)for(var r=0,a=o.length;r<a;r++)o[r].fn!==e&&o[r].fn._!==e&&i.push(o[r]);return i.length?n[t]=i:delete n[t],this}},e.exports=o},{}],7:[function(e,n,o){!function(i,r){if("function"==typeof t&&t.amd)t(["module","select"],r);else if(void 0!==o)r(n,e("select"));else{var a={exports:{}};r(a,i.select),i.clipboardAction=a.exports}}(this,function(t,e){"use strict";function n(t){return t&&t.__esModule?t:{default:t}}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var i=n(e),r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=function(){function t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}return function(e,n,o){return n&&t(e.prototype,n),o&&t(e,o),e}}(),c=function(){function t(e){o(this,t),this.resolveOptions(e),this.initSelection()}return a(t,[{key:"resolveOptions",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.action=e.action,this.container=e.container,this.emitter=e.emitter,this.target=e.target,this.text=e.text,this.trigger=e.trigger,this.selectedText=""}},{key:"initSelection",value:function t(){this.text?this.selectFake():this.target&&this.selectTarget()}},{key:"selectFake",value:function t(){var e=this,n="rtl"==document.documentElement.getAttribute("dir");this.removeFake(),this.fakeHandlerCallback=function(){return e.removeFake()},this.fakeHandler=this.container.addEventListener("click",this.fakeHandlerCallback)||!0,this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="absolute",this.fakeElem.style[n?"right":"left"]="-9999px";var o=window.pageYOffset||document.documentElement.scrollTop;this.fakeElem.style.top=o+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,this.container.appendChild(this.fakeElem),this.selectedText=(0,i.default)(this.fakeElem),this.copyText()}},{key:"removeFake",value:function t(){this.fakeHandler&&(this.container.removeEventListener("click",this.fakeHandlerCallback),this.fakeHandler=null,this.fakeHandlerCallback=null),this.fakeElem&&(this.container.removeChild(this.fakeElem),this.fakeElem=null)}},{key:"selectTarget",value:function t(){this.selectedText=(0,i.default)(this.target),this.copyText()}},{key:"copyText",value:function t(){var e=void 0;try{e=document.execCommand(this.action)}catch(t){e=!1}this.handleResult(e)}},{key:"handleResult",value:function t(e){this.emitter.emit(e?"success":"error",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})}},{key:"clearSelection",value:function t(){this.trigger&&this.trigger.focus(),window.getSelection().removeAllRanges()}},{key:"destroy",value:function t(){this.removeFake()}},{key:"action",set:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"copy";if(this._action=e,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function t(){return this._action}},{key:"target",set:function t(e){if(void 0!==e){if(!e||"object"!==(void 0===e?"undefined":r(e))||1!==e.nodeType)throw new Error('Invalid "target" value, use a valid Element');if("copy"===this.action&&e.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if("cut"===this.action&&(e.hasAttribute("readonly")||e.hasAttribute("disabled")))throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');this._target=e}},get:function t(){return this._target}}]),t}();t.exports=c})},{select:5}],8:[function(e,n,o){!function(i,r){if("function"==typeof t&&t.amd)t(["module","./clipboard-action","tiny-emitter","good-listener"],r);else if(void 0!==o)r(n,e("./clipboard-action"),e("tiny-emitter"),e("good-listener"));else{var a={exports:{}};r(a,i.clipboardAction,i.tinyEmitter,i.goodListener),i.clipboard=a.exports}}(this,function(t,e,n,o){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function c(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function l(t,e){var n="data-clipboard-"+t;if(e.hasAttribute(n))return e.getAttribute(n)}var s=i(e),u=i(n),f=i(o),d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},h=function(){function t(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}return function(e,n,o){return n&&t(e.prototype,n),o&&t(e,o),e}}(),p=function(t){function e(t,n){r(this,e);var o=a(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return o.resolveOptions(n),o.listenClick(t),o}return c(e,t),h(e,[{key:"resolveOptions",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.action="function"==typeof e.action?e.action:this.defaultAction,this.target="function"==typeof e.target?e.target:this.defaultTarget,this.text="function"==typeof e.text?e.text:this.defaultText,this.container="object"===d(e.container)?e.container:document.body}},{key:"listenClick",value:function t(e){var n=this;this.listener=(0,f.default)(e,"click",function(t){return n.onClick(t)})}},{key:"onClick",value:function t(e){var n=e.delegateTarget||e.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new s.default({action:this.action(n),target:this.target(n),text:this.text(n),container:this.container,trigger:n,emitter:this})}},{key:"defaultAction",value:function t(e){return l("action",e)}},{key:"defaultTarget",value:function t(e){var n=l("target",e);if(n)return document.querySelector(n)}},{key:"defaultText",value:function t(e){return l("text",e)}},{key:"destroy",value:function t(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)}}],[{key:"isSupported",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:["copy","cut"],n="string"==typeof e?[e]:e,o=!!document.queryCommandSupported;return n.forEach(function(t){o=o&&!!document.queryCommandSupported(t)}),o}}]),e}(u.default);t.exports=p})},{"./clipboard-action":7,"good-listener":4,"tiny-emitter":6}]},{},[8])(8)});;
