//alert('lpd.js');

// 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 = 100000000;

addLoadEvent(set_page_loaded);

function $() {
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == 'string')
			element = getElementByIdCompat(element);
		if (arguments.length == 1)
			return element;
		elements.push(element);
	}
	return elements;
}
function getElementByIdCompat(name) {
	if (document.getElementById) {
		return document.getElementById(name);
	} else if (document.all) {
		return document.all[name];
	} else if (document.layers) {
		var theobj = {};
		theobj = document.layers[name];
		theobj.style = document.layers[name];
		return theobj;
	}
}



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 addGenericEvent(source, trigger, func) {
  if (source.addEventListener)
    source.addEventListener(trigger,func,false);
  else if (source.attachEvent)
    source.attachEvent("on"+trigger,func);
}

function removeGenericEvent(source, trigger, func) {
  if (source.removeEventListener)
    source.removeEventListener(trigger,func,true);
  else if (source.detachEvent)
    source.detachEvent("on"+trigger,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 getcookie(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 c.substring(nameEQ.length,c.length);
	}
	return null;
}


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 && document.getElementById(el).className.match(/blink/))
      removename (document.getElementById(el),"blink");
    if (onoff && !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 js_include(url, id) {
  var new_script = document.createElement('script');
  new_script.type = 'text/javascript';
  if (id) new_script.id = id;
  new_script.src = url;
  document.getElementsByTagName('head').item(0).appendChild(new_script);
}

function css_include(url, id) {
  var new_css_file = document.createElement('link');
  new_css_file.type = 'text/css';
  if (id) new_css_file.id = id;
  new_css_file.rel = "stylesheet";
  new_css_file.href = url;
  document.getElementsByTagName('head').item(0).appendChild(new_css_file);
}


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/>';
  //alert(document.getElementById('debug_info').innerHTML);
}

function hex2dec(s){return parseInt(s,16);}

function compatible_textcolor(color){

    var r = hex2dec(color.substr(1,2));
    var b = hex2dec(color.substr(3,2));
    var g = hex2dec(color.substr(5,2));

    var brightness = Math.round((r*299+g*587+b*114)/1000);

    if (brightness < 128){return "#ffffff";}
    else{return "#000000";}
}


function DialogBox(properties) {

  this.id = (properties['id']) ? properties['id'] : null;
  this.title = (properties['title']) ? properties['title'] : '';
  this.images_url = (properties['images_url']) ? properties['images_url'] : '';
  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";
  this.subDialogBox = null;  // holy recursion, batman!  The dialog box can contain another!
  
  if (!this.element_id) {
    this.element_id = "dialog_box";
  }
  this.element.id = this.element_id;  // confusing!
  
  //if (this.id) this.element_id += "_"+this.id;
  //alert(this.id+' '+this.element_id);
  
  document.getElementsByTagName("body").item(0).appendChild(this.element);
  var temp = '<div class="header" style="background-image:url('+this.images_url+'gradient_background1.png);background-repeat:repeat-x;" onmousedown="dragStart(event, \''+this.element_id+'\')"><a id=\"'+this.element_id+'_hide" class="close" href="javascript:'+this.id+'.close()"><img src="'+this.images_url+'close_button1.gif" alt="[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() {
    if (this.subDialogBox)
      this.subDialogBox.close();
    this.element.style.display = "none";
  }
  
  this.anchor = function(el) {
  
    if (dragObj.zIndex < this.element.style.zIndex)
      dragObj.zIndex = this.element.style.zIndex;
    else
      this.element.style.zIndex = dragObj.zIndex+1;
  
    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";
    }
    
    
  }
  
}


// Array Extensions  v1.0.6
// documentation: http://www.dithered.com/javascript/array/index.html
// license: http://creativecommons.org/licenses/by/1.0/
// code by Chris Nott (chris[at]dithered[dot]com)


var undefined;
function isUndefined(property) {
  return (typeof property == 'undefined');
}


