Number.prototype.padTo=function(n) {
	if(this.length > n) return;
	var r="" + this
	while(r.length < n) {
		r = "0" + r
	}
	return r;
}

function pad_2(num_string) {
  if(num_string.length >= 2) {
    return num_string;
  } else {
    return "0"+num_string;
  }
}
function days_in_month(year, month) {
  month--; // To get 0-11 months
  month++; // Because we want to look at the next month!
  
  if(month>11) {
    month=0;
    year++;
  }
  start_of_next_month = new Date(year, month);
  end_of_this_month = new Date(start_of_next_month.getTime() - (1000*60*60*12));
  return end_of_this_month.getDate();
}
function set_max_day_from_value(name) {
  max_day=days_in_month(
    document.getElementById(name+".y").value, 
    document.getElementById(name+".m").value
  );
  for(i = 28; i<max_day+1; i++) {
    document.getElementById(name+".d."+i).disabled=false;
  }
  for(i = max_day+1; i<32; i++) {
    document.getElementById(name+".d."+i).disabled=true;
  }
  if(document.getElementById(name+".d").value > max_day)
    document.getElementById(name+".d").value = max_day;
}
function update_hidden_date(name) {
  document.getElementById(name+".h").value =
    document.getElementById(name+".y").value + "-" +
    pad_2(document.getElementById(name+".m").value) + "-" + 
    pad_2(document.getElementById(name+".d").value) +
    document.getElementById(name+".t").value;
}
function update_hidden_date_ym(name) {
  document.getElementById(name+".h").value =
    document.getElementById(name+".y").value + "-" +
    pad_2(document.getElementById(name+".m").value);
}
function find_element_root_offset(element) {
	x=0; y=0;
  while(element) {
    x+=element.offsetLeft;
    y+=element.offsetTop;
    element=element.offsetParent;
  }
	return [x,y];
}
function overlay_near_element(target_element, move_element_id, approx_width, approx_height) {
	target_position = find_element_root_offset(target_element);
	x = target_position[0];
	y = target_position[1];
  divstyle=document.getElementById(move_element_id).style;
  if(x>approx_width/2) {x-=approx_width/2} else {x=0}
  if(y>approx_height/2) {y-=approx_height/2} else {y=0}
  divstyle.left=x+"px";
  divstyle.top=y+"px";
  divstyle.visibility='visible';
}
function try_refresh(time, url) {
  location.href=url;
  setTimeout("try_refresh(" + time + ", '" + url + "')",time*1000);
}
function set_action(this_form, new_action) {
  var elements = this_form.elements;
  for(i = 0 ; i < elements.length ; ++i) {
    if(elements[i].name == "action")
      elements[i].value = new_action;
  }
  return true;
}
var page_title;

function override_page_title(t) {
	page_title = t;
}

// Look for the first h1 tag (possibly inside a div)
// Falls back to the element with ID "effective-title"
function set_title() {
	if(!page_title) {
		var heads = document.getElementsByTagName("h1");
		if(heads.length > 0) {
			var title_text_node;
			for(var i=0; i<heads.item(0).childNodes.length; i++) {
				if(heads.item(0).childNodes.item(i).data) {
					title_text_node = heads.item(0).childNodes.item(i);
					break;
				}
			}
		} else if(document.getElementById("effective-title")) {
			title_text_node=document.getElementById("effective-title").firstChild;
		} else {
			return;
		}
		if(!title_text_node) return;
		page_title = title_text_node.data;
	}
	var new_title = "Heart: ";
	// The first head should be the one we want
	new_title = new_title + page_title;
	document.title = new_title;
  return true; 
}

function toggle_div(id) {
  div=document.getElementById(id);
  if (div.style.display == 'none') {
    div.style.display = 'block';
  } else {
    div.style.display = 'none';
  }
}


broken_windows_browser=0;
if(navigator.userAgent.toLowerCase().indexOf("msie")>=0) broken_windows_browser=1;
var xmlhttp_by_name = {};

function xmlhttp_call_with_args(name, orst, url, args) {
	var post_content = "";
	for(var i in args) {
		post_content += i + "=" + encodeURIComponent(args[i]) + ";";
	}

	var xmlhttp_o;
	if(broken_windows_browser) {
		xmlhttp_o = new ActiveXObject("MsXml2.XmlHttp");
	} else {
		xmlhttp_o = new XMLHttpRequest();
	}
	xmlhttp_by_name[name] = xmlhttp_o;
	xmlhttp_o.onreadystatechange=orst;
	xmlhttp_o.open("POST", url, true);
	xmlhttp_o.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp_o.setRequestHeader("Content-length", post_content.length);
	xmlhttp_o.setRequestHeader("Connection", "close");
	xmlhttp_o.send(post_content);
	return xmlhttp_o;
}

