//This file contains global routines that many of the Javascript engines and
//code routines depend upon.  Therefore I pulled all the routines out into this
//global code base so that I wouldn't have to worry about possible duplication
//of the routines by each separate piece of code that uses these functions.

//The following is some compatibility code taken from the SMF script.
// Define document.getElementById for Internet Explorer 4.
if (typeof(document.getElementById) == "undefined")
	document.getElementById = function (id)
	{
		// Just return the corresponding index of all.
		return document.all[id];
	}

//////////////////////////////////////////////////////////////////////////////////////
// Shorthand Functions ///////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////

function clearValue(element_name)
{
  document.getElementById(element_name).value='';
}

function getValue(element_name)
{
  return document.getElementById(element_name).value;
}

function setValue(element_name,input_value)
{
  document.getElementById(element_name).value=input_value;
}

function getInner(element_name)
{
  return document.getElementById(element_name).innerHTML;
}

function setInner(element_name,input_value)
{
  document.getElementById(element_name).innerHTML=input_value;
}

function getEncodedValue(name)
{
  return encodeURIComponent(document.getElementById(name).value);
}

//////////////////////////////////////////////////////////////////////////////////////
// Interface /////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////

var last_selected_name='';

function select_box(name)
{
  //First handle erase of old select box.
  if(last_selected_name=='')
  {
     //No need to erase an old box.
  }
  else
  {
   document.getElementById(last_selected_name).style.borderColor="#000";
   document.getElementById(last_selected_name).style.borderWidth="1px";
  }
  //No handle the new select box.
  if(name=='')
  {
    //Empty parameter passed so must have just meant to erase old box.
  }
  else
  {
    document.getElementById(name).style.borderColor="#0F0";
    document.getElementById(name).style.borderWidth="2px";
  }
  //Even if the name was an empty string assign it to last_select_name.
  last_selected_name = name;
}

function setTab(name,number)
{
  document.getElementById(name).tabIndex=number;
}

///////////////////////////////////////////////////////////////////////////////////////
// Parsing and Processing /////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////

function trim(s) {
  if (!s || s=="") return "";
  while ((s.charAt(0)==' ') || (s.charAt(0)=='\n') || (s.charAt(0)=='\t') || (s.charAt(0,1)=='\r')) s=s.substring(1,s.length);
  while ((s.charAt(s.length-1)==' ') || (s.charAt(s.length-1)=='\n') || (s.charAt(s.length-1)=='\t') || (s.charAt(s.length-1)=='\r')) s=s.substring(0,s.length-1);
  return s;
}

var month_names = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

function dateString(month_number,day,year)
{
  return month_names[month_number-1]+" "+day+", "+year;
}

//This function reformats the address if needed so that all addresses have the
//same layout.  This aids in database organization and result sorting.
function redo_address(input_element)
{
  //First get the input element's value.
  current_address = input_element.value;
  //Now extract the various tokens in the value.
  var tokens = current_address.split(' ');
  //Now we need to pull the house number out of the token array and rebuild the street name.
  var number_expr = /[#]*\d/;
  var street="";
  var number="";
  for(var token_number=0; token_number<tokens.length; token_number++)
  {
    if(number_expr.test(tokens[token_number])==1)
    {
      number+=tokens[token_number];  //Found the number token.
      if(token_number!=tokens.length-1 & /^[A-Za-z]{1}$/.test(tokens[token_number+1]))
      {
        //The next token appears to be a duplex side, ie: Test Street #502 B
        number+=tokens[token_number+1];
        token_number+=1;
      }
    }
    else
    {
      if(tokens[token_number]!="")
      {
        //This is not an empty token formed by a double space.
        //First make sure that the first letter of the word is capitalized
        var temp_token = tokens[token_number];
        temp_token=(temp_token.slice(0,1)).toUpperCase()+temp_token.slice(1,temp_token.length);
        street+=temp_token+" ";  //Assume this token must be part of street name.
      }
    }
  }
  //Now process the number token.
  number=number.replace(/#/g,'');  //Remove all pounds, in case of duplicates,
  number="#"+number;  //Put a single pound back on the front.
  input_element.value = street+number;
}

//The following function from the open source SMF forum engine.
// Replaces the currently selected text with the passed text.
function replaceText(text, destination_name)
{
  destination = document.getElementById(destination_name);
	// Attempt to create a text range (IE).
	if (typeof(destination.caretPos) != "undefined" && destination.createTextRange)
	{
		var caretPos = destination.caretPos;

		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		caretPos.select();
	}
	// Mozilla text range replace.
	else if (typeof(destination.selectionStart) != "undefined")
	{
		var begin = destination.value.substr(0, destination.selectionStart);
		var end = destination.value.substr(destination.selectionEnd);
		var scrollPos = destination.scrollTop;

		destination.value = begin + text + end;

		if (destination.setSelectionRange)
		{
			destination.focus();
			destination.setSelectionRange(begin.length + text.length, begin.length + text.length);
		}
		destination.scrollTop = scrollPos;
	}
	// Just put it on the end.
	else
	{
		destination.value += text;
		destination.focus(destination.value.length - 1);
	}
}

// Get the inner HTML of an element, thanks to SMF
function getInnerHTML(element)
{
	if (typeof(element.innerHTML) != 'undefined')
		return element.innerHTML;
	else
	{
		var returnStr = '';
		for (var i = 0; i < element.childNodes.length; i++)
			returnStr += getOuterHTML(element.childNodes[i]);

		return returnStr;
	}
}

//A generic outer HTML function, thanks to SMF.
function getOuterHTML(node)
{
	if (typeof(node.outerHTML) != 'undefined')
		return node.outerHTML;

	var str = '';

	switch (node.nodeType)
	{
	// An element.
	case 1:
		str += '<' + node.nodeName;

		for (var i = 0; i < node.attributes.length; i++)
		{
			if (node.attributes[i].nodeValue != null)
				str += ' ' + node.attributes[i].nodeName + '="' + node.attributes[i].nodeValue + '"';
		}

		if (node.childNodes.length == 0 && in_array(node.nodeName.toLowerCase(), ['hr', 'input', 'img', 'link', 'meta', 'br']))
			str += ' />';
		else
			str += '>' + getInnerHTML(node) + '</' + node.nodeName + '>';
		break;

	// 2 is an attribute.

	// Just some text..
	case 3:
		str += node.nodeValue;
		break;

	// A CDATA section.
	case 4:
		str += '<![CDATA' + '[' + node.nodeValue + ']' + ']>';
		break;

	// Entity reference..
	case 5:
		str += '&' + node.nodeName + ';';
		break;

	// 6 is an actual entity, 7 is a PI.

	// Comment.
	case 8:
		str += '<!--' + node.nodeValue + '-->';
		break;
	}

	return str;
}

//////////////////////////////////////////////////////////////////////////////////////
// Communications ////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////

//This function is designed to retrieve an httpRequest object for the purpose of
//doing AJAX.

function getRequestObject()
{
  var httpRequest;

  try
  {
    httpRequest = new XMLHttpRequest();
  }
  catch(requestError)
  {
    try
    {
      httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(requestError)
    {
      try
      {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(requestError)
      {
        window.alert("This page will not run correctly because your browser does not support AJAX.");
        return false;
      }
    }
  }
  return httpRequest;
}


