/*
 * $HeadURL:: http://ambraproject.org/svn/ambra/head/ambra/webapp/src/main/webapp/javasc#$
 * $Id: init_article_metrics.js 7723 2009-06-03 00:23:44Z ssterling $
 *
 * Copyright (c) 2006-2010 by Public Library of Science
 * http://plos.org
 * http://ambraproject.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
dojo.require("dojo.fx");

dojo.addOnLoad(
  function() {
    var almService = new alm();

    var doi = dojo.byId('doi').value;
    var articleDate = dojo.byId('articlePubDate').value;

    if(almService.validateArticleDate(articleDate)) {
      if(almService.isArticle(doi)) {
        almService.getRelatedBlogs(doi,setRelatedBlogs, setRelatedBlogError);
        almService.getCites(doi, setCites, setCitesError);
        almService.getSocialBookMarks(doi, setBookmarks, setBookmarksError);
        almService.getIDs(doi, setIDs, setIDsError);
        almService.getCounter(doi, setChartData, setChartDataError);
      } else {
        setNoDataMessageError('cumulativeData');
        dojo.fx.wipeIn({ node:'cumulativeData', duration: 1000 }).play();

        setNoDataMessageError('relatedBlogPosts');
        dojo.fadeOut({ node:'relatedBlogPostsSpinner', duration: 1000 }).play();

        setNoDataMessageError('relatedCites');
        dojo.fadeOut({ node:'relatedCitesSpinner', duration: 1000 }).play();

        setNoDataMessageError('relatedBookmarks');
        dojo.fadeOut({ node:'relatedBookmarksSpinner', duration: 1000 }).play();
        setIDsError(null);
      }
    } else {
      //The article is less then 2 days old, and there is no data
      //give the user a good error message
      setChartDataError('This article was only recently published. ' +
        'Although we update our data on a daily basis (not in real time), there may be a 48-hour ' +
        'delay before the most recent numbers are available.<br/><br/>');

      dojo.fx.wipeIn({ node:'cumulativeData', duration: 1000 }).play();

      setDelayMessageError('relatedBlogPosts');
      dojo.fadeOut({ node:'relatedBlogPostsSpinner', duration: 1000 }).play();

      setDelayMessageError('relatedCites');
      dojo.fadeOut({ node:'relatedCitesSpinner', duration: 1000 }).play();

      setDelayMessageError('relatedBookmarks');
      dojo.fadeOut({ node:'relatedBookmarksSpinner', duration: 1000 }).play();
    }
  }
);

function setChartDataError(message) {
  setError('cumulativeData', message);
}

function setChartData(response) {
  dojo.byId('cumulativeData').style.display = 'none';
  dojo.fadeOut({ node:'cumulativeDataSpinner', duration: 1000 }).play();

  if(response == null || response.article == null
      || response.article.source == null || response.article.source.length < 1
      || response.article.source[0].citations == null || response.article.source[0].citations.length < 1
      || response.article.source[0].citations[0].citation == null
      || response.article.source[0].citations[0].citation.views == null
      ) {
    setDelayMessageError('cumulativeData');
    return;
  }

  var pubDateInMilliseconds = new Number(dojo.byId('articlePubDate').value);
  var pubDate = Date.getDateFromGMT(pubDateInMilliseconds);
  var cumulativeChart = new reporting.articleViewsCumulative();
  var almService = new alm();
  var data = almService.massageCounterData(response.article.source[0].citations[0].citation.views, pubDateInMilliseconds);
  //Ruby returns seconds past 1/1/1970, not milliseconds.
  var updatedDate = new Date((new Number(response.article.source[0].updated_at)) * 1000);
  var july1st2005InMilliseconds = 1120176000000;

  if(data.total == 0) {
    setDelayMessageError('cumulativeData');
  } else {
    var html = "<span><strong>Total Article Views: </strong></span>";
    html = html + "<span class=\"highlight\">" + data.total + "</span> from ";
    html = html + "<strong>" + Date.formatDate(pubDate) + "</strong> (publication date) - ";
    html = html + "<strong>" + Date.formatDate(updatedDate) + "</strong>*";

    html = html + "<div><h3>Breakdown by View Type</h3></div>";
    html = html + "HTML Page Views: <strong>" + data.totalHTML + "</strong><br/>";
    html = html + "PDF Downloads: <strong>" + data.totalPDF + "</strong><br/>";
    html = html + "XML Downloads: <strong>" + data.totalXML + "</strong>";

    html = html + "<h3 class=\"normFont\"><strong>Cumulative Views</strong> from ";
    html = html + "<strong>" + Date.formatDate(pubDate) + "</strong> (publication date) - ";
    html = html + "<strong>" + Date.formatDate(updatedDate) + "</strong>*</h3>";
    html = html + "<div id=\"cumulativeGraphYLabel\">Views</div>";
    html = html + "<div id=\"cumulativeGraph\"></div>"; // Here is where the graph is added to page.
    html = html + "<div id=\"cumulativeGraphXLabel\">Months</div>";
    html = html + "<span class=\"footnote\">*Data refer to views from the <em>"
      + dojo.byId('journalDisplayName').value + "</em> Web site only.<br/>";

    if(pubDateInMilliseconds < july1st2005InMilliseconds) {
      html = html + "*All usage prior to July 1st 2005 is reported as an HTML page view.<br/>";
    }

    html = html + "*Although we update our data on a daily basis (not in real time), there " +
      "may be a 48-hour delay before the most recent numbers are available.</span>";

    dojo.byId('cumulativeData').innerHTML = html;
    dojo.fx.wipeIn({ node:'cumulativeData', duration: 2000 }).play();

    cumulativeChart.create(data, "cumulativeGraph", "#003399", pubDate);
    dojo.fadeIn({ node:'cumulativeGraph', duration: 1000 }).play();

    // XML link at the bottom of the page.
    dojo.byId('pgXtras').style.visibility = "visible";
    dojo.fx.wipeIn({ node:'pgXtras', duration: 1000 }).play();

    //  Now use these values to create HTML for the Right Hand Column.
    setChartDataInRHC(response);
  }
}

/**
 * Set HTML for display of the Related Blogs returned from ALM.  Since the Metrics tab (of the
 * Article pages) does nothing with this information, this function just calls the
 * similarly-named setRelatedBlogsInRHC function defined in the init_article_rhc.js file.
 *
 * @param response The reply back from the Article Level Metrics server.
 */