var alert_count = 0;
var alert_limit = 20;
function alert_l(str) {
	alert_count++;
	if(alert_count>= alert_limit) return;
	return window.alert(str);
}

function build_simple_xmlr_statechange(n, on_success, on_failure, check_for_success) {
	return function() {
		/* effective args: n, on_success, on_failure */
		// if LOADED
		var my_xmlhttp = xmlhttp_by_name[n];
		if(my_xmlhttp.readyState == 4 && my_xmlhttp.status == 200) {
			var xmldoc=my_xmlhttp.responseXML;
			if(!xmldoc) {
				if(on_failure) on_failure();
			} else if(!xmldoc.lastChild) {
				if(on_failure) on_failure(xmldoc.lastChild);
			} else if(check_for_success && !check_for_success(xmldoc.lastChild)) {
				if(on_failure) on_failure(xmldoc.lastChild);
			} else {
				if(on_success) on_success(xmldoc.lastChild);
			}
		} else if(my_xmlhttp.readyState == 4) {
			alert_l("HTTP error: "+my_xmlhttp.status);
			if(on_failure) on_failure();
		}
	};
}

function form_to_http_request(f, on_success, on_failure, check_for_success) {
	var form_contents = {};
	for(var i=0; i<f.elements.length; i++) {
		var e = f.elements.item(i);
		if(e.disabled) continue;
		if(e.type == "radio" || e.type == "checkbox") {
			if(!e.checked) continue;
		} else if(e.type == "submit" || e.type == "image") {
			// Broken for now.
			continue;
		}
		if(!e.name) continue; // Should never happen, but does.
		form_contents[e.name]=form_contents[e.name] || [];
		form_contents[e.name].push(e.value);
	}
	var orst = build_simple_xmlr_statechange(f.action, on_success, on_failure, check_for_success);
	xmlhttp_call_with_args(f.action, orst, f.action, form_contents);
	return false;
}

function replace_el_with_id(id, w) {
	var s = document.getElementById(id);
	s.parentNode.replaceChild(w, s);
	if(!w.id) w.id=id;
}

function _mkel(name, attributes, contents, tail_tweaks) {
	var e = document.createElement(name);
	if(attributes) {
		for(var n in attributes) {
			if(broken_windows_browser && n == "type" && name == "button") continue; // Skip it, cross fingers.
			e[n]=attributes[n];
		}
	}
	if(contents) for(var i=0; i<contents.length; i++) {
		if(!contents[i]) continue; // Should never happen, but... you know the drill.
		if(contents[i].nodeType) {
			e.appendChild(contents[i]);
		} else {
			e.appendChild(document.createTextNode(contents[i]));
		}
	}
	if(tail_tweaks)
		tail_tweaks(e);
	return e;
}

var popup__detail_container;
function prepare_detail_container() {
	window.onscroll=function() {
		if(popup__detail_container)
			document.body.removeChild(popup__detail_container);
		popup__detail_container = undefined;
	}
}

function show_popup_detail(ndc, desired_width, options) {
	options=options||{};
	var duration=0.5;
	if(undefined != options.popup_duration)
		duration = options.popup_duration;
	var detail_container = popup__detail_container;
	if(detail_container) try {document.body.removeChild(detail_container)} catch(e) {};

	popup__detail_container = detail_container = ndc;
	var onclick_closes = function() {
		new Effect.Shrink(detail_container.id, {duration: duration, direction: "center"});
		if(options.onclose) options.onclose();
	}
	if(options.closeWidget) {
		options.closeWidget.onclick = onclick_closes;
	}

	var close_el = document.createElement("button");
	//close_el.type="button";
	close_el.onclick = onclick_closes;
	close_el.appendChild(document.createTextNode("Close"));
	var anchor_p = document.createElement("p");
	anchor_p.style.textAlign="center";
	if(options.footer_extra) {
		for(var i=0; i<options.footer_extra.length; i++)
			anchor_p.appendChild(options.footer_extra[i]);
	}
	anchor_p.appendChild(close_el);
	detail_container.appendChild(anchor_p);
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;

	detail_container.style.position='fixed';
	detail_container.style.background="#fff";
	detail_container.style.border="2px outset";
	detail_container.style.display="none";
	if(desired_width)
		detail_container.style.width = desired_width;
	if(options.be_square)
		detail_container.style.height = detail_container.style.width;
	detail_container.id="pseudo-popup";
	document.body.appendChild(detail_container);
	detail_container.style.left = Math.round((w - Element.getWidth(detail_container)) / 2 ) + "px";
	detail_container.style.top = Math.round((h - Element.getHeight(detail_container)) / 2 ) + "px";
	new Effect.Grow(detail_container.id, {duration: duration, direction: "center"});
}

function unhtml(content_to_decode) {
	var span = document.createElement("span");
	span.innerHTML=content_to_decode;
	return(span.innerText || span.textContent);
}