// Array.concat() - Join two arrays
if (isUndefined(Array.prototype.concat) == true) {
  Array.prototype.concat = function (secondArray) {
     var firstArray = this.copy();
     for (var i = 0; i < secondArray.length; i++) {
        firstArray[firstArray.length] = secondArray[i];
     }
     return firstArray;
  };
}

// Array.pop() - Remove the last element of an array and return it
if (isUndefined(Array.prototype.pop) == true) {
  Array.prototype.pop = function() {
     var lastItem = undefined;
    if ( this.length > 0 ) {
        lastItem = this[this.length - 1];
        this.length--;
    }
    return lastItem;
  };
}

// Array.push() - Add an element to the end of an array
if (isUndefined(Array.prototype.push) == true) {
  Array.prototype.push = function() {
     var currentLength = this.length;
     for (var i = 0; i < arguments.length; i++) {
        this[currentLength + i] = arguments[i];
     }
     return this.length;
  };
}

// Array.shift() - Remove the first element of an array and return it
if (isUndefined(Array.prototype.shift) == true) {
  Array.prototype.shift = function() {
     var firstItem = this[0];
     for (var i = 0; i < this.length - 1; i++) {
        this[i] = this[i + 1];
     }
     this.length--;
     return firstItem;
  };
}

// Array.slice() - Copy several elements of an array and return them
if (isUndefined(Array.prototype.slice) == true) {
  Array.prototype.slice = function(start, end) {
     var temp;
     
     if (end == null || end == '') end = this.length;
     
     // negative arguments measure from the end of the array
     else if (end < 0) end = this.length + end;
     if (start < 0) start = this.length + start;
     
     // swap limits if they are backwards
     if (end < start) {
        temp  = end;
        end   = start;
        start = temp;
     }
     
     // copy elements from array to a new array and return the new array
     var newArray = new Array();
     for (var i = 0; i < end - start; i++) {
        newArray[i] = this[start + i];
     }
     return newArray;
  };
}

// Array.splice() - Splice out and / or replace several elements of an array and return any deleted elements
if (isUndefined(Array.prototype.splice) == true) {
  Array.prototype.splice = function(start, deleteCount) {
     if (deleteCount == null || deleteCount == '') deleteCount = this.length - start;
     
     // create a temporary copy of the array
     var tempArray = this.copy();
     
     // Copy new elements into array (over-writing old entries)
     for (var i = start; i < start + arguments.length - 2; i++) {
        this[i] = arguments[i - start + 2];
     }
     
     // Copy old entries after the end of the splice back into array and return
     for (var i = start + arguments.length - 2; i < this.length - deleteCount + arguments.length - 2; i++) {
        this[i] = tempArray[i + deleteCount - arguments.length + 2];
     }
     this.length = this.length - deleteCount + (arguments.length - 2);
     return tempArray.slice(start, start + deleteCount);
  };
}

// Array.unshift - Add an element to the beginning of an array
if (isUndefined(Array.prototype.unshift) == true) {
  Array.prototype.unshift = function(the_item) {
     for (loop = this.length-1 ; loop >= 0; loop--) {
        this[loop+1] = this[loop];
     }
     this[0] = the_item;
     return this.length;
  };
}


function array_kickout(ar, the_item) {
  var tempArray = new Array();
  
  for (var i = 0; i < ar.length; i++)
     if (ar[i] != the_item)
       tempArray.push(ar[i]);
  return tempArray;
}

function array_indexof(ar,searchElement) {
  if (isUndefined(Array.prototype.indexOf) == false)
    return ar.indexOf(searchElement);
    
  for(var i=0;i<ar.length;i++)
    if(searchElement == ar[i]) return i;
  return -1
}

function array_contains(ar, el) {
  for(var i=0;i<ar.length;i++) {
    //debug('comparing ('+el+') and ('+ar[i]+')');
    if(el == ar[i]) return true;
  }
  return false;
}




