$(document).ready(function(){
	/*
	TODO
	- add effects
	- add anchors so that clicking a link doesn't make the page jump back to top
	*/

	var shNum = "h2"; // The section h# to expect
	var hNum = "h3"; // The h# to expect
	var cont = $("div.special");
	var iDivs = cont.find("div"); // The i stands for "initial"
	var isHdrs = cont.find(shNum);
	var iHdrs = iDivs.find(hNum);
	var bmDiv = $(document.createElement("div")).attr("id", "bmDiv");
	var pgDiv = $(document.createElement("div")).attr("id", "pgDiv");
	var shNxt = [];
	var hdrAs = [];

  var ohsBgImgUrl = "imgs/our-history-style-a-active-bg.png";
  var ohsBgImg = $(document.createElement("img")).attr("src", ohsBgImgUrl);

	var childs = cont.children();

	isHdrs = jQuery.makeArray(isHdrs);

	$.each(isHdrs, function(i){
		var cur = $(this);
		shNxt.push(cur.next().find(hNum));
	});

	// Set up the links to the content
	iHdrs.each(function(i){
		var curHdr = $(this);
		var html = curHdr.html();
		var hdrA = $(document.createElement("a"));

		if(curHdr.text() == $(shNxt[0]).text()){
			shNxt.shift();
			$(isHdrs.shift()).appendTo(bmDiv);
		}
		hdrA.appendTo(bmDiv);
		hdrAs.push(hdrA);
		hdrA.html(html);
		hdrA.attr("href", "javascript:function(){return false;}");
		hdrA.click(function(){setActive(i)});
	}); // END HDRS.EACH

	// Order is important! These should not come before above code
	pgDiv.append(iDivs);
	cont.append(bmDiv);
	cont.append(pgDiv);

	// Fix some style issues that would be impractical to fix in CSS
  setTimeout(function(){
    var pgDiv = $("#pgDiv");
    var bmDiv = $("#bmDiv");

    pgDiv.find("div").last().css({ "border-bottom" : "none" });
    bmDiv.find("a").last().css({ "border-bottom" : "none" });

    var pgH = pgDiv.height();
    var bmH = bmDiv.height();

    if(pgH > bmH){
      pgDiv.css({ "border-left" : "1px solid #f0f0f0" });
      bmDiv.css({ "border-right" : "none" });
    }
    else{
      pgDiv.css({ "border-left" : "none" });
      bmDiv.css({ "border-right" : "1px solid #f0f0f0" });
    }

    // make prev borderless and make last h# in bmDiv have top margin
    var bdh2 = bmDiv.find("h2").last();
    bdh2.css({"margin-top":"30px"});
    bdh2.prev().css({"border-bottom":"none"});

  }, 1000);

	function setActive(lucky){
		var top = $(hdrAs[lucky]).height() / 2;
		ohsBgImg.css({"position":"absolute","top":top,"right":"-1px"});

		$(hdrAs).each(function(i){
			var curA = $(this);
			if(i == lucky) curA.addClass("active").append(ohsBgImg);
			else curA.removeClass("active");
		});

		iDivs.each(function(i){
			var curDiv = $(this);
			if(i == lucky) curDiv.show();
			else curDiv.hide();
		});
	}

	setActive(0);

}); // END DOCUMENT.READY