var TYPE_RES = {
    email_address: /^.+@.+\..{2,3}$/,
    telephone: /(\d[^\d]*){10}/
};

var wikiTerms = new Array();

function validate_form(form_id, fields) {
    // alert("Your mother was a hamster and your father smelt of elderberries.");
    var fm = document.getElementById(form_id);
    var ok = true;
    for (var field_id in fields) {
	var info = fields[field_id];
	var v = fm[field_id].value;
	var label = info['n'];
	if (v) {
	    var typename = info['type'];
	    if (typename) {
		if (!TYPE_RES[typename].test(v)) {
		    alert("The value '" + v + "' is not valid for '" + label + "'.");
		    ok = false;
		    break;
		}
	    }
	}
	else {
	    if (!info['optional']) {
		alert("You must supply a value for '" + label + "'.");
		ok = false;
		break;
	    }
	}
    }
    return ok;
}

// see:
//   http://developer.mozilla.org/en/docs/DOM:window.open
//   http://developer.mozilla.org/en/docs/DOM:window
//   http://msdn.microsoft.com/workshop/author/dhtml/reference/methods/open_0.asp
//   http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/obj_window.asp

// versus '_blank', which would mean a new one every time
var POPUP_NAME = 'buildsite_popup';
// fixed features
var POPUP_FEATURES = 'height=500,width=660,resizable=1,location=0,menubar=0,scrollbars=1,status=0,titlebar=0,toolbar=0,directories=0';

function do_popup(href) {
    /* for window.open features, NN4 has screenX and screenY; IE4 has left and top. moz supports all. */
    /* for getting current window position, IE has window.screenLeft and screenTop */
    var features = POPUP_FEATURES;
    var x = (window.screenX ? window.screenX : window.screenLeft) + 10;
    var y = (window.screenY ? window.screenY : window.screenTop) + 75;
    features += "left=" + x + ",top=" + y;

    var win = window.open(href, POPUP_NAME, features);
    return false;
}

function open_demo ( url ) {
  window.open(url, POPUP_NAME+"_demo", "height=730,width=998,resizable=1,location=0,menubar=0,scrollbars=1,status=1,titlebar=0,toolbar=0,directories=0").focus();
  return false;
}

var MIN_WIDTH = 300;
var MIN_HEIGHT = 300;
var MAX_HEIGHT = 700;

function size_to_fit(win) {
    if (!win) win = window;
    var de = win.document.documentElement ? win.document.documentElement : win.document.body;
    // alert("content=(" + de.scrollWidth + "," + de.scrollHeight + ") window=(" + de.clientWidth + "," + de.clientHeight + ")");

    // there is also win.sizeToContent() in moz, but not IE
    //win.resizeBy(de.scrollWidth - de.clientWidth, de.scrollHeight - de.clientHeight);
    // resize only width to fit
    var h = de.clientHeight > MIN_HEIGHT ? de.clientHeight : MIN_HEIGHT;
    if (h > MAX_HEIGHT) h = MAX_HEIGHT;
    win.resizeTo(de.scrollWidth > MIN_WIDTH ? de.scrollWidth : MIN_WIDTH, h);

}

function tooltip_show(id, node) {
    var n = document.getElementById(id);
    if (n) {
        if (n.getAttribute('product')) {
          var stand = n.getElementsByTagName('b')[0];
          var imgsrc = '/images/tooltip.gif?product='
                        + n.getAttribute('product')
                        + '&rnd=' + Math.random();
          if (stand && !stand.getAttribute('shown') ) {
            var i = new Image(1,1);
            i.src = imgsrc;
            stand.setAttribute( 'shown', 'yes' );
          }
        }
	n.style.display = 'block';
	n.style.visibility = 'visible';
    }
    else {window.status = "ERROR: no node with id '" + id + "'";}
    return false;
}

function tooltip_hide(id, node) {
    document.getElementById(id).style.display = 'none';
    document.getElementById(id).style.visibility = 'hidden';
    return false;
}


