﻿/// <FileHeader>
/// <FileName>SearchResult.js</FileName>
/// <Description>
/// This file will have javascript function for search result page
/// </Description>
/// <Author>Purushottam Sahu</Author>
/// <DateCreated date="24/05/2009"/>
/// <RevisionHistory>
/// <Revision date="" author="">
/// </Revision>
/// </RevisionHistory>
/// </FileHeader>


/* -----------------------------------------------------------------------------------------------------
Start Region - Page Load
-------------------------------------------------------------------------------------------------------*/
$(document).ready(function() {

    //retain search keyword
    if (typeof (searchKeyword) != "undefined") {
        $("#SaveSearchCriteriaText").val(searchKeyword);
        if (searchKeyword.indexOf(":") != -1) {
            var searchTextValue = searchKeyword.split(":");
            var searchString = '';
            for (i = 1; i < searchTextValue.length; i++) {
                searchString = searchString + ":" + searchTextValue[i];
            }
            var popupText = $fullText;

            $('#SimpleSearch_Popup li').each(function() {
                var reservedword = $(this).attr("reservedKeyword");
                
             
                if (reservedword != '') {
                    reservedword = reservedword.substring(0, reservedword.length - 1);
                    if (reservedword.toLowerCase() == searchTextValue[0].toLowerCase()) {

                        popupText = $(this).attr("displaySearchText");
                    }
                }
            });
            if (popupText != $fullText) {
                if (searchString != '') {
                    searchKeyword = searchString.substring(1, searchString.length);
                }
            }

            $("#PopupText").html(popupText);
            $("#allSearchModel_FreeText").val(searchKeyword);
        }
        $("#SearchText").val(searchKeyword);
    }

    //Show progress
    $("#showProgress").show();
    $("#save_search_msg").hide();
    $("#All").hide();

    //Set drop down list autopostback true
    //$("#SortBy").addClass("order_by_dropdown");
    $("#SortBy").change(function() {
        var form = $(this).parents('form');
        form.submit();
    });

    //$("#PageSize").addClass("rpp_dropdown_s4");
    $("#PageSize").change(function() {
        var form = $(this).parents('form');
        form.submit();
    });

    if ($("#activeTab").val() != '') {
        activeTabIndex = $("#activeTab").val();
    }

    //flag to disable tab
    var isLocked = false;
    //Create search result page tabs
    $('#SearchResultTab').tabs({
        cache: true,
        selected: activeTabIndex,
        fx: { opacity: 'toggle' },
        select: function(event, ui) {
            // $("#pageNumber").val('');
            if (isLocked) {
                //alert("Please wait ...");
                return false;
            }
            return true;
        },
        show: function(event, ui) {
            $("#activeTab").val($('#SearchResultTab').tabs('option', 'selected'));
            selectedCategory = $(ui.tab).attr("url");
            selectedPanel = selectedCategory + 'Result';
            var pageNo = 1;
            if (($(ui.panel).attr('id')).toLowerCase() == "all") {
                var $pageNumberAll = $("#pageNumberAll");
                if ($pageNumberAll.val() != "") {
                    pageNo = $pageNumberAll.val();
                }
            }
            else if (($(ui.panel).attr('id')).toLowerCase() == "journal") {
                var $pageNumberJA = $("#pageNumberJA");
                if ($pageNumberJA.val() != "") {
                    pageNo = $pageNumberJA.val();
                }
            }
            else if (($(ui.panel).attr('id')).toLowerCase() == "ebooks") {
                var $pageNumberBook = $("#pageNumberBook");
                if ($pageNumberBook.val() != "") {
                    pageNo = $pageNumberBook.val();
                }
            }
            else if (($(ui.panel).attr('id')).toLowerCase() == "databases") {
                var $pageNumberDatabases = $("#pageNumberDatabases");
                if ($pageNumberDatabases.val() != "") {
                    pageNo = $pageNumberDatabases.val();
                }
            }
            else if (($(ui.panel).attr('id')).toLowerCase() == "mostreadarticles") {
                var $pageNumberMostReadArticles = $("#pageNumberMostReadArticles");
                if ($pageNumberMostReadArticles.val() != "") {
                    pageNo = $pageNumberMostReadArticles.val();
                }
            }

            rCount = $(ui.tab).attr("Count");
            if (($(ui.panel).attr('title')).toLowerCase() == "in progress" && !isLocked) {
                isLocked = true
                if (($(ui.panel).attr('title')).toLowerCase() == "in progress") {
                    $("#showProgress").show();
                    $(ui.panel).hide();
                    //$("#progressBar").toggle();
                    var _post = {
                        searchterm: $("#SearchTerm").val(),
                        resultcount: rCount,
                        category: selectedCategory,
                        pageno: pageNo
                    };
                    $(ui.panel).load(resultURL, _post, function() {
                    
                        //Facet Load
                        $("#showProgress").hide();
                        $(ui.panel).show();
                        $(ui.panel).attr('title', '');
                        isResultAvail = true;
                        if (isCountAvail) {
                            rCount = $(".ui-tabs-selected a").attr("Count");
                            setPager(rCount);
                        }
                        else {
                            $("#" + selectedCategory + " .totalPages").each(function(i, item) {
                                $(this).html('<img alt="loading" style="vertical-align:middle;" src="' + urlCLoader + '" />');
                            });
                            $("#" + selectedCategory + " .next_button").each(function(i, item) {
                                $(this).html('<a title="Next" class="PageLinkDisable" href="#"><img alt="Next Page" src="' + urlImgNextDisable + '" border="0"></a>');
                            });
                        }
                        isLocked = false;
                    });
                }
            }
        }
    });

    //result count
    if (typeof (searchResultCount) != "undefined") {
        $.post(searchResultCount, { searchterm: $("#SearchTerm").val() }, function(data) {
            eval("var obj=" + data);
            $.each(obj, function(i, item) {
                isCountAvail = true;
                $("#spc" + i).html("(" + item.Count + ")");
                $("#spc" + i).parent("a").attr("Count", item.Count);
            });

            if (isResultAvail) {
                rCount = $(".ui-tabs-selected a").attr("Count");

                setPager(rCount);
            }
        });
    }

    //Disable tabs if not from simple search
    if (disableTabIndex != null) {
        //Disable tabs
        $('#SearchResultTab').data('disabled.tabs', disableTabIndex);
    }


    //Save search criteria to database
    $(".lnkSaveSearch").unbind("click").bind("click", function(event) {
        event.preventDefault();
        $("#SaveSearchCriteria-form").submit();
    });


    //Save search criteria to database
    $(".save_bttn").unbind("click").bind("click", function(event) {
        event.preventDefault();
        $("#SaveSearchCriteria-form").submit();
    });

    $("#SaveSearchCriteria-form").submit(function() {
        var isLocked = false;
        if (!isLocked && $(this).valid()) {
            isLocked = true;
            var login = $("#IsLoggedIN").val();

            if (login == "False") {
                pop();
                return false;
            } else {
                $("#SaveSearchCriteria-form").append($("#SearchTerm"));
                var $tab = $(".ui-tabs-selected a");
                var url = $("#SaveSearchCriteria-form").attr("action");
                var searchTerm = "#SearchTerm";
                //var _post = $("#SaveSearchCriteria-form").serialize();
                var _post = {
                    SearchTerm: $(searchTerm).val(),
                    Criteria: $("#Criteria").val()
                };
                $.post(url, _post, function(result) {
                    var $save_search_msg = $("#save_search_msg");
                    if (result == "") {
                        $save_search_msg.show();
                        $save_search_msg.html("Search criteria saved");
                    }
                    else {
                        $save_search_msg.show();
                        $save_search_msg.html("Some error occurred while processing your request");
                    }
                });
            }
        }
        return false;
    });

    $("#loginForm").validate();
    //login pop up for save search criteria
    var pop = function() {
        var $screen = $('#screen');
        if (jQuery.browser.version == 6.0) {
            $screen.css({ "display": "block", opacity: 0.25, "width": $(document).width() - 24, "height": $(document).height() - 24 });
        }
        else {
            $screen.css({ "display": "block", opacity: 0.25, "width": $(document).width(), "height": $(document).height() });
        }

        //hide popup if user click on cancel
        $(".cancel_bttn").click(function() {
            $("#box").css("display", "none"); $('#screen').css("display", "none"); $('body').css({ "overflow": "auto" });
        });

        $('body').css({ "overflow": "hidden" });
        $('#box').css({ "display": "block" }).click(function() { });

        //when user click on login
        $("#loginForm").submit(function() {
            //$("#loginProgress").show();
            var url = $("#loginForm").attr("action");
            var _post = $("#loginForm").serialize();
            if ($(this).valid()) {
                $.post(url, _post, function(result) {
                    if (result == "true") {
                        var $login_text_right_s4 = $(".login_text_right_s4");
                        $(".welcome_text_inner_s4").html("Welcome!!!!<br /> <strong>" + $("#loginModelData_UserName").val() + "</strong>");
                        $login_text_right_s4.children("a:eq(0)").html("Logout")
                        $login_text_right_s4.children("a:eq(0)").attr("href", urlLogoff);
                        $login_text_right_s4.children("a:eq(1)").html("My Profile");
                        //urlEditProfile = urlEditProfile + $.trim($('#loginModelData_UserName').val());
                        $login_text_right_s4.children("a:eq(1)").attr("href", urlEditProfile);
                        $("#IsLoggedIN").val("true");
                        $("#box").css("display", "none"); $('#screen').css("display", "none"); $('body').css({ "overflow": "auto" });
                        $("#SaveSearchCriteria-form").submit();
                    }
                    else {
                        $("#box").html(result);
                        pop();
                    }
                });
            }
            //$("#loginProgress").hide();
            return false;
        });
    }

    $("#search_advance_link .search_new_gray_bold_txt").click(function() {
        var strQuery = "";
        if ($("#FreeText_Search").val() != "" && $("#FreeText_Search").val() != null) {
            strQuery = "?keywords=" + $("#FreeText_Search").val();
        }
        this.href = this.href + strQuery;
        return true;
    });



    /* -----------------------------------------------------------------------------------------------------
    Start Region - Refine searches
    --------------------------------------------------------------------------------------------------------*/
    $("#refine_search").unbind("click").bind("click", function(event) {
        var url = $(this).attr("href");
        //send request
        jQuery('<form action="' + url.toLowerCase() + '" method="post"></form>').append($("#SearchTerm")).append($("#SearchText")).append($("#ReservedText")).appendTo('body').submit().remove();
        event.preventDefault();
    });
    /* -----------------------------------------------------------------------------------------------------
    End Region - Refine searches
    --------------------------------------------------------------------------------------------------------*/
});                                                                                                                                     //docment.ready

