/**
 * This file must be included before any other javascript on the page. 
 * When all import statements are finished, init.js should also be included.
 * Both files should use the script tag, instead of the jsImport command.
**/
 
/**
 * register an onload event without over-writing the old one
 */
function registerWindowEvent(funct) {
	var old = (window.onload) ? window.onload : function () {};
	window.onload = function () {old(); funct()};
}

function doCopyPrototype(descendantName, parentName) { 
		var descendant = eval(descendantName);
		var parent = eval(parentName);
	    var sConstructor = parent.toString(); 
	    var aMatch = sConstructor.match( /\s*function (.*)\(/ ); 
	    if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; } 
	    for (var m in parent.prototype) { 
	        descendant.prototype[m] = parent.prototype[m]; 
	    } 
};

var _prototypes = new Array();
function copyPrototype(descendant, parent) {
	var prototype = new Object();
	prototype.descendant = descendant;
	prototype.parent = parent;
	
	/* If the descendant is a parent of another prototype, it must be declared first */
	var arrayLength = _prototypes.length;
	for (var i=0; i<_prototypes.length; i++) {
		if(_prototypes[i].parent == descendant) {
			if (i==0)
				_prototypes.unshift(prototype);
			else {
				var insertPos = i-1;
		    	array1 = _prototypes.slice(0,insertPos);
	    		array1.push(prototype);
	    		var array2 = _prototypes.slice(insertPos);
		    	_prototypes = array1.concat(array2);
		    }
		  	break;
		}
	}
	
	if (arrayLength == _prototypes.length) {
		_prototypes.push(prototype);
	}
	
}

function copyPrototypes() {
  for (var i=0; i<_prototypes.length; i++) {
    doCopyPrototype(_prototypes[i].descendant, _prototypes[i].parent);
  }
}

/* get all elements by a class name */
/* deprecated - use NodeUtils.getChildrenByClassName */
function getElementsByClassName(tagName, className){
		var elements = document.getElementsByTagName(tagName);
		var matches = new Array();
    for(var i=0; i<elements.length; i++){
        node = elements[i];
        if(node.className == className){
            matches[matches.length] = node;
        }
    }
    return (matches)
}

/* gets the current position of the cursor */
function getCursorPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}

/* stores an object into an array, referenced by 'id' */
var _objects = new Array();
function storeInArray(id, object) {
  if (_objects[id] == null)
  	_objects[id] = new Array();
  _objects[id][_objects[id].length] = object;
}

/**
*
* imports another script file
*
**/
var _jsImports = new Array();

function getFileNameFromUri(uri, timestamp) {
 var fileName = uri;
  if (uri.indexOf(".") >= 0) {
    var fileNameParts = uri.split(".");
    fileName = "/js/" + fileNameParts.join("/");
    if (timestamp != null)
    	fileName += "." + timestamp;
    fileName += ".js";
  }
  return fileName;
}

function jsImport(file) {
  var fileName = getFileNameFromUri(file);
  if (_jsImports[file] != null)
	return;

  _jsImports[file] = fileName;
 
   
  document.write("<script src=\"" + fileName + "\" type=\"text/javascript\"></script>\n");
 // alert("success");
}

function jsImportDynamic(uri, timestamp) {
   var fileName = getFileNameFromUri(uri, timestamp);
   var e = document.createElement("script");
   e.src = fileName;
   e.type="text/javascript";
   document.getElementsByTagName("head")[0].appendChild(e);
   return e;
}

/* remove the given object from the object array */
function removeFromArray(id, object) {
  var objects = _objects[id];
  var newObjects = new Array();
  for (var i=0; i<objects.length; i++) {
    if (objects[i] != object)
      newObjects[newObjects.length] = objects[i];
  }
  _objects[id] = newObjects;
}

/* retrieves array of object, referenced by 'id' */
function getArray(id) {
  return _objects[id];
}

/**
 * writes out to a debug window 
 */
 var debugWindow = null;
function debug(text) {
  if (debugWindow == null)
  	debugWindow = window.open("", 'debugWindow', "width=500,height=300,scrollbars=yes,resizeable=yes");
  top.debugWindow.document.writeln(text + "<br />");
}

/**
 * if an error occurs, try to log it to the server logs
 */
onerror = logError;
function logError(msg, url, line) {
 		
 		if (window.XMLHttpRequest) {
			var xmlHttpLogger = new XMLHttpRequest(); //Firefox, safari
		} else {
			var xmlHttpLogger = new ActiveXObject("Microsoft.XMLHTTP"); //IE
		}
		
		var queryString = encodeURI("msg=" + msg + "&url=" + url + "&line=" + line + "&page=" + window.location + "&userAgent=" + navigator.userAgent);
		xmlHttpLogger.open("GET", "/log-error.ajax?" + queryString, true);
		xmlHttpLogger.send(null);
		
		/* try to hide the error in live sites */
		if (url.indexOf("test.") >=0 || url.indexOf("devel.") >=0 || url.indexOf(".applynx.") >=0 || url.indexOf("local.") >=0)
			return false;
		else
			return true;
   
 }
