////////////////////////////////////////////////////////////////
// GLOBALS
KEY = "87ea83cc7b50b4f6e42046de41171cbe8e985538"
EBIBLE_SNIPPET_URL = "http://ebible.com/api/ebibleSnippet"
EBIBLE_LINK_URL = "http://ebible.com/bookmark/?show=all"



/////////////////////////////////////////////////////////////////////
// Utility functions taken from standard.js

// We are passed a dom_element and we will
//  Collect all of the descendants of dom_element that are of class <className>
// into an array.
function findDescendantsByClass(dom_element, className) {
  var elements = new Array();

  for (var i=0; i < dom_element.childNodes.length; ++i) {
    var element = dom_element.childNodes[i];

    //alert("checking element.id=" + element.id + " element.className=" + element.className);

    // Get all of the descendants that are of class <className>
    var descendant_elements = findDescendantsByClass(element, className);
    elements = elements.concat(descendant_elements);  // Append them to our list

    // Make sure that the tagName attribute exists before the comparison!
    // It might not if "element" is not a DOM Element (for example, it could
    // be a #text element
    if (element.tagName) {
      // Check element to see if it's a member of <className>
      if (StyleClass.contains(element, className)) {
        // It is, so push it onto our <elements> list
        elements.push(element);
      }
    }
  }

  return elements;
}

// This function takes a dom element <element> and searches through its
// ancestors until if finds an element with <tagName>.  If it cannot find an
// ancestor it returns null.
function findAncestorByTag(element, tagName) {
  // Make sure element is valid.
  tagName = tagName.toUpperCase();

  if (element) {
    element = element.parentNode;

    // Keep going up the tree until we find an element of className
    while (element && element.tagName) {
      if (element.tagName.toUpperCase() == tagName) {
        return(element)
      }
      element = element.parentNode;
    }
  }

  return(null);
}

function eventTarget(event) {
  if (event) {
    if (event.target) {
      return(event.target)
    }

    if (event.srcElement) {
      return(event.srcElement)
    }
  }
  else {
    return(null)
  }
}

/******************************************************************************
*  Cross browser way to add and remove events
******************************************************************************/
function addEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    //alert("Handler could not be attached");
  }
}

function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    //alert("Handler could not be removed");
  }
}


/******************************************************************************
Here are some functions to help dealing with CSS classes.
******************************************************************************/

function StyleClass() {
}

StyleClass.split = function(classes_string) {
  if (classes_string) {
    return classes_string.split(" ");
  }
  else {
    return(new Array());
  }
}

StyleClass.join = function(classes) {
  // Returns a class name suitable for insertion into a dom elements
  // className attribute.
  if (classes) {
    return(classes.join(" "));
  }
  else {
    return("");
  }
}

// <container> is a dom_element, a string, or an array.
// Returns true if <container> contains style class <className> and false
// otherwise.
StyleClass.contains = function(container, className) {
  // dom_element_or_class_string
  //   Must be a DOM ELEMENT or a class STRING
  var classes;
  if (typeof container == "string") {
    classes = StyleClass.split(container);
  }
  else if (typeof container == "array") {
    classes = container;
  }
  else {
    // Assume container is a DOM element.
    classes = StyleClass.split(container.className);
  }

  // Returns true of classes collection contains className
  return(contains(classes, className));
}

// <array> is an array.  The function returns true if <array> contains an object
// that is equal to <obj> (but not necessarily the same object!), and false
// otherwise.
function contains(array, obj) {
  var idx = indexOf(array, obj);

  if (idx >= 0) {
    return(true);
  }
  else {
    return(false);
  }
}

// <array> is an array.  The function returns the index of the first object in
// the array that is equal to <obj> (but not necessarily the same object!).
// If no object equal to <obj> is found, returns -1.
function indexOf(array, obj) {
  for (var i = 0; i<array.length; i++) {
    if (array[i] == obj) {
      return(i);
    }
  }

  return(-1);
}

// Author: Jason Levitt
// Date: December 7th, 2005
// Constructor -- pass a REST request URL to the constructor
//
function JSONscriptRequest(fullUrl) {
    // REST request path
    this.fullUrl = fullUrl; 
    // Keep IE from caching requests
    this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
    // Get the DOM location to put the script tag
    this.headLoc = document.getElementsByTagName("head").item(0);
    // Generate a unique script tag id
    this.scriptId = 'YJscriptId' + JSONscriptRequest.scriptCounter++;
}

// Static script ID counter
JSONscriptRequest.scriptCounter = 1;

// buildScriptTag method
//
JSONscriptRequest.prototype.buildScriptTag = function () {

    // Create the script tag
    this.scriptObj = document.createElement("script");
    
    // Add script object attributes
    this.scriptObj.setAttribute("type", "text/javascript");
    this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
    this.scriptObj.setAttribute("id", this.scriptId);
}
 
// removeScriptTag method
// 
JSONscriptRequest.prototype.removeScriptTag = function () {
    // Destroy the script tag
    this.headLoc.removeChild(this.scriptObj);  
}

// addScriptTag method
//
JSONscriptRequest.prototype.addScriptTag = function () {
    // Create the script tag
    this.headLoc.appendChild(this.scriptObj);
}

/*************************************************************************
 * orderText - orders the passage Text from eBible.com via JSON script request
 *************************************************************************/
function orderText(request) {
  // Dispatch the request
  aObj = new JSONscriptRequest(request);
  // Build the script tag
  aObj.buildScriptTag();
  // Execute (add) the script tag
  aObj.addScriptTag();

}


/******************************************************************************
  Copyright (c) 2006, Godspeed Computing Inc. 
  www.godspeedcomputing.com
  All Rights Reserved.

  Author: Scott Luedtke
  Date: September 26 2006

  eBibleSnippet
  Used to display bible passages on a website dynamically

******************************************************************************/

///////////////////////////////////////////////////////////////////////////////
// eBibleSnippet
//  Ebible snippet dynamically replaces specified elements with the actual scripture
//  text for bible verses.

var ebSnippets = []

function ebSnippetLoader(class_name, translation, related_topics) {

  ebSnippets = findDescendantsByClass(document.body, class_name);
  var passages = [];
    
  if (ebSnippets.length > 0){
    for (var i=0; i < ebSnippets.length; i++) {
        var element = ebSnippets[i];
        passages[i] = escape(element.innerHTML);
    }
    query= passages.join(",")
    request = EBIBLE_SNIPPET_URL + "?apiKey=" + KEY + "&q=" + query + "&source=" + escape(translation) + "&callback=receivedText&relTopics=" + related_topics;
    orderText(request);
  }
}

function orderText(request) {
  // Dispatch the request
  aObj = new JSONscriptRequest(request);
  // Build the script tag
  aObj.buildScriptTag();
  // Execute (add) the script tag
  aObj.addScriptTag();

}

function receivedText(verses) {
 for (var i=0, verse; verse = verses[i]; i++) {
        ebSnippets[i].innerHTML = verse.text;
     }  
}