/* -----------------------------------------------------------------------------------------------------
End Region - Page Load
--------------------------------------------------------------------------------------------------------*/





/* -----------------------------------------------------------------------------------------------------
/// <FileHeader>
/// <Description>
/// Result Page Function
/// </Description>
/// <Author>Purushottam Sahu</Author>
/// </FileHeader>
--------------------------------------------------------------------------------------------------------*/
function InitializeResultTabJavascript() {
  
    /* -----------------------------------------------------------------------------------------------------
    Start Region - Result page expand collapse functionality
    --------------------------------------------------------------------------------------------------------*/
    //Collapse all search result collapsable area
    $("#" + selectedCategory + " .msg_body").hide();
    if (selectedCategory.toLowerCase() == 'databases')
    {
        $("#" + selectedCategory + " .lnkExpandAll").hide();
    }
    else
    {
        $("#" + selectedCategory + " .lnkExpandAll").show();
    }
    

    var IsExpanded=false;
    var IsJournalPage=false;
    var zero=false;
    var Expand=true;    
    var IsNotNull=false;
    var linkStr = GetExpandCollapseState(selectedCategory);
    if(linkStr != '')
    {
     if(linkStr=="Collapse All")
     {
       Expand=false;
     }
     IsNotNull=true;
    }
    
    if(Expand)
    {
    if (selectedCategory.toLowerCase() == 'advancearticles' || selectedCategory.toLowerCase() == 'issues' || selectedCategory.toLowerCase() == 'mostreadarticles')
    {
    IsJournalPage=true;
    IsExpanded=true;
    
    $("#" + selectedCategory + " .lnk_txt_msg_head").each(function(i, valueOfElement) {
                if(i<2)
                {
                    //set the zero flag true for first two images need to load explictly.
                    zero=true;
                }
                actionMore($(this).parent("div"));
                zero=false;
            });
             //apply the lazy load 
             $("#" + selectedCategory + " img.GALoader1:gt(1)").lazyload({  
                         placeholder : loadingImg,  
                         effect: "fadeIn",
                         threshold :0
                         }); 
     }
     else
     {
         IsExpanded=false;
         if(IsNotNull)
         {
             IsJournalPage=false;
             IsExpanded=true;
    
            $("#" + selectedCategory + " .lnk_txt_msg_head").each(function(i, valueOfElement) {
                        actionMore($(this).parent("div"));
                    });
                    
             $("#" + selectedCategory + " .lnkExpandAll").html("Collapse All");
              $("#" + selectedCategory + " .lnkExpandAll").attr("title", "Collapse All");     
             }
             else
             {
               IsExpanded = false;
               $("#" + selectedCategory + " .lnkExpandAll").html("Expand All");
               $("#" + selectedCategory + " .lnkExpandAll").attr("title", "Expand All");
             }
         }
        
     }
     else
     {
       IsExpanded = false;
       $("#" + selectedCategory + " .lnkExpandAll").html("Expand All");
       $("#" + selectedCategory + " .lnkExpandAll").attr("title", "Expand All");
     }

    var singleExpanded=false;
    //Expand All - Collapse All
    $("#" + selectedCategory + " .lnkExpandAll").unbind("click").bind("click", function(event) {
        singleExpanded=false;
        
        event.preventDefault();
        if ($(this).html() == "Expand All") {
            RetainExpandCollapseState(selectedCategory,"Expand All");
            $(this).html("Collapse All");
            $(this).attr("title", "Collapse All");
            //iterate for all links
            $("#" + selectedCategory + " .lnk_txt_msg_head").each(function(i, valueOfElement) {
            
                if(i<2)
                {
                    //set the zero flag true for first two images need to load explictly.
                    zero=true;
                }
                actionMore($(this).parent("div"));
                zero=false;
            });
            
            if(IsJournalPage)
            {
                if (IsExpanded == false)
                {
                     IsExpanded=true;
                     $("#" + selectedCategory + " img.GALoader1:gt(1)").lazyload({  
                     placeholder : loadingImg,  
                     effect: "fadeIn",
                     threshold :0
                     }); 
                }
           }
        }
        else {
            RetainExpandCollapseState(selectedCategory,"Collapse All");
            IsExpanded=true;
            $(this).html("Expand All");
            $(this).attr("title", "Expand All");
            //iterate for all links
            $("#" + selectedCategory + " .lnk_txt_msg_head").each(function(i, valueOfElement) {
                actionLess($(this).parent("div"));
            });
        }
    });
   
  
    //Expand Collapse
    $("#" + selectedCategory + " .lnk_txt_msg_head").unbind("click").bind("click", function(event) {
        if ($(this).text() == "Expand") {
            singleExpanded=true;
            actionMore($(this).parent("div"));
            event.preventDefault();
        }
        else {
            singleExpanded=false;
            actionLess($(this).parent("div"));
            event.preventDefault();
        }
    });

    //Expand Collapse
    $("#" + selectedCategory + " .lnk_img_msg_head").unbind("click").bind("click", function(event) {
        if ($(this).children("img").attr("alt") == "Expand") {
            singleExpanded=true;
            actionMore($(this).parent("div"));
            event.preventDefault();
        }
        else {
            singleExpanded=false;
            actionLess($(this).parent("div"));
            event.preventDefault();
        }
    });

    //To collapse div
    function actionLess($parentDiv) {
        var $less_lnk_img_msg_head= $parentDiv.parent(0).children(0).children(".lnk_img_msg_head").children("img");
        $less_lnk_img_msg_head.attr("src", urlMore);
        $less_lnk_img_msg_head.attr("alt", 'Expand');
        
        var childrenmsghead_less=$parentDiv.parent("div").children(0).children(".lnk_txt_msg_head");
        childrenmsghead_less.text("Expand");
        childrenmsghead_less.attr("title", "Expand");
        childrenmsghead_less.parent("div").css("width", "47px");
        $parentDiv.parent("div").parent("div").parent("div").parent("div").parent("div").parent("div").children(".msg_body").slideUp("slow");
    }
    //To expand div
    function actionMore($parentDiv) {

        var $more_lnk_img_msg_head=$parentDiv.parent(0).children(0).children(".lnk_img_msg_head");
        $more_lnk_img_msg_head.children("img").attr("src", urlLess);
        $more_lnk_img_msg_head.children("img").attr("alt", 'Collapse');
        
        var $childrenmsghead=$parentDiv.parent("div").children(0);
        $childrenmsghead.children(".lnk_txt_msg_head").text("Collapse");
        $childrenmsghead.children(0).children(".lnk_txt_msg_head").attr("title", "Collapse");
        $childrenmsghead.children(".lnk_txt_msg_head").parent("div").css("width", "55px");
        
        var $contentDiv = $parentDiv.parent("div").parent("div").parent("div").parent("div").parent("div").parent("div").children(".msg_body");
        //var $gaImage = $contentDiv.children(0).children(0);
        var $gaImage = $contentDiv.find('.GALoader img');

        //expand div
        $contentDiv.slideDown("slow");
        
        var srcPath='';
            if(IsJournalPage)
            {
            if(singleExpanded==true)
            {
                if (IsExpanded == false)
                {
                   srcPath="src";
                }
            }
            else
            {
                if(zero == true)
                {
                    //loading the first two images on JLP explictly.    
                    srcPath="src";
                   
                }else{
                    //load the image via lozy load plugin.    
                    srcPath="src1";
                }
            }
            }
            else
            {
             //load the image via lozy load plugin.    
                    srcPath="src";
            }
         
        if(srcPath != '')
        {
            //load GA/cover image
            if ($contentDiv.attr("itype") == "GA") {
                $gaImage.attr(srcPath, urlGAImage  + $gaImage.attr("Title"));
                
            } else if ($contentDiv.attr("itype") == "CoverImage") {
                $gaImage.attr(srcPath, urlCoverImage  + $gaImage.attr("Title"));
            }
         }
        

        //Load paragraph text
        var $pDiv = $contentDiv.children(".PLoader");
        var url = (urlParagraph + '/' + $pDiv.attr("url")).toLowerCase();
        var _post = {
            searchterm: $("#SearchTerm").val()
        };
        if ($pDiv.attr("title") == "In Progress") {
            $pDiv.load(url, _post);
            $pDiv.attr("title", "Contextual Paragraph");
        }
    }
    
    //    //load cover images on journal landing page issue tab
//        $(".CoverImageLoader").each(function(i, valueOfElement) {
//            var $gaImage = $(this).children(0).children(0);
//           $gaImage.attr("src", urlGAImage + '/' + $gaImage.attr("Title"));
//        });


    /* -----------------------------------------------------------------------------------------------------
    Start Region - Result Page Paging
    --------------------------------------------------------------------------------------------------------*/

    //Pager go button click
    $("#" + selectedCategory + " .go_button").unbind("click").bind("click", function(event) {
        var $PageNoTextBox = $(this).parent("div").parent("div").children("div").children(".page_no_box");
        if (validateText($PageNoTextBox)) {
            var selectedTab = $(this).parent("div").parent("div").parent("div").parent("div").parent("div").parent("div").attr("id");
            RetainPageNumberState(selectedTab, $PageNoTextBox.val());
            ReturnArticleURL(selectedTab);
            postPageNumber($PageNoTextBox.val());
           
        }
    });
    //Handle enter keypress on pagenumber
    $("#" + selectedCategory + " .page_no_box").keydown(function moveToPage(event) {
    
        if (event.keyCode == 13) {
            if (validateText($(this))) {
                var selectedTabOnKeyPress = $(this).parent("div").parent("div").parent("div").parent("div").parent("div").parent("div").attr("id");
                RetainPageNumberState(selectedTabOnKeyPress, $(".page_no_box").val());
                ReturnArticleURL(selectedTabOnKeyPress);
                postPageNumber($(".page_no_box").val());
            }
        }
    });
    //Disable Next Previous click
    $("#" + selectedCategory + " .PageLinkDisable").unbind("click").bind("click", function(event) {
        event.preventDefault();
    });
    //Next Previous Click
    $("#" + selectedCategory + " .PageLink").unbind("click").bind("click", function(event) {
        var selectedTabOnPreNextvBtnClick = $(this).parent("div").parent("div").parent("div").parent("div").parent("div").parent("div").attr("id");
        RetainPageNumberState(selectedTabOnPreNextvBtnClick, $(this).attr("Count"));
        ReturnArticleURL(selectedTabOnPreNextvBtnClick);
        postPageNumber($(this).attr("Count"));
        event.preventDefault();
    });

    // This function set result URL.
    function ReturnArticleURL(selectedTab) {
        if (selectedTab.toLowerCase() == "advancearticles") {
            resultURL = resultURLAdvanceArticle.toLowerCase();
        }
        else if (selectedTab.toLowerCase() == "themedissues") {
            resultURL = resultURLThemeIssues.toLowerCase();
        }
        else if (selectedTab.toLowerCase() == "issues" || selectedTab.toLowerCase() == "divarchivejournals") {
            resultURL = resultURLIssues.toLowerCase();
        }
        else if (selectedTab.toLowerCase() == "mostreadarticles") {
            resultURL = resultURLMostReadArticles.toLowerCase();
        }
        else if (selectedTab.toLowerCase() == "subjects") {
            resultURL = resultURLSubjects.toLowerCase();
        }
        else if (selectedTab.toLowerCase() == "divarticlecollectionlanding") {
        resultURL = resultURLSubjectArticles.toLowerCase();
        }
       
    }

    // This function retain the value of the page number.
    function RetainPageNumberState(selectedTab, value) {

        if (selectedTab.toLowerCase() == "all") {
            //set the page number value for 'All' tab.        
            $("#pageNumberAll").val(value);
        }
        else if (selectedTab.toLowerCase() == "journal") {
            //set the page number value for 'Journal Article' tab.
            $("#pageNumberJA").val(value);
        }
        else if (selectedTab.toLowerCase() == "ebooks") {
            //set the page number value for 'EBook' tab.
            $("#pageNumberBook").val(value);
        } else if (selectedTab.toLowerCase() == "advancearticles") {
            //set the page number value for 'Advance Article' tab.
            $("#pageNumberAdvanceArticle").val(value);
        }
        else if (selectedTab.toLowerCase() == "themedissues") {
            //set the page number value for 'Theme Issue' tab.
            $("#pageNumberThemedIssues").val(value);
        }
        else if (selectedTab.toLowerCase() == "databases") {
            //set the page number value for 'Database' tab.
            $("#pageNumberDatabases").val(value);
        }
        else if (selectedTab.toLowerCase() == "mostreadarticles") {
            //set the page number value for 'Most Read Articles' tab.
            $("#pageNumberMostReadArticles").val(value);
        }
        else if (selectedTab.toLowerCase() == "subjects") {
        //set the page number value for 'Most Read Articles' tab.
        $("#pageNumberSubjects").val(value);
    }
    else if (selectedTab.toLowerCase() == "divarticlecollectionlanding") {
    $("#pageNumberSubjectArticles").val(value); 
    }
    }
    
     // This function retain the value of the Expand/Collapse Status.
    function RetainExpandCollapseState(selectedTab, value) {
        if (selectedTab.toLowerCase() == "all") {
            //set the Expand/Collapse value for 'All' tab.        
            $("#expandCollapseAll").val(value);
        }
        else if (selectedTab.toLowerCase() == "journal") {
            //set the Expand/Collapse value for 'Journal tab.
            $("#expandCollapseAllJA").val(value);
        }
        else if (selectedTab.toLowerCase() == "books") {
            //set the Expand/Collapse value for 'Books' tab.
            $("#expandCollapseAllBook").val(value);
        }
        else if (selectedTab.toLowerCase() == "databases") {
            //set the Expand/Collapse value for 'Databases' tab.
            $("#expandCollapseAllDatabases").val(value);
        }
        else if (selectedTab.toLowerCase() == "advancearticles") {
            //set the Expand/Collapse value for 'Advance Article' tab.
            $("#expandCollapseAllAdvanceArticle").val(value);
        }
        else if (selectedTab.toLowerCase() == "issues") {
            //set the Expand/Collapse value for 'Theme Issue' tab.
            $("#expandCollapseAllIssues").val(value);
        }
        else if (selectedTab.toLowerCase() == "mostreadarticles") {
            //set the Expand/Collapse value for 'Most Read Articles' tab.
            $("#expandCollapseAllMostReadArticles").val(value);
        }
        else if (selectedTab.toLowerCase() == "divarticlecollectionlanding") {
            //set the Expand/Collapse value for 'Most Read Articles' tab.
        $("#expandCollapseAllSubjects").val(value);
        }
    }
    
    //Get the retained value for the Collapse/Expand link.
    function GetStatus(control)
    {
       var linkStatus='';
        if (control.val() != "") 
        {
          linkStatus = control.val();
        }
        return linkStatus;
    }
    
    // This function retain the value of the page number.
    function GetExpandCollapseState(selectedTab) {
        var expandAll = true;
        var status='Expand All';
        if (selectedTab.toLowerCase() == "advancearticles") {
             status = GetStatus($("#expandCollapseAllAdvanceArticle"));
        }
        else if (selectedTab.toLowerCase() == "all")
        {
             status = GetStatus($("#expandCollapseAll"));
        }
        else if (selectedTab.toLowerCase() == "journal")
        {
             status = GetStatus($("#expandCollapseAllJA"));
        }
        else if (selectedTab.toLowerCase() == "books")
        {
             status = GetStatus($("#expandCollapseAllBook"));
        }
        else if (selectedTab.toLowerCase() == "databases")
        {
             status = GetStatus($("#expandCollapseAllDatabases"));
        }
        else if (selectedTab.toLowerCase() == "issues")
        {
             status = GetStatus($("#expandCollapseAllIssues"));
        }
        else if (selectedTab.toLowerCase() == "mostreadarticles")
        {
            status = GetStatus($("#expandCollapseAllMostReadArticles"));
        }
        else if (selectedTab.toLowerCase() == "divarticlecollectionlanding") {
        status = GetStatus($("#expandCollapseAllSubjects"));
        }
        return status;
    }

    //Page number validation for text box
    //$("#" + selectedCategory + " .page_no_box").keyup(function() {
    function validateText(textBox) {
        var max = eval($("#" + selectedCategory + " .totalPages").html());
        var pageindex = eval($("#" + selectedCategory + " .txtPageIndex").val());
        var value = textBox.val();
        var orignalValue = value;
        val = value.replace(/[0-9]*/g, "");
        var msg = "Only Integer Values allowed.";

        if ((value < 1) || (value > max)) {
            textBox.val(pageindex);
            msg = "Integer value is not in range";
            alert(msg);
            return false;
        }

        if (val != '') {
            orignalValue = orignalValue.replace(/([^0-9].*)/g, "")
            textBox.val(pageindex);
            alert(msg);
            return false;
        }

        return true;
    };
    //});
    /* -----------------------------------------------------------------------------------------------------
    End Region - Result Page Paging
    --------------------------------------------------------------------------------------------------------*/


    /* -----------------------------------------------------------------------------------------------------
    Start Region - Save abstract like endnote
    --------------------------------------------------------------------------------------------------------*/

    //Check box select all
    $("#" + selectedCategory + " .chkSelectAll").unbind("click").bind("click", function() {
        $("#" + selectedCategory + " .toCheck").attr('checked', $("#" + selectedCategory + " .chkSelectAll").is(':checked'));
    });

    //Save Abstract area, Like Endnote
    $("#" + selectedCategory + " .btnSaveResult").unbind("click").bind("click", function(event) {
        event.preventDefault();
        var markedIDs = new Array; markedIDs
        var referenceManagerType = "";
        var selectedAbstractFormat = $("#" + selectedCategory + " .save_record_list_value_s4_jrnls").val();
        if (selectedAbstractFormat == "BibTex") {
            referenceManagerType = "Bibtex";
        }
        else {
            referenceManagerType = "EndNote";
        }

        var _type = null;
        switch (selectedCategory.toLowerCase()) {
            case "ebooks": _type = "Chapter"; break;
            case "journal": _type = "Article"; break;
            case "all": _type = "All"; break;
            default: _type = "All"; break;
        };
        $("#" + selectedCategory + " .toCheck").each(function(i) {
            if ($(this).is(':checked')) {
                markedIDs.push($(this).val());
            }
        });

        if (markedIDs.length > 0) {
            var _post = {
                downloadType: _type,
                markedIDs: markedIDs,
                managerType: referenceManagerType
            };
            DownloadFile(urlFormatedResult, _post, 'post');
        }
        else
        { alert('Please select search record'); }
    });



    /* -----------------------------------------------------------------------------------------------------
    End Region - Save abstract like endnote
    --------------------------------------------------------------------------------------------------------*/

    /* -----------------------------------------------------------------------------------------------------
    Start Region - Save PDF
    --------------------------------------------------------------------------------------------------------*/

    $(".lnkPDF").unbind("click").bind("click", function(event) {
        var url = $(this).attr("href");
        window.open(url.toLowerCase());
        event.preventDefault();
    });

    /* -----------------------------------------------------------------------------------------------------
    End Region - Save PDF
    --------------------------------------------------------------------------------------------------------*/

    /* -----------------------------------------------------------------------------------------------------
    Start Region - Interactive Article Download
    --------------------------------------------------------------------------------------------------------*/

    $(".lnkIArticle").unbind("click").bind("click", function(event) {
        var url = $(this).attr("href");
        window.open(url.toLowerCase());
        event.preventDefault();
    });

    /* -----------------------------------------------------------------------------------------------------
    End Region - Interactive Article Download
    --------------------------------------------------------------------------------------------------------*/

    //tooptip
    //JT_init();

} //End of function InitializeResultPage

