function trim(sString) {
	while (sString.substring(0,1) == ' ') {
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ') {
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}
function ajaxPost(url, data, methodError, methodDone) {
  var userid = readCookie('userid');
  var httpRequest = makeRequest(methodError, methodDone);
  if (!httpRequest) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return;
  }
  url = randomizeUrl(url);
  userid = encodeURI(userid);
  userid = replaceAll(userid, '+', '%2B');
  url = url + '&userid=' + userid;
  httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  httpRequest.open('POST', url, true);
  httpRequest.send(data);
}
function ajaxGet(url, methodError, methodDone) {
  var userid = readCookie('userid');
  var httpRequest = makeRequest(methodError, methodDone);
  if (!httpRequest) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return;
  }
  url = randomizeUrl(url);
  userid = encodeURI(userid);
  userid = replaceAll(userid, '+', '%2B');
  url = url + '&userid=' + userid;
  httpRequest.open('GET', url, true);
  httpRequest.send(null);
}
function replaceAll(source, searchFor, replacement) {
	var index = source.indexOf(searchFor);
	while ( index > -1 ) {
		source = source.substring(0, index) + replacement + source.substring(index + searchFor.length);
		index = source.indexOf(searchFor);
	}
	return source;
}
function randomizeUrl(url) {
	var date = new Date();
	var cruft = '' + date.getYear();
	cruft = cruft + 'a' + date.getMonth();
	cruft = cruft + 'a' + date.getDate();
	cruft = cruft + 'a' + date.getHours();
	cruft = cruft + 'a' + date.getMinutes();
	cruft = cruft + 'a' + date.getSeconds();
	cruft = cruft + 'a' + date.getTime();
	return url + '&cruft=' + cruft;
}

function statechanged(httpRequest, methodError, methodDone) {
  if (httpRequest.readyState == 4) {
    if (httpRequest.status == 200) {
      methodDone(httpRequest);
    } 
    else {
      methodError(httpRequest);
    }
  }
}
function createRadioInput(name, value) {
	// cant set the name dynamically in IE, IE SUCKS!!!!!!!
  if ( document.all && !opera ) {
  	return document.createElement('<input type="radio" name="' + name + '" value="' + value + '">');
  }
  else {
		var radio = document.createElement('input');
  	radio.setAttribute('type', 'radio');
  	radio.setAttribute('name', name);
	  radio.setAttribute('value', value);
	  return radio;
  }
}

function makeRequest(methodError, methodDone) {
	var httpRequest;
	if ( opera ) {
		httpRequest = operaHttpRequest;
	}
	else {
		httpRequest = buildRequest();
	}
  if ( httpRequest ) {
	  httpRequest.onreadystatechange = function() { statechanged(httpRequest, methodError, methodDone); };
  }
  return httpRequest;
}
function buildRequest() {
  var httpRequest;
  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
    if (httpRequest.overrideMimeType) {
      httpRequest.overrideMimeType('text/xml');
      // See note below about this line
    }
  } 
  else if (window.ActiveXObject) { // IE
    try {
      httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } 
    catch (e) {
      try {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch (e) {}
    }
  }
  return httpRequest;
}
function displayError(httpRequest) {
		strResponse = httpRequest.responseText;
          switch (httpRequest.status) {
                   // Page-not-found error
                   case 404:
                           alert('Error: Not Found. The requested URL could not be found.');
                           break;
                   // Display results in a full window for server-side errors
                   case 500:
	                   var errorWin;
				        // Create new window and display error
				        try {
				                errorWin = window.open('', 'errorWin');
				                errorWin.document.body.innerHTML = strResponse;
				        }
				        // If pop-up gets blocked, inform user
				        catch(e) {
				                alert('An error occurred, but the error message cannot be' +
				                        ' displayed because of your browser\'s pop-up blocker.\n' +
				                        'Please allow pop-ups from this Web site.');
				        }
                           break;
                   default:
                           // Call JS alert for custom error or debug messages
                           if (strResponse.indexOf('Error:') > -1 || 
                                   strResponse.indexOf('Debug:') > -1) {
                                   alert(strResponse);
                           }
                           break;
           }
}
function replaceTextById(id, text) {
      var el = document.getElementById(id);
      if (el){
        while (el.firstChild){
          el.removeChild(el.firstChild);
        }
        el.appendChild(document.createTextNode(text));
      }
   } 
/**
 * sample onkeypress="return tabInstead(this, event)"
 **/
