/*
 * $HeadURL:: http://ambraproject.org/svn/ambra/head/ambra/libs/js/src/main/scripts/ambr#$
 * $Id: alm.js 7770 2009-07-07 18:51:15Z josowski $
 *
 * Copyright (c) 2006-2009 by Topaz, Inc.
 * http://topazproject.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.
 */

/**
 * ambra.alm
 *
 * This class has utilities for fetching data from the ALM application.
 **/

dojo.provide("alm");

dojo.require("dojo.io.script");

(function() {
  dojo.declare("alm", null, {
    constructor:function() {
      if(almHost != null && almHost != '' && almHost != 'alm.example.org') {
        //almHost should always be defined as a global variable
        this.host = almHost;
      } else {
        throw new Error('The related article metrics server is not defined.  Make sure the ambra/platform/freemarker/almHost node is defined the ambra.xml file.');
      }

      //The current DOI should be on any page metrics is being use on
      //As a hidden form variable
      var doi = escape(dojo.byId('doi').value);

      if(doi == null) {
        throw new Error('Can not locate the current DOI.');
      }

      this.doi = doi.replace(new RegExp('/', 'g'),'%2F');
    },

    /*
    * If the article is less then 48 hours old, we don't want to display
    * the data quiet yet.
    * */
    validateArticleDate:function() {
      //The article publish date should be stored in the current page is a hidden form variable
      var pubDateInMilliseconds = new Number(dojo.byId('articlePubDate').value);
      var todayMinus48Hours = (new Date()).getTime() - 172800000;

      if(todayMinus48Hours < pubDateInMilliseconds) {
        return false;
      } else {
        return true;
      }
    },

    isArticle:function() {
      if(this.doi.indexOf("image") > -1) {
        return false;
      }

      return true;
    },

    getIDs:function(callBack, errorCallback) {
      var request = "articles/" + this.doi + ".json?history=0";
      this.getData(request, callBack, errorCallback);
    },

    getRelatedBlogs:function(callBack, errorCallback) {
      var request = "articles/" + this.doi + ".json?citations=1&source=Bloglines,Nature,Postgenomic,research%20Blogging";
      this.getData(request, callBack, errorCallback);
    },

    getSocialBookMarks:function(callBack, errorCallback) {
      var request = "articles/" + this.doi + ".json?citations=1&source=Citeulike,Connotea";
      this.getData(request, callBack, errorCallback);
    },

    getCites:function(callBack, errorCallback) {
      var request = "articles/" + this.doi + ".json?citations=1&source=CrossRef,PubMed%20Central,Scopus";
      this.getData(request, callBack, errorCallback);
    },

    getCounter:function(callBack, errorCallback) {
      var request = "articles/" + this.doi + ".json?citations=1&source=Counter";
      this.getData(request, callBack, errorCallback);
    },

    getCitesCrossRefOnly:function(callBack, errorCallback) {
      var request = "articles/" + this.doi + ".json?citations=1&source=CrossRef";
      this.getData(request, callBack, errorCallback);
    },

    /**
      *  host is the host and to get the JSON response from
      *  chartIndex is the  current index of the charts[] array
      *  callback is the method that populates the chart of  "chartIndex"
      *  errorCallback is the method that gets called when:
      *    --The request fails (Network error, network timeout)
      *    --The request is "empty" (Server responds, but with nothing)
      *    --The callback method fails
      **/
    getData:function(request, callBack, errorCallback) {
      var url = this.host + "/" + request;

      console.log(url);

      var getArgs = {
        callbackParamName: "callback",
        url:url,
        caller:this,
        callback:callBack,
        errorCallback:errorCallback,

        load:function(response, args) {
          /**
           * Callback is the method being called.
           * args.args.caller is the object the method is part of
           **/
          if(response == null) {
            throw new Error('The server did not send an appropriate response.');
          }

          callBack.call(args.args.caller, response);
          return response;
        },

        error:function(response, args) {
          /**
            * Callback is the method being called.
            * args.args.caller is the object the method is part of
            **/
          errorCallback.call(args.args.caller, "Our system is having a bad day. We are working on it. Please check back later.");
          return response;
        },

        timeout:10000
      };

      dojo.io.script.get(getArgs);
    }
  });
})();

function setError(textID, message) {
  dojo.byId(textID).style.display = 'none';
  dojo.byId(textID).innerHTML = '<span class="inlineError"><img src="' + appContext + '/images/icon_error.gif"/>&nbsp;' + message + '</span>';
  dojo.fx.wipeIn({ node:textID, duration: 1000 }).play();
}

function setDelayMessageError(textID) {
  dojo.byId(textID).style.display = 'none';
  dojo.byId(textID).innerHTML = '<span class="inlineError"><img src="' + appContext + '/images/icon_error.gif"/>&nbsp;This article was only recently published.</span>';
  dojo.fx.wipeIn({ node:textID, duration: 1000 }).play();
}

function setNoDataMessageError(textID) {
  dojo.byId(textID).style.display = 'none';
  dojo.byId(textID).innerHTML = '<span class="inlineError"><img src="' + appContext + '/images/icon_error.gif"/>&nbsp;We don\'t collect usage data for this type of content.</span>';
  dojo.fx.wipeIn({ node:textID, duration: 1000 }).play();
}