/* -----------------------------------------------------------------------------------------------------
End - Result page expand collapse functionality
--------------------------------------------------------------------------------------------------------*/

/* -----------------------------------------------------------------------------------------------------
Start Region - Facet load unload
--------------------------------------------------------------------------------------------------------*/

//Load facets asynchronously
function LoadFacets() {
    var panel = $("#" + selectedCategory + " .facet");
    var $tab = $(".ui-tabs-selected a");
    var _post = {
        searchterm: $("#SearchTerm").val(),
        category: selectedCategory
    };
    $.post(urlFacets, _post, function(result) {
        $(panel).html(result);
        EvtFacetLoad();
        SaveSearchExpandState();
    });
}
//Facet
function EvtFacetLoad() {
    //For Facet links show hide
    //Hide All
    $("#" + selectedCategory + " .right_highlight_txt_red_hidden").hide();

    //Toggle based on click
    $("#" + selectedCategory + " .facets_view_all_div").unbind("click").bind("click", function(event) {
        event.preventDefault();
        $("#" + selectedCategory + " .right_highlight_txt_red_hidden").hide();
        $("#" + selectedCategory + " .facets_view_all_div").show();
        var $parentDivFacet=$(this).parent("div").parent("div").parent("div");
        $parentDivFacet.children("div").children("ul").children(".right_highlight_txt_red_hidden").show();
        $parentDivFacet.parent("div").children(".right_highlight_txt_red_hidden").show();
        $(this).parent("div").parent("div").children("div").children(".facets_view_all_div").hide();
    });

    //post facet search criteria to server
    $("#" + selectedCategory + " .lnk_highlight_txt_red").unbind("click").bind("click", function(event) {
        var resultForm = $("#frmUpdateSearchSetting");
        var fcValue = $(this).attr("Title");
        var fcType = $(this).parent("div").attr("Title");
        var fcContentType = $(this).parent("div").parent("div").attr("Title");

        //resultForm.attr('action', urlResult);
        
        resultForm.append('<input id="fcValue" name="fcValue" type="hidden" value="' + fcValue + '" />');
        resultForm.append('<input id="fcType" name="fcType" type="hidden" value="' + fcType + '" />');
        resultForm.append('<input id="fcContentType" name="fcContentType" type="hidden" value="' + fcContentType + '" />');
        resultForm.append('<input id="category" name="category" type="hidden" value="' + selectedCategory + '" />');
        resultForm.submit();
        event.preventDefault();
    });

    //Remove facet
    $("#" + selectedCategory + " .rFilter").unbind("click").bind("click", function(event) {
        var fcType = $(this).parent("div").parent("div").children("div").attr("Title");
        var fcRValue = $(this).parent("div").parent("div").children("div").children("*:first").attr("Title")
        removeFacet(fcType, fcRValue);
        event.preventDefault();
    });

    //Remove filter from top link click
    $(".rTopFilter").unbind("click").bind("click", function(event) {
        var fcType = $(this).parent("div").parent("div").children("div").children("span:first").text()
        var fcRValue = $(this).parent("div").parent("div").children("div").children("span").next().text();
        removeFacet(fcType, fcRValue);
        event.preventDefault();
    });

    //Remove filter from top link click
    $(".rTopFilterDisable").unbind("click").bind("click", function(event) {
        alert('Disable Link');
        event.preventDefault();
    });


    //Remove All
    $(".rAllFilter").unbind("click").bind("click", function(event) {
        removeFacet('*', '*');
        event.preventDefault();
    });
} //End for facet load