function get(obj) {
  if ( typeof obj == "string" && document.getElementById ) {
    return document.getElementById(obj);
  } else {
    return null;
  }
}

function create( name, attributes ) {
  var el = document.createElement( name );
  if ( typeof attributes == 'object' ) {
    for ( var i in attributes ) {
      el.setAttribute( i, attributes[i] );

      if ( i.toLowerCase() == 'class' ) {
        el.className = attributes[i];  // for IE compatibility

      } else if ( i.toLowerCase() == 'style' ) {
        el.style.cssText = attributes[i]; // for IE compatibility
      }
    }
  }
  for ( var i = 2; i<arguments.length; i++ ) {
    var val = arguments[i];
    if ( typeof val == 'string' ) { val = document.createTextNode( val ) };
    el.appendChild( val );
  }
  return el;
}

function BookmarkBuildSite() {

    title = "BuildSite";
    url = "http://buildsite.com/";
    if( window.external ) { // IE Favorite
	window.external.AddFavorite( url, title );
    } else if(window.opera && window.print) { // Opera Hotlist
	alert( "Please press Ctrl-T to bookmark this page." );
    } else {
	alert( "Please press Ctrl-D to bookmark this page." );
    }
    return false;
}

var LEFTNAV_OPEN_DELAY = 100; // ms
var LEFTNAV_SLIDE_SPEED = 300; // ms
var LEFTNAV_CLOSE_SPEED = 100; // ms

var leftnav_current_li = null;
var leftnav_mouseover_li = null;
var leftnav_mouseover_in = false;
var leftnav_mouseover_timeout = null;


function leftnav_open ( li ) {
  li.setAttribute("in_timeout", null);
  li.setAttribute("out_timeout", null);

  if ( leftnav_current_li ) {
    if ( leftnav_current_li == li ) {
      return;
    }

    leftnav_close(leftnav_current_li);
  }

  if ( $(li).children(".noopen").length ) {
    // Can't be opened.
    return;
  }

  leftnav_current_li = li;
  $(li).removeClass("closed");
  $(li).addClass("open");
  $(li).children("ul").slideDown(LEFTNAV_SLIDE_SPEED);
}

function leftnav_close ( li ) {
  li.setAttribute("in_timeout", null);
  li.setAttribute("out_timeout", null);

  leftnav_current_li = null;
  $(li).children("ul").slideUp(LEFTNAV_CLOSE_SPEED, function () {
    $(li).removeClass("open");
    $(li).addClass("closed");
  });
}

$(function() {
  $("#leftmenu > li > a").each(function () {
    var li = this.parentNode;

    if ( $(li).is(".open") ) {
      leftnav_current_li = li;
    }

    $(li).mouseover(function () {
      leftnav_mouseover_in = true;

      if ( leftnav_mouseover_li != li ) {
        leftnav_mouseover_li = li;

        if ( leftnav_mouseover_timeout ) {
          window.clearTimeout(leftnav_mouseover_timeout);
          leftnav_mouseover_timeout = null;
        }

        leftnav_mouseover_timeout = window.setTimeout(function () {
            leftnav_mouseover_li = null;
            leftnav_mouseover_timeout = null;
            if ( leftnav_mouseover_in ) {
              leftnav_open(li);
            }
          }, LEFTNAV_OPEN_DELAY);
      }
    });

    $(li).mouseout(function () {
      if ( leftnav_mouseover_li == li ) {
        leftnav_mouseover_in = false;
      }
    });
  })
});


function initialize_section_message ( section, fixed ) {
  var match = new RegExp("\\blast_" + section + "_message=(\\d+)")
    .exec(document.cookie);

  if ( !fixed && match ) {
    show_section_message(section, parseInt(match[1], 10) % 4 + 1);
  } else {
    show_section_message(section, 1);
  }

  document.getElementById("banner-button-1").onclick = function () {
    show_section_message(section, 1);
    return false;
  }
  document.getElementById("banner-button-2").onclick = function () {
    show_section_message(section, 2);
    return false;
  }
  document.getElementById("banner-button-3").onclick = function () {
    show_section_message(section, 3);
    return false;
  }
  document.getElementById("banner-button-4").onclick = function () {
    show_section_message(section, 4);
    return false;
  }
}

