// TODO: accept an optional namespace parameter to prevent crapping
// all over your global object
function include(library) {
    var lib_path = '/static/lib/';
    $.getScript(lib_path + library + '.js');
}

function id(x) { return x; };
// takes f, a1, a2, ... and returns function() { f(a1, a2, ...) }
function ap(f) { var args = arguments; return function() { return f.apply(null, Array.prototype.slice.call(args, 1)); }; };
// oo version, takes f, a1, a2, ... returns function() { a1.f(a2, ...) }
function apo(f) { var args = arguments; return function() { return f.apply(args[1], Array.prototype.slice.call(args, 2)); }; };
function callm(methodName, obj) { return function() {
  if(obj == null) { return this[methodName]() }
  else { return obj[methodName](); }
} }
function cp(f, g) { return function(a) { f(g(a)); } }
function map(f, list) {
  var ret = [];
  for(var i = 0; i < list.length; i++) ret.push(f(list[i]));
  return ret;
}
function zip(list1, list2) {
  var ret = [];
  for(var i = 0; i < list1.length; i++) ret.push([list1[i], list2[i]]);
  return ret;
}

$(document).ready(function () {
  $("input[type=text].empty, input[type=password].empty, textarea.empty").each(function() {
    var that = this;
    this.defaultValue = this.value;
    this.onfocus = function() { if(that.value == that.defaultValue)
      this.value = ""; }
    this.onblur = function() { if(that.value == "")
      that.value = that.defaultValue };
    //this.onblur = function() { setTimeout(function() { if(that.value == "")
    //  that.value = that.defaultValue }, 100) };
  });
});

function asyncSubmit(form, callback) {
  var data = {};
  $(form).find("input").each(function() { data[this.name] = this.value; });
  var action = $(form).attr('action');
  if(!action) action = '.';
  $.post(action, data, callback, 'html');
  return false;
}

function Overlay(content, width, height) {
  var self = {};
  self.width = width ? width : 600;
  self.height = height ? height : 300;
  self.content = content;

  self.close = function() {
    this.over.remove();
    this.dimmer.children().unwrap();
  }

  $('body').wrapInner($('<div/>')
    .css({
      'opacity': '0.5',
      'z-index':'100',
      'background-color': 'white'
      })
    .attr('id', 'dimmer0')
  );
  self.dimmer = $('#dimmer0');

  self.over = $('<div/>')
    .css({
       'position': 'fixed'
      ,'padding': '15px'
      ,'z-index': '200'
      ,'opacity': '1.0'
      ,'width': self.width
      ,'height': self.height
      ,'top': ($(window).height() / 2 - self.height / 2) + 'px'
      ,'left': ($(window).width() / 2 - self.width / 2) + 'px'
      ,'margin': 'auto'
      ,'background-color': 'white'
      ,'border': '3px solid #D3D3D3'
      ,'-moz-border-radius': '25px'
      ,'-moz-box-shadow': 'black 5px 5px 10px 0'
      })
    .html(content)
  ;

  $('body').append(self.over);

  return self;
}