//fucntion for remove facet(s)
function removeFacet(fcType, fcRValue) {
    var resultForm = $("#frmUpdateSearchSetting");
    //resultForm.attr('action', urlResult);
    resultForm.append('<input id="fcRValue" name="fcRValue" type="hidden" value="' + fcRValue + '" />');
    resultForm.append('<input id="fcType" name="fcType" type="hidden" value="' + fcType + '" />');
    resultForm.append('<input id="category" name="category" type="hidden" value="' + selectedCategory + '" />');
    resultForm.submit();
}
/* -----------------------------------------------------------------------------------------------------
End Region - Facet load unload
--------------------------------------------------------------------------------------------------------*/

//Post Page Number to Server
function postPageNumber(_page) {
    //Facet Load
    $("#" + selectedCategory).hide();
    $("#showProgress").show();
    //$("#progressBar").toggle();
    var $tab = $(".ui-tabs-selected a");
    var panel = $("#" + $tab.attr("url"));
    if (selectedCategory.toLowerCase() == "divarticlecollectionlanding") {
        var _post = {
        name: serCode,
        sid: sid,
        sercode: serCode,
        issnprint: issnPrint,
        issnonline: issnOnline,
        themeId: themeId,
            pagenumber: _page
        };
    }
    else {
        var _post = {
            searchterm: $("#SearchTerm").val(),
            category: selectedCategory,
            resultcount: $tab.attr("Count"),
            name: serCode,
            jname: themeJournalName,
            pagenumber: _page,
            pageno:_page,
            themeId: themeId,
            issueID: issueID_pn,
            issnprint: issnPrint_pn,
            issnonline: issnOnline_pn,
            isContentAvailable: isContentAvailable,
            articleSubmissionUrl: articleSubmissionUrl,
            doiList: doiList,
            MostReadCleanupDuration: MostReadCleanupDuration
        };
    }
    //load journal home page tab
    if (serCode != '') {
            $("#" + selectedCategory).load(resultURL, _post, function() {
            //show progress
            $("#showProgress").hide();
            $("#" + selectedCategory).show();
        });
    }
    else {
       panel.load(resultURL, _post, function() {
            //show progress
            $("#showProgress").hide();
            $("#" + selectedCategory).show();
        });
    }
}


