// A simple (heh) javascript library with functions for the following:

// tracking mouse motion
// getting element coordinates
// making xmlhttprequest calls
// setting cookies
// crossbrowser event handling
// scrolling to an element
// display messages in a nice way

var xmlhttp = null;
var mouse_x = 0;
var mouse_y = 0;
var page_loaded = false;
var rightnow = new Date();
var messages = '';
var messages_element = null;
var dragObj = new Object();
dragObj.zIndex = 0;

addLoadEvent(set_page_loaded);

function set_page_loaded() {
  page_loaded = true;
}

function addLoadEvent(func) {
  if (window.addEventListener)
    window.addEventListener("load",func,false);
  else if (document.addEventListener)
    document.addEventListener("load",func,false);
  else if (window.attachEvent)
    window.attachEvent("onload",func);
  else if (document.attachEvent)
    document.attachEvent("onload",func);
}

function addResizeEvent(func) {
  if (window.addEventListener)
    window.addEventListener("resize",func,false);
  else if (document.addEventListener)
    document.addEventListener("resize",func,false);
  else if (window.attachEvent)
    window.attachEvent("onresize",func);
  else if (document.attachEvent)
    document.attachEvent("onresize",func);
}

function update_messages(text, cancelScroll)
{
  if (!messages_element) return;
  
	if (text) {
    messages_element.innerHTML = text;
    messages_element.style.display = "block";
		setUpperRight(messages_element);
  }
  else
    messages_element.style.display = "none";
}


function window_x() {
  if (window.screenX)
    return window.screenX
  else if (window.screenLeft)
    return window.screenLeft;
}

function window_y() {
  if (window.screenY)
    return window.screenY
  else if (window.screenTop)
    return window.screenTop;
}

function mousemove(e) { 
  if (page_loaded)
  {
    if (e && e.clientX) { // Moz
      mouse_x = e.clientX + window.scrollX;
      mouse_y = e.clientY + window.scrollY;
      event_target = e.target;
    }
    else if (window.event) { // IE
      if (document.documentElement)   // Explorer 6 Strict
      {
        mouse_x = window.event.clientX + document.documentElement.scrollLeft - 4;
        mouse_y = window.event.clientY + document.documentElement.scrollTop - 4;
      }
      else if (document.body) // all other Explorers
      {
        mouse_x=window.event.clientX+document.body.scrollLeft-4;
        mouse_y=window.event.clientY+document.body.scrollTop-4;
      }
 
      mouse_window_x = window.event.clientX;
      mouse_window_y = window.event.clientY;
    }
  }
}





/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setcookie(name, value, expires, path, domain, secure)
{
    document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function XBrowserAddHandler(target,eventName,handlerName) { 
  if ( target.addEventListener ) { 
    target.addEventListener(eventName, function(e){target[handlerName](e);}, false);
  } else if ( target.attachEvent ) { 
    target.attachEvent("on" + eventName, function(e){target[handlerName](e);});
  } else { 
    var originalHandler = target["on" + eventName]; 
    if ( originalHandler ) { 
      target["on" + eventName] = function(e){originalHandler(e);target[handlerName](e);}; 
    } else { 
      target["on" + eventName] = target[handlerName]; 
    } 
  } 
}

function scrollto(el, xoffset, yoffset) {
  var x = getRealLeft(el) + xoffset;
  var y = getRealTop(el) + yoffset;
  window.scrollTo(x, y);
}


function get_property(p, k, d) {
  if (p == null) return d;
	return (p[k]) ? p[k] : d;
}


function xmlhttp_init() {
  //alert(" (xmlhttp_init) start");
  //if (xmlhttp) return;
  
  try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
    try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
      xmlhttp = false;
    }
  }

  if (!xmlhttp && typeof XMLHttpRequest!='undefined')
    xmlhttp = new XMLHttpRequest();

  //alert(" (xmlhttp_init) done");
}

function getRealLeft(imgElem) {
  xPos = imgElem.offsetLeft;
  tempEl = imgElem.offsetParent;
    //alert("element " + imgElem.id + "\\nparent "+ tempEl.id);
    //alert("element " + imgElem + "\\nparent "+ tempEl);
    while (tempEl != null) {
      xPos += tempEl.offsetLeft;
      tempEl = tempEl.offsetParent;
    }
  return xPos;
}

function getRealTop(imgElem) {
  yPos = imgElem.offsetTop;
  tempEl = imgElem.offsetParent;
  while (tempEl != null) {
      yPos += tempEl.offsetTop;
      tempEl = tempEl.offsetParent;
    }
  return yPos;
}

function get_page_boundaries()
{
  if (window.innerWidth) {
    distance_to_right_edge = window.innerWidth-mouse_x
    distance_to_bottom = window.innerHeight-mouse_y;
  } else if (document.body.clientWidth) {
    distance_to_right_edge = document.body.clientWidth-mouse_x;
    distance_to_bottom = document.body.clientHeight-mouse_y;
  }
}


function removename(el, name) {
  var i, curList, newList;
  // Remove the given class name from the className property of the element.
  newList = new Array();
  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
    if (curList[i] != name)
      newList.push(curList[i]);
  el.className = newList.join(" ");
}

