/**
 *
 *
 */
function myFullTextPopUp() {
    // remove spinner once full text popup had loaded, needed due to some times a lag in loading no idea if its failed or not
    $(".fullTextIframe").removeClass("progress");
}

var ajaxCall = {
    /**
     * @param    string    typeOfCall
     * @param    string    fileToGet
     * @param    string    element
     * @param    string    errorMessage
     * @param    function  optionalCallFunction
     */
    call: function(typeOfCall, fileToGet, element, errorMessage, optionalCallFunction) {
        var $element = $(element);
        $element.addClass("progress");
        $.ajax({
            type:typeOfCall,
            url:fileToGet,
            success:function(dataResp) {
                $element.removeClass("progress");
                $element.append(dataResp);
                if (typeof optionalCallFunction === "function") {
                    optionalCallFunction();
                }
            },
            error:function(Xhr, statusMsg) {
                $element.removeClass("progress").html(errorMessage);
                //console.log(errorMessage);
            }
        });
    }
};

$(document).ready(function() {
    //$(".searchoption").click(function(e) {
    $(".searchoptionmenu").on("click", ".searchoption", function(e) {
        var $this = $(this),
            $qsForm = $("#quicksearchform");
        if ($("#search-value1").val() !== "") {
            if ($this.hasClass("searchall")) {
                $(".navitem_search #option1").val("tka");
            }
            if ($this.hasClass("searchtitle")) {
                $(".navitem_search #option1").val("title");
            }
            if ($this.hasClass("searchpubtitle")) {
                $qsForm.append("<input type='hidden' name='database' value='2' />");
                $qsForm.find("#option1").remove();
                $qsForm.append("<input type='hidden' name='title' value='" + $("#search-value1").val() + "' />");
                $qsForm.find("#search-value1").attr("name","x");
            }
            if ($this.hasClass("searchauthor")) {
                $qsForm.append("<input type='hidden' name='option2' value='author' />");
                $qsForm.find("#option1").remove();
                $qsForm.append("<input type='hidden' name='value2' value='" + $("#search-value1").val() + "' />");
                $qsForm.find("#search-value1").attr("name","x");
            }
            if ($this.hasClass("searchsubscriptions")) {
                $qsForm.append("<input type='hidden' name='freetype' value='subscribed' />");
            }
            if ($this.hasClass("searchoa")) {
               $qsForm.append("<input type='hidden' name='freetype' value='openaccess' />");
            }
            if ($this.hasClass("searchfree")) {
               $qsForm.append("<input type='hidden' name='freetype' value='freecontent' />");
            }
            if ($this.hasClass("searchallaccess")) {
               $qsForm.append("<input type='hidden' name='freetype' value='allfree' />");
            }
            $qsForm.submit();
        } else {
            alert("Please enter a search term first before choosing a filter option");
        }
        return false;
    });

    //$("#subjectarea").mouseover(function() {
    $(document).on("mouseover", "#subjectarea", function(e) {
        $("#subjectlist").show();
    });

    //$("ul.toprightsidenav").mouseout(function() {
    $(document).on("mouseout", "ul.toprightsidenav", function(e) {
        $("#subjectlist").hide();
    });

    // 508 accessibility work, get focus if error logging in
    if ($("#form-signin .error").length > 0 ) { // checks for error message then give focus to username input
        $(".navbar-toggle.signin-section-nav-button").trigger("click");
        $(".signInLink").addClass("open");
        // $(".signInLink").trigger("click");
        $(".signin-tools").toggleClass("show-login-box");
        $("#username").focus();
        $(".signInLink").trigger("click");
    }

    // share icons in more drop down need a link to get focus to trigger a drop down.
    //$(".Section508Share").click(function(e) {
    $(".shareContent").on("click", ".Section508Share", function(e) {
        e.preventDefault();
    });

    //$(".Section508Share").focus(function() {
    $(".shareContent").on("focus", ".Section508Share", function(e) {
        $(this).parent().addClass("open");
    });

    $("form.advancedSearch").submit(function(e) {
        if ($("#title-box").val() === "" && $("#author").val() === "" && $("#journal-box").val() === "") {
            e.preventDefault();
            $("#title-box").focus();
            $(".searchForFields .rust").append("<div class=\"searcherror\">A search term, author or publication title is required</div>");
        }
    });

    //$("#title-box").keypress(function() {
    $("#search-form").on("keypress", "#title-box", function() {
        $(".searcherror").remove();
    });

    //$("#author").keypress(function() {
    $("#search-form").on("keypress", "#author", function(e) {
        $(".searcherror").remove();
    });

    //$("#journal-box").keypress(function() {
    $("#search-form").on("keypress", "#journal-box", function(e) {
        $(".searcherror").remove();
    });

    if ($(".perRegLogin .error").length > 0) {
        var $el = $(".perRegLogin .error").parent().find('input');
        $el.addClass("invalidField");
        $el[0].focus();
        // $(".form-input-text.invalidField").focus();
    }

    //$(".form-input-text.invalidField").keypress(function() {
    $(document).on("keypress", ".form-input-text.invalidField", function(e) {
        $(this).parent().find(".error").remove();
    });

    //$(".expandlinks").click(function(e) {
    $(document).on("click", ".expandlinks", function(e) {
        e.preventDefault();
        var $this = $(this);
        if ($this.find(".plus").hasClass("hide")) {
            $this.find(".plus").removeClass("hide");
            $this.find(".minus").addClass("hide");
            $this.parent("span").parent("li").find(".expandable").slideUp();
        }  else {
            $this.find(".plus").addClass("hide");
            $this.find(".minus").removeClass("hide");
            $this.parent("span").parent("li").find(".expandable").slideDown();
        }
        return false;
    });

    $(".expandlinks").click();

    function handleFilterOptions(e) {
        var $filterform = $("#filterform"),
            classList = e.target.classList,
            ok2Submit = false,
            newInput = "",
            newValue = "";
        if (classList.contains("allfilter")) {
            newValue = "all";
            ok2Submit = true;
        }
        if (classList.contains("subsfilter")) {
            newValue = "subs";
            ok2Submit = true;
        }
        if (classList.contains("freefilter")) {
            newValue = "free";
            ok2Submit = true;
        }
        if (ok2Submit) {
            newInput = "<input type='hidden' value='" + newValue + "' name='j_availability' />";
            $filterform.append(newInput);
            $filterform.submit();
        }
    }

    $(".filteroptions").on("click", handleFilterOptions);

    $(".searchoptionsbutton").on("click", function(e) {
        e.preventDefault();
        return false;
    });

    $(".printButton").on("click", function(e) {
        window.print();
        return false;
    });

    $(".fulltext").on("click", function(e) {
        var $this = $(this),
            downloadURL = $this.attr("data-popup");
        if (downloadURL) {
            popup(downloadURL,'downloadWindow','900','800');
        }

        if ($this.hasClass("html") || $this.hasClass("pdf")) {
            var pagegaAccount = $(".pubGAAccount").text();
            if (pagegaAccount) {
                // console.log(pagegaAccount);
               (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                   (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                   m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                   })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

                   ga('create', '+ pagegaAccount +', 'ingentaconnect.com');
                   ga('send', 'pageview');
            }
        }
    });

    function checkForCookie() {
        var ca = document.cookie.split(";"),
            nameEQ = "cookiepolicypopupIC02=",
            ShowHidePopUp = false;
        for (var i = 0; i < ca.length; i++) {
            if (ca[i].indexOf(nameEQ) === 1) {
                ShowHidePopUp = false;
                break;
            } else {
                ShowHidePopUp = true;
            }
        }

        if (ShowHidePopUp) {
            $(".mainCookiesPopUp").fadeIn().delay(7000).fadeOut();
        }
    }

    // sets cookie if they agree to it..
    // $(".setCookie").click(function(e) {
    $(document).on("click", ".setCookie", function(e) {
        var curDate = new Date(),
            expDate = new Date();
        // Set expiry for 3 years...
        expDate.setMonth(curDate.getMonth() + 36);
        document.cookie = "cookiepolicypopupIC02=1; expires=" + expDate.toUTCString() + "; path=/";
        $(".setCookie").text("Cookie Policy Approved");
        e.preventDefault();
    });

    //$(".closePolicyPopup").click(function() {
    $(document).on("click", ".closePolicyPopup", function(e) {
        $(".mainCookiesPopUp").hide();
    });

    // checks for Cookie on first load
    checkForCookie();

    //$(".opendeleteFolder a").click(function(e){
    $(document).on("click", ".opendeleteFolder a", function(e){
        var $this = $(e.target),
            $thisClass = $this.attr("class"),
            $itemFolderContainer = $this.parent().parent();

        if ($thisClass === 'openfolder') {
            $itemFolderContainer.find(".fa-folder-o").hide();
            $itemFolderContainer.find(".fa-folder-open-o").show();
        } else {
            $itemFolderContainer.find(".fa-folder-open-o").hide();
            $itemFolderContainer.find(".fa-folder-o").show();
        }
    });

    // full text popup
    $(document).on("click", ".fulltextSTOP", function(e){
        e.preventDefault();
        var $this = $(this),
            winWidth  = $(window).width(),
            winHeight = $(window).height(),
            newWidth  = winWidth - (winWidth * 0.45),
            newHeight = winHeight - (winHeight * 0.09),
            ifra,
            pagesValues,
            startPos = 0,
            endPos = 0,
            pageCount = 0;

        $(".fullTextContainer").remove(); // remove or duplicate popups and not all dialog branded
        $(".fullTextIframe").remove();
        $("body").append("<div id='dialog' class='fullTextContainer' title='" + $(".abstract-heading").text() + "'></div>");

        // work out window size and adjust as needed
        ifra = document.createElement("IFRAME");
        ifra.setAttribute("src",$this.attr("data-fulltext-url"));
        ifra.setAttribute("onload","myFullTextPopUp()");  // calls a function that removes the spinner once iframe loaded as can be a delay
        ifra.setAttribute("class","fullTextIframe progress");
        ifra.style.width = "100%";

        // hack below to set iframe height size just bigger than pdf, issue on Ipads not scrolling. CSS hack to assist this as well.
        pagesValues = $(".pagesNum").html();
        startPos = pagesValues.indexOf('\(') + 1;
        endPos = pagesValues.indexOf('\)', startPos);
        pageCount = pagesValues.substring(startPos,endPos);
        ifra.style.height = (pageCount * 1200) + "px";

        $(".fullTextContainer").append(ifra);

        $("#dialog").dialog({
            resizable:true,
            modal: true ,
            width:newWidth,
            height:newHeight,
            buttons: {
                "Close": function() {
                    $(this).dialog("close");
                    $(".fullTextIframe").remove();
                }
            }
        });
    });

    //##### Home Page AJAX Calls

   // Home page main carousel, bootstrap own carousel, but now tweaked to call contents in via ajax
   if ($(".ingentaIntro").length > 0) {
      ajaxCall.call("GET",
         "/docs/homeMainCarouselContents.html",
         "#carousel-example-generic",
         "Please refresh the page, there seemed to be an issues loading the content");
      // Home page add carousel, as above ...
      ajaxCall.call("GET",
         "/docs/carouselContentsAds.html",
         "#carousel-example-generic-sidebar",
         "Please refresh the page, there seemed to be an issues loading the content");
   }

    // Home page Fast Track Article call to ajax
    if ($(".homeLeftArticles").length > 0) {
        ajaxCall.call("GET",
            "/docs/fastTrackArticle.html",
            ".homeLeftArticles ul",
            "Please refresh the page, there seemed to be an issues loading the content",
            function trimMostRecentArticles() {
                var mostRecentArticles = $(".homeLeftArticles ul li");
                // console.log(mostRecentArticles);
                $.each(mostRecentArticles,function(index, value) {
                    var $this = $(this),
                        $articleLink = $this.find("h4 a"),
                        $articleSpan = $this.find("span.article"),
                        articleLinkattr = $articleLink.attr("href"),
                        articleSpanHtml = $articleSpan.html(),
                        truncatedArticle = articleSpanHtml ? articleSpanHtml.substring(0, 650) : "";
                    truncatedArticle += '...<a href="'+ articleLinkattr +'">more</a></xhtml:span>';
                    $articleSpan.html(truncatedArticle);
                });
            });
    }

    // validation for 'Remove' on shopping cart
    var form = $(".cartForm"),
        checked = false,
        cartForm = $("form").hasClass(".cartForm");

    $(".cartForm").on("click", ".btn.btn-general.icbutton", function(e) {
        //check checkboxes

        $(".cartForm input[type=checkbox]").each(function() {
            checked = $(this).attr('checked');
            if (checked) {
                $(".cartForm input[type=checkbox]").each(function() {
                    $(this).rules('add', {required: false});
                });
                return false;
            }
        });

        if (!checked && cartForm === true) {
            form.validate();
            $(".cartForm input[type=checkbox]").each(function() {
                $(this).rules('add', {
                    required: true,
                    messages: {
                        required: "You must select an item"
                    }
                });
            });
        }
    });

    // MoreLikeThis (Related Articles)
    function relatedArticles() {
       var morelikethisurl = $("#hiddenContext").text() + "/search/morelikethis",
         pubrelatedcontentids = $("#hiddenmorelikethisids").text(),
         webid = "/" + $("#hiddenmorelikethiswebid").text(),
         fields = $("#hiddenmorelikethisfields").text(),
         restrictions = $("#hiddenmorelikethisrestrictions").text(),
         number = $("#hiddenmorelikethisnumber").text(),
         numbershown = $("#hiddenmorelikethisnumbershown").text(),
         numbershownMax = $("#hiddenmorelikethisnumbershownMax").text(),
         numberIncrement = $("#hiddenmorelikethisnumbershownIncrement").text(),
         numbershowndefault = $("#hiddenmorelikethisnumbershowndefault").text(),
         data = {
            "pubrelatedcontentids": pubrelatedcontentids,
            "webid": webid,
            "fields": fields,
            "restrictions": restrictions,
            "number": number,
            "numbershown": numbershown,
            "numbershownMax":numbershownMax,
            "numberIncrement":numberIncrement,
            "numbershowndefault":numbershowndefault
         };

         // Since we want to handle failure as well as success,
         // we need to use ajax() rather than post().
         // $.post fails silently on error!
         $.ajax({
            type : "POST",
            url : morelikethisurl,
            data : data,
            dataType: "text",
            success: function(resp) {
               var target = $("#morelikethiscontent").get(0);
               target.innerHTML = resp;
               $(".morelikethisloading").remove();
            },
            error : function(resp) {
            // var cMsg = "'MoreLikeThis' AJAX POST to '" +
            // morelikethisurl + "' failed: " + resp.status + " (" +
            // resp.statusText + ")";
            $(".morelikethisloading").remove();
            // console.log(cMsg);
            }
         });
    } // end of function

    //$(".morelink a").live("click",function(e) {
    $(document).on("click", ".morelink a", function(e) {
        e.preventDefault();
        // parseInt() should ALWAYS specify the base...
        var $this = $(this),
            likethisnum = parseInt($("#hiddenmorelikethisnumber").html(), 10) || 0,
            likethisnumshow = parseInt($("#hiddenmorelikethisnumbershown").html(), 10) || 0,
            likethisnumMax = parseInt($("#hiddenmorelikethisnumbershownMax").html(), 10) || 0,
            likethisnumshowdefault = parseInt($("#hiddenmorelikethisnumbershowndefault").html(), 10) || 0,
            likethisnumshowIncrement = parseInt($("#hiddenmorelikethisnumbershownIncrement").html(), 10) || 0;

        if (likethisnumshow < likethisnumMax && likethisnumshow === likethisnumshowdefault) {
            // console.log("first");
            $this.parent().html("<img class=\"morelikethisloading\" src=\"/images/admin/spinner.gif\" alt=\"Loading\" />");
            $("#hiddenmorelikethisnumber").text(likethisnumshowIncrement + 1);
            $("#hiddenmorelikethisnumbershown").text(likethisnumshowIncrement);
//          removed as possibly causing downturn in TrendMD clicks
//          relatedArticles();
            $("#hiddenmorelikethisnumber").text(likethisnumMax);
            $("#hiddenmorelikethisnumbershown").text(likethisnumMax);
        } else {
            // console.log("second");
            $this.parent().html("<img class=\"morelikethisloading\" src=\"/images/admin/spinner.gif\" alt=\"Loading\" />");
//          removed as possibly causing downturn in TrendMD clicks
//          relatedArticles();
        }
    });
    if ($("#hiddenmorelikethisids").size() > 0) {
//     removed as possibly causing downturn in TrendMD clicks
//     relatedArticles();
    }
    //$(".morelinkTruncate a").click(function(e) {
    $(document).on("click", ".morelinkTruncate a", function(e) {
        // add class
        e.preventDefault();
        var $listItem = $(this).parent().parent().find(".expandedList");

        if ($listItem.hasClass("hidden")) {
            $listItem.removeClass("hidden");
            $(".morelinkTruncate .more").html("&gt; Less");
        } else {
            $listItem.addClass("hidden");//hasClass();
            $(".morelinkTruncate .more").html("&gt; More");
        }
    });

    // Insert the current year into the copyright year in the footer...
    if ($(".copyyear").length > 0) {
        var today = new Date(),
            yyyy = today.getUTCFullYear();
        $(".copyyear").html(yyyy);
    }

    // Hide navigation on payment page by default
    $(".rightnav").hide();

    // Show navigation on payment page
    $(".container").on("click", "#shownavlink", function(e) {
        $("#shownav").hide();
        $(".rightnav").slideDown();
    });

    // Hide navigation on payment page
    $(".container").on("click", "#hidenavlink", function(e) {
        $("#shownav").show();
        $(".rightnav").slideUp();
    });

    // Saved Searches functionality...
    $(".closefolder").hide();
    $(".foldercontents").hide();
    $(".savedSearches").on("click", ".openfolder", function(e) {
        var $this = $(this);
        $this.parents(".savedsearchfolder").find(".foldercontents").slideDown();
        $this.hide();
        $this.parent("div").find(".closefolder").show();
        return false;
    });
    $(".savedSearches").on("click", ".closefolder", function(e) {
        var $this = $(this);
        $this.parents(".savedsearchfolder").find(".foldercontents").slideUp();
        $this.hide();
        $this.parent("div").find(".openfolder").show();
        return false;
    });
    $(".savedSearches").on("click", ".deletefolder", function(e) {
        if (confirm("Are you sure you want to delete this folder?")) {
            return true;
        } else {
            return false;
        }
    });

    // Counter page start end check...
    $("#counterfour\\:request-reports").on("click", function() {
        var sMonth,
            eMonth,
            startyearmonth,
            endyearmonth;
        sMonth = $("#counterfour\\:startMonth").val();
        if (sMonth < 10) {
            sMonth = "0" + sMonth;
        }
        eMonth = $("#counterfour\\:endMonth").val();
        if (eMonth < 10) {
            eMonth = "0" + eMonth;
        }
        startyearmonth = $("#counterfour\\:startYear").val() + sMonth;
        endyearmonth = $("#counterfour\\:endYear").val() + eMonth;
        if (startyearmonth > endyearmonth) {
            $("#end-month-year-message").html("Please select an valid date range; End Date should be after Start Date.");
            return false;
        } else {
            $("#end-month-year-message").html("");
            $("#counterfour").submit();
        }
    });

});