//Download function for ajax call
function DownloadFile(url, data, method) {
    //url and data options required
    if (url && data) {
        //data can be string of parameters or array/object
        data = typeof data == 'string' ? data : jQuery.param(data);
        //split params into form inputs
        var inputs = '';
        jQuery.each(data.split('&'), function() {
            var pair = this.split('=');
            inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1].split('%0A')[0] + '" />';
        });
        //send request
        jQuery('<form action="' + url.toLowerCase() + '" method="' + (method || 'post') + '">' + inputs + '</form>').appendTo('body').submit().remove();
    };
};

function setPager(count) {
    //call did you mean
    if (count < 1) {
        getDidYouMean();
    }

    $("#" + selectedCategory + " .totalPages").each(function(i, item) {
        $(this).html(Math.ceil(count / pageSize));
    });
    if (count > pageSize) {
        $("#" + selectedCategory + " .next_button").each(function(i, item) {
            var countVal = $("#" + selectedCategory + " .page_no_box").val();
            var parseCountVal = parseInt(countVal);
            parseCountVal = parseCountVal + 1;
            $(this).html('<a title="Next" count=' + parseCountVal + ' class="PageLink" href="' + resultURL.toLowerCase() + '"><img alt="Next Page" src="' + urlImgNext + '" border="0"></a>');
        });
    }
    
    InitializeResultTabJavascript();
}
//Did you mean
function getDidYouMean() {
    if (typeof (correctedSearchTerm) != "undefined" && typeof (searchKeyword) != "undefined") {
        $.post(correctedSearchTerm, { freeText: searchKeyword }, function(data) {
            if (data != "") {
                var $lnkDidYouMean=$("#lnkDidYouMean");
                $lnkDidYouMean.html(data);
                $lnkDidYouMean.attr("href", urlDidYouMean + '&freeText=' + data);
                $(".clsDidYouMean").fadeIn(2000);
            }
        });
    }
}