function blink(el, times, onoff)
{
  if (times==0) 
  {
    if (onoff == 0 && document.getElementById(el).className.match(/blink/))
      removename (document.getElementById(el),"blink");
    if (onoff == 1 && !document.getElementById(el).className.match(/blink/))
      document.getElementById(el).className += " blink";
    return;
  }
  
  if (document.getElementById(el).className.match(/blink/))
    removename (document.getElementById(el),"blink");
  else
    document.getElementById(el).className += " blink";
  
  setTimeout("blink('"+el+"',"+(times-1)+", "+onoff+")", 100);
  
}

function setUpperRight(el) {
	/*
	if (document.body.clientWidth) {
		el.style.pixelLeft = document.body.clientWidth - el.offsetWidth;
	}
	else if (document.layers) {
		el.left = window.innerWidth - el.clip.width - 15;
	}
	*/
	
	if (document.body.clientWidth) {
		el.style.left = (document.body.clientWidth - el.clientWidth - 35) + 'px';
		el.style.top = document.body.scrollTop;

	} else if (window.innerWidth) {
		el.style.left = (window.innerWidth - el.clientWidth - 35) + 'px';
		el.style.top = window.scrollY;
	}
}

function dragStart(event, id) {

  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (window.event.srcElement)
      dragObj.elNode = window.event.srcElement;
    else if (event.target)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }
  
  dragObj.cursorStartX = mouse_x;
  dragObj.cursorStartY = mouse_y;
  dragObj.elStartLeft  = parseInt(getRealLeft(dragObj.elNode), 10);
  dragObj.elStartTop   = parseInt(getRealTop(dragObj.elNode),  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;
  dragObj.elNode.style.zIndex = ++dragObj.zIndex;
  // Capture mousemove and mouseup events on the page.

  if (document.attachEvent) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  
  if (document.addEventListener) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }    
}

function dragGo(event) {
  dragObj.elNode.style.left = (dragObj.elStartLeft + mouse_x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + mouse_y - dragObj.cursorStartY) + "px";
  
  if (window.event) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  
  if (event.preventDefault)
    event.preventDefault();  
} 

function dragStop(event) {
  // Stop capturing mousemove and mouseup events.

  if (document.detachEvent) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (document.removeEventListener) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}

function getStyle(obj, style){
  if(!document.getElementById) return;
  if(!obj.style) return;
    //window.status = "getting style "+style+" for object "+obj.toString();
    var value = obj.style[style];
    if(!value)
      if(document.defaultView)
        value = document.defaultView.getComputedStyle(obj, "").getPropertyValue(style);
      else if(obj.currentStyle)
        value = obj.currentStyle[style];
    return value.replace(/px$/,'');
}


function debug(text) {
	if (!document.getElementById('debug_info')) return;
	//if (!text || text == '') text = "null";
	text += '';
  text = text.replace(/\n/g, '<br/>');

	document.getElementById('debug_info').innerHTML += text+'<br/>';
}

function contains(a,t) {
  for (var i=0;i<a.length;i++)
    if (a[i] == t)
      return true;
  return false;
}

function DialogBox(properties) {

  this.id = (properties['id']) ? properties['id'] : null;
  this.title = (properties['title']) ? properties['title'] : '';
  this.element_id = (properties['element_id']) ? properties['element_id'] : null;
  this.contents = properties['contents'];
  this.element = document.createElement('div');     // the DOM element that holds the dialog box
  this.element.style.display = "none";
  this.element.className += "dialog_box";
  
  if (this.element_id) {
    this.element.id = this.element_id;
  } else {
    this.element.id = "dialog_box";
    if (this.id) this.element.id += "_"+this.id;
  }
  
  document.getElementsByTagName("body").item(0).appendChild(this.element);
  var temp = '<div class="header" onmousedown="dragStart(event, \''+this.element.id+'\')"><a id=\"'+this.element.id+'_hide" class="close" href="javascript:'+this.id+'.close()">[X]</a><span class="title" id="'+this.element.id+'_title">'+this.title+'</span></div>';
  temp += '<div class="contents" id="'+this.element.id+'_contents"></div>';
  temp += '<br style="clear:both;"/>';
  temp += '</div>';
  this.element.innerHTML = temp;
  
  this.hide_element = document.getElementById(this.element.id+"_hide");
  //XBrowserAddHandler(this.hide_element,"mousedown","mousedownHandler");
  
  this.hide_element.mousedownHandler = function() {
    //var id = this.id.replace(/_hide/, "");
    var eval_text = this.id+".close();";
    alert(eval_text);
    eval(eval_text);
  }

  this.reset = function()  {
    document.getElementById(this.element.id+"_title").innerHTML = "";
    document.getElementById(this.element.id+"_contents").innerHTML = "";
  }
  
  this.setContents = function(contents) {
    document.getElementById(this.element.id+"_contents").innerHTML = contents;
  }
  
  this.setTitle = function(title) {
    document.getElementById(this.element.id+"_title").innerHTML = title;
  }
  
  this.close = function() {
    this.element.style.display = "none";
  }
  
  this.anchor = function(el) {
    if (!el) { // anchor to mouse cursor
      this.element.style.left = '100px';
      this.element.style.top = (mouse_y-10)+"px";
    } else {
      this.element.style.left = getRealLeft(el)+10+"px";
      this.element.style.top = getRealTop(el)+10+"px";
    }
  }
  
}