function show_section_message ( section, index ) {
  var i;
  for ( i = 1 ; i <= 4 ; i++ ) {
    if ( i == index ) {
      $("#banner-button-" + i).addClass("on");
      $("#banner-message-" + i).show();
      $("#banner-link-" + i).show();
    } else {
      $("#banner-button-" + i).removeClass("on");
      $("#banner-message-" + i).hide();
      $("#banner-link-" + i).hide();
    }
  }

  document.cookie = "last_" + section + "_message=" + index;
}



var wikiDefinitions = {};

function highlightWikiTerms() {
return;
	var usedTerms = new Array;

	for (i = 0; i < wikiTerms.length; i++) {
		var used = false;

		var word = wikiTerms[i];
		word = word.replace("-", "\\-");

		var re = new RegExp("(\\W|^)(" + word + ")(\\W|$)", "gi");
		var re2 = new RegExp("(<h3.*?)<span class=\"wiki-tooltip-loading\">(.*?)</span>(.*?</h3>)", "gi");

		$('.has-wikipedia-terms').each(function(index, item) {
			if (re.test($(item).html())) {
				used = true;

				$(item).html(
					$(item).html()
					.replace(re, '$1<span class="wiki-tooltip-loading">$2</span>$3')
					.replace(re2, '$1$2$3')
				);
			}
		});

		if (used) usedTerms.push(wikiTerms[i]);
	}

	if (usedTerms.length > 0) $.getJSON(
		"/wiki/definitions",
		{ "term": usedTerms },
		function(data) {
			wikiDefinitions = data;
			$('.wiki-tooltip-loading').each(function(i, item) {
				var pos = findPos(item);
				var wd = wikiDefinitions[$(item).html().toLowerCase()]; 
				$("<div />")
					.html(
						"<h3>" + $(item).html() + "</h3>" + 
						wd[0] + 
						'<p style="margin-top:2em;"><a href="' + wd[1] + '">' + wd[1] + '</a></p>'
					)
					.appendTo(
						$("<div />")
							.attr({ "class": "wiki-popup" })
							.css({ "left": pos.left + 20, "top": pos.top + $(item).height() })
							.appendTo($(item))
					)
				;

				$(item)
					.hover(
						function () { $(this).children(".wiki-popup").show(); },
						function () { $(this).children(".wiki-popup").hide(); }
					)
					.removeClass("wiki-tooltip-loading")
					.addClass("wiki-tooltip")
				;
			});
		}
	);
}

function findPos(obj) {
	var curleft = curtop = 0;

	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}

	return { "left": curleft, "top": curtop };
}


if (typeof jQuery != 'undefined') {
	$(highlightWikiTerms);
}

$(function() {
    var stop = false;
    $("#astm_official_description").children("p").each(function(i, item) {
        if (stop) return;

        stop = true;
        $(item).addClass("first").nextAll().hide();
        $("<a />")
            .attr({ "href": "#" })
            .html("more")
            .bind("click", function() {
                $(this).html($(this).html() == "more" ? "less" : "more");
                $(this).parent().prevAll(":not(.first)").slideToggle();
                return false
            })
            .appendTo($("<p />").attr({ "align": "right" }).appendTo($("#astm_official_description")))
        ;
        $("#astm_official_description").show();
    });
});

$(function() {
    if ($("tr.green-data table tr").length <= 3) return;

    var len = $("tr.green-data table tr").length;
    $("tr.green-data table")
        .after($("<p>").css({"text-align": "right", "margin": "5px 0px"})
                .append($("<a>")
                    .attr({"href": "#"}).html("more")
                    .bind("click", function() {
                        $(this).html($(this).html() == "more" ? "less" : "more");
                        $("tr.green-data table tr").slice(-(len-3), len).toggle();
                        return false;
                    })
                )
            );
    $("tr.green-data table tr").slice(-(len-3), len).hide();
});