function setDynamicMarginTopHide(id) {
    $(id).css({ 'margin-top': ($("#ps_container").height()+107) + 'px' });
}

function setDynamicMarginTopShow(id) {
    if (jQuery.browser.version == "7.0") {
       $(id).css({ 'margin-top': (137 - $("#ps_content_container").height()) + 'px' });
    } else {
        $(id).css({ 'margin-top': (127 - $("#ps_content_container").height()) + 'px' });
        }
}

function SaveSearchExpandState() {
    var $saved_search_criteria = $(".saved_search_criteria");
    var $save_this_search = $(".save_this_search");
    var $save_this_search_expand = $(".save_this_search_expand");
    var $save_search_help = $(".save_search_help");
    var $save_this_search_collapsed = $(".save_this_search_collapsed");
    var $search_criteria_text = $("#search_criteria_text");
    var $error_message = $(".error_message");
    var $save_search_loader = $(".save_search_loader");
    var $ExpandState = $("#ExpandState");
    var $EmailAlertState = $("#EmailAlertState");

    if ($ExpandState.val() == "") {
        $saved_search_criteria.hide();
        $(".save_seach_cont").show();
        $save_this_search.hide();
        $save_this_search_collapsed.show();
        $(".search_result_bottom_right_wrapper_new").removeClass("saveSearch_setmargin18_OnExpand").addClass("deafult_topmargin_facet");
    }
    else {

        if ($ExpandState.val() == "2") {
            //Display Successful save popup state
            $saved_search_criteria.show();
            $(".save_seach_cont").hide();
            $save_this_search.hide();
            $save_search_loader.hide();
            $save_this_search_collapsed.hide();
            $(".search_result_bottom_right_wrapper_new").removeClass("deafult_topmargin_facet");
        }
        else if ($ExpandState.val() == "1") {
            $save_this_search.slideDown("slow");
            $save_this_search_collapsed.hide();
            $saved_search_criteria.hide();
            $(".search_result_bottom_right_wrapper_new").removeClass("deafult_topmargin_facet").addClass("saveSearch_setmargin18_OnExpand");
        }
        else if ($ExpandState.val() == "3") {

            $save_search_loader.hide();
            $saved_search_criteria.hide();
            $save_this_search.hide();
            $save_this_search_collapsed.hide();
            $error_message.show();
            $(".search_result_bottom_right_wrapper_new").removeClass("deafult_topmargin_facet");
            $(".search_result_bottom_right_wrapper_new").removeClass("saveSearch_setmargin18_OnExpand").addClass("deafult_topmargin_save_error_facet");
            
        }
        else {
            $saved_search_criteria.hide();
            $save_this_search.hide();
            $save_this_search_collapsed.show();
            $(".search_result_bottom_right_wrapper_new").removeClass("saveSearch_setmargin18_OnExpand").addClass("deafult_topmargin_facet");
        }
    }
}