function setIDs(response) {
  setIDsInRHC(response);
}

function setIDsError(message) {
  //Do nothing
}


function setBookmarks(response) {
  dojo.byId('relatedBookmarks').style.display = 'none';
  dojo.fadeOut({ node:'relatedBookmarksSpinner', duration: 1000 }).play();

  var numRendered = 0;
  var doi = escape(dojo.byId('doi').value);

  if (response.article.source.length > 0) {
    var html = "";

    for (var a = 0; a < response.article.source.length; a++) {
      var url = response.article.source[a].public_url;

      if(response.article.source[a].count > 0) {
        if (url) { // Only list links that have DEFINED URLS
          if (numRendered > 0) {
            html = html + ", ";
          }
          html = html + "<a href=\"" + url + "\">" + response.article.source[a].source
              + " (" + response.article.source[a].count + ")</a>";
          numRendered++;
        }
      }
    }
  }

  if (numRendered == 0) {
    html = "No related bookmarks found";
  }

  dojo.byId('relatedBookmarks').innerHTML = html;
  dojo.fx.wipeIn({ node:'relatedBookmarks', duration: 500 }).play();
}

function setBookmarksError(message) {
  dojo.fadeOut({ node:'relatedBookmarksSpinner', duration: 1000 }).play();
  setError('relatedBookmarks', message);
}

// Sort into ascending order by the "source" variable of each element.  ALWAYS put Scopus first.
function sortCitesBySource(a,b) {
  if (b.source.toLowerCase() == 'scopus') {
    return 1;
  } else if (a.source.toLowerCase() == 'scopus' || a.source.toLowerCase() < b.source.toLowerCase()) {
    return -1;
  } else if (a.source.toLowerCase() > b.source.toLowerCase()) {
    return 1;
  }
  return 0;
}

function setCites(response) {
  dojo.byId('relatedCites').style.display = 'none';
  dojo.fadeOut({ node:'relatedCitesSpinner', duration: 1000 }).play();

  var numCitesRendered = 0;
  var doi = escape(dojo.byId('doi').value);

  if (response.article.source.length > 0) {
    var html = "";

    // Citation Sources should always start with Scopus (if an entry for Scopus exists)
    //   followed by the rest of the sources in alphabetical order.
    response.article.source = response.article.source.sort(sortCitesBySource);

    for (var a = 0; a < response.article.source.length; a++) {
      var url = response.article.source[a].public_url;

      //  If CrossRef, then compose a URL to our own CrossRef Citations page.
      if (response.article.source[a].source == 'CrossRef' && response.article.source[a].count > 0) {
        if (numCitesRendered > 0) {
          html = html + ", ";
        }
        html = html + "<a href=\"" + dojo.byId('crossRefPageURL').value + "\">CrossRef ("
            + response.article.source[a].count + ")</a>";
        numCitesRendered++;
      }
      //  Only list links that HAVE DEFINED URLS
      else if (url && response.article.source[a].count > 0) {
        if (numCitesRendered > 0) {
          html = html + ", ";
        }
        html = html + "<a href=\"" + url + "\">" + response.article.source[a].source + " ("
              + response.article.source[a].count + ")</a>";
        numCitesRendered++;
      }
    }
  }

  if (numCitesRendered == 0) {
    html = "No related citations found";
  }

  dojo.byId('relatedCites').innerHTML = html;
  dojo.fx.wipeIn({ node:'relatedCites', duration: 500 }).play();

  //  Now use these values to create HTML for the Right Hand Column.
  setCitesInRHC(response);
}

function setCitesError(message) {
  dojo.fadeOut({ node:'relatedCitesSpinner', duration: 1000 }).play();
  setError('relatedCites', message);
}

function setRelatedBlogs(response) {
  var html = "";
  var htmlSearch = "";

  dojo.byId('relatedBlogPosts').style.display = 'none';
  dojo.fadeOut({ node:'relatedBlogPostsSpinner', duration: 1000 }).play();

  var numBlogsRendered = 0;
  var doi = escape(dojo.byId('doi').value);

  if (response.article.source.length > 0) {
    html = "";

    // If there is at least one hit for a blog site, then create a link to those blogs.
    // else, if there are zero hits for a blog site, then create a "search for title" link instead.
    for (var a = 0; a < response.article.source.length; a++) {
      var url = response.article.source[a].public_url;

      //Only list links that HAVE DEFINED URLS
      if (url && response.article.source[a].count > 0) {
        if (numBlogsRendered > 0) {
          html = html + ", ";
        }
        html = html + "<a href=\"" + url + "\">" + response.article.source[a].source
            + " (" + response.article.source[a].count + ")</a>";
        numBlogsRendered++;
      } else if (response.article.source[a].search_url != null
          && response.article.source[a].search_url.length > 0) {
        htmlSearch = htmlSearch + ", <a href=\"" + response.article.source[a].search_url
            + dojo.byId('articleTitleUnformatted').value
            + "\">" + response.article.source[a].source + "</a>";
      }
    }
  }

  if (numBlogsRendered > 0) {
    html = html + "<br/>";
  }

  html = html + "Search for related blog posts on <a href=\"http://blogsearch.google.com/blogsearch?as_q=%22"
      + dojo.byId('articleTitleUnformatted').value + "%22\">Google Blogs</a>";

  if (htmlSearch.length > 0) {
    html = html + htmlSearch;
  }

  dojo.byId('relatedBlogPosts').innerHTML = html;
  dojo.fx.wipeIn({ node:'relatedBlogPosts', duration: 1000 }).play();
}

function setRelatedBlogError(message) {
  dojo.byId('relatedBlogPosts').style.display = 'none';
  dojo.fadeOut({ node:'relatedBlogPostsSpinner', duration: 1000 }).play();

  html = "Search for related blog posts on <a href=\"http://blogsearch.google.com/blogsearch?as_q=%22"
      + dojo.byId('articleTitleUnformatted').value
      + "%22\">Google Blogs</a><br/><div id=\"relatedBlogPostsError\"></div>";

  dojo.byId('relatedBlogPosts').innerHTML = html;
  dojo.fx.wipeIn({ node:'relatedBlogPosts', duration: 1000 }).play();
  setError('relatedBlogPostsError', message);  
}