function tabInstead(field, event) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (keyCode == 13) {
      var i;
      for (i = 0; i < field.form.elements.length; i++)
        if (field == field.form.elements[i])
          break;
      i = (i + 1) % field.form.elements.length;
      field.form.elements[i].focus();
      return false;
    } 
    else
    return true;
}      
function hideModal(name) {
  hideIFrame();
  // un attache events from resize.
  var div = document.getElementById(name);
  div.style.display = 'none';
}
var resizeadded = false;
var opera = (navigator.userAgent.indexOf("Opera") != -1 ? true : false);
// if opera then we need a global http request object.
if ( opera ) {
	var operaHttpRequest = buildRequest();
}
function showModal(name) {
  showIFrame();
  // one time only stuff needed for resizing and scrolling.
  if ( !resizeadded ) {
    if ( document.all && !opera ) {
    	// stuff needed by ie to make the veil cover everything during reisizes and scrolls.
	    insertCssRule("modalIframe", "width:expression(document.body.clientWidth);");
  	  insertCssRule("modalIframe", "left:expression(ignoreme=document.body.scrollLeft);");
    	insertCssRule("modalIframe", "height:expression(document.body.clientHeight);");
    	insertCssRule("modalIframe", "top:expression(ignoreme=document.body.scrollTop);");
    }
    else {
    	// stuff needed by firefox to get the veil to cover everything during resizes and scrolls.
		  var iframe = document.getElementById('modalIframe');
		  iframe.style.top = 0;
		  iframe.style.left = 0;
	    var func = new Function("resize('" + name + "');");
    	if (window.attachEvent) {
  	    window.attachEvent('onresize', func);
	    }
    	else if (window.addEventListener) {
  	    window.addEventListener('resize', func, false);
	    }
    	else {
  	    window.onresize = func;
	    }
    }
    resizeadded = true;
  }
  var div = document.getElementById(name);
  if ( document.all && !opera ) {
    div.style.position = 'absolute';
    // does the div already have the css added?
    if ( !div.applied ) {
	    var w = '' + document.getElementById(name).style.width;
	    w = w.substring(0, w.length-2);
      insertCssRule(name, "top:expression(eval(document.compatMode&&document.compatMode=='CSS1Compat')?documentElement.scrollTop+((documentElement.clientHeight-this.clientHeight)/2 ): document.body.scrollTop+((document.body.clientHeight-this.clientHeight)/2));left:expression(eval(document.compatMode&&document.compatMode=='CSS1Compat')?documentElement.scrollLeft+(document.body.clientWidth/2)-("+w+"/2):document.body.scrollLeft+(document.body.offsetWidth/2)-("+w+"/2));");
    }
    div.applied = true;
	  div.style.display = 'block';
  }
  else {
    div.style.position = 'fixed';
	  div.style.display = 'block';
    centerDiv(name);
  }
}
function resize(name) {
  var iframe = document.getElementById('modalIframe');
  if ( iframe.style.display == 'block' ) {
    showIFrame();
    centerDiv(name);
  }
}
function hideIFrame() {
  var iframe = document.getElementById('modalIframe');
  iframe.style.display = 'none';
}
function showIFrame() {
  var iframe = document.getElementById('modalIframe');
  if ( !document.all || opera ) {
	  iframe.style.display = 'none';
  	iframe.style.width = document.body.scrollWidth;
	  iframe.style.height = document.body.scrollHeight;
  }
  iframe.style.display = 'block';
}
function centerDiv(name) {
	// this should only be called for firefox to get the div centered when it first appears or when resize occurs.
  var div = document.getElementById(name);
  var w = '' + div.offsetWidth;
  var h = '' + div.offsetHeight;
  div.style.top = (window.innerHeight / 2) - (h / 2);
  div.style.left = (window.innerWidth / 2) - (w / 2);
}
function getWindowWidth() {
  var width = document.documentElement && document.documentElement.clientWidth ||
    document.body && document.body.clientWidth ||
    document.body && document.body.parentNode && document.body.parentNode.clientWidth ||
    0;
  return width;
}
function GetWindowHeight() {
    var height = document.documentElement && document.documentElement.clientHeight ||
      document.body && document.body.clientHeight ||
      document.body && document.body.parentNode && document.body.parentNode.clientHeight ||
      0;
    return height;
}
function insertCssRule(selector, rule) {
  var stylesheet = document.styleSheets[document.styleSheets.length - 1];
  if (stylesheet.addRule) {
    stylesheet.addRule('#' + selector, rule, stylesheet.rules.length);
    return stylesheet.rules.length - 1;
  }
  else {
    stylesheet.insertRule('#' + selector + ' {' + rule + '}', stylesheet.cssRules.length);
    return stylesheet.cssRules.length - 1;
  }
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	value = escape(value);
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
	}
	return '';
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
//post an event to the personalization system.
function personalize(t, v) {
  ajaxGet("/ajax.jsp?action=event&t=" + escape(t) + "&v=" + escape(v), personalizeError, personalizeDone);
}
function personalizeError() {
}
function personalizeDone(result) {
  var response = eval("(" + result.responseText + ")");
}
