/**
 * -- JavaScript support functions/methods
 * 
 * Array.map(function(x) {..}) -- map function onto array, returns new array
 * Array.indexOf(obj)          -- returns index of given element or -1
 * 
 * 
 * String.htmlents()           -- replaces &,",',<,> with their HTML equivalents
 * 
 * 
**/

// Array.map(callback) (is that the correct word?)
if (! Array.prototype.map) {
  Array.prototype.map = function(fun /*, thisp*/) {
    var len = this.length >>> 0;
    if (typeof fun != "function") {
      throw new TypeError();
    }
    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
      if (i in this) {
        res[i] = fun.call(thisp, this[i], i, this);
      };
    };
    return res;
  };
};

// Array.indexOf(obj)
if (! Array.prototype.indexOf) {
  Array.prototype.indexOf = function(obj) {
    for (var i=0; i<this.length; i++) {
      if (this[i]==obj) {
        return i;
      }
    }
    return -1;
  };
};

// String.htmlents()
if (! String.prototype.htmlents) {
  String.prototype.htmlents = function() {
    var trans = {'&':'&amp;', '"':'&quot;', "'":'&#039;', '<':'&lt;', '>':'&gt;'};
    var arr = this.split('');
    for (var i=0;i<arr.length;i++) {
      if (trans.hasOwnProperty(arr[i])) {
        arr[i] = trans[arr[i]];
      }
    }
    return arr.join('');
  };
}

// -- scrollTo(selector)
function scrollTo(selector, callback) {
  var targetOffset = $(selector).offset().top;
  $('html,body').animate({scrollTop: targetOffset}, 500, function() {
    if (typeof callback == 'function') callback();
  });
}

// -- isScrolledIntoView(elem)
function isScrolledIntoView(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();
  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();
  return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
}
