/*
ALL SCRIPTING IN THIS DOCUMENT WAS WRITTEN BY NICK ANNIS FOR THE ENGINES AND ENERGY CONVERSION LAB (CSU)
	-last revised: 5/20/09
	
	-requires additional files:
		vector.js

AVAILABLE FUNCTIONS:
-add				:	adds data and a corresponding key to the back of the vector 
									-args:	value 		- data to be stored
											key			- (optional) key to identify data by
-findKey			:	returns index in the vector corresponding to the location of the key and associated data,
						returns -1 if no matching key is found
									-args:	key			- key to search for within the vector
-findValue			: 	returns index in the vector where the data is stored, returns -1 if matching data is not found
									-args:	value		- data to search for (must match)
-remove				: 	removes an element by location within the vector
									-args:	value		- INT: index location to remove, may also be a "key"
														  value, or data value to search for
-get				: 	returns data stored at a specific location
									-args:	index		- INT: index location to return
-size				: 	returns the number of elements in the vector
											

*/

function Vector(copy){
	if(typeof copy == "undefined")
		copy = null;
	this.data = new Array();
	this.lastPos = 0;
	
	if(copy != null && typeof copy[0] != "undefined"){
		for(var i=0;i<copy.length;i++){
			this.add(copy[i]);
		}
	}
	
	return true;
}

Vector.prototype.add = function(value,key){
	if(typeof key == "undefined")
		key = null;
	
	this.data[this.lastPos++] = [value,key];
}

Vector.prototype.findKey = function(key){
	for(var i=0;i<this.lastPos;i++){
		if(this.data[i][1]==key){
			return i;
		}
	}
	return -1;
}

Vector.prototype.findValue = function(value){
	for(var i=0;i<this.lastPos;i++){
		if(this.data[i][0]==value){
			return i;
		}
	}
	return -1;
}

Vector.prototype.remove = function(value){
	var index = -1;
	if(typeof value!="number"){
		index = findKey(value);
		if(index<0){
			index = findValue(value);
		}
	}
	else{
		index = value;
	}
	if(index>=0 && index<this.lastPos){
		for(var i = index;(i+1)<this.lastPos;i++){
			this.data[i] = this.data[i+1];
		}
		this.data[--this.lastPos] = null;
		return true;
	}
	else
		return false;
}

Vector.prototype.get = function(index){
	try{
		return this.data[index][0];
	}
	catch(err){
		return null;
	}
}

Vector.prototype.getKey = function(index){
	try{
		return this.data[index][1];
	}
	catch(err){
		return null;
	}
}

Vector.prototype.size = function(){
	return this.lastPos;
}

Vector.prototype.shuffle = function(){
	for(var i=0;i<this.lastPos;i++){
		var j = Math.floor(Math.random()*this.lastPos);
		this.swapPositions(i,j);
	}
}

Vector.prototype.swapPositions = function(first,second){
	if(first!=second){
		var temp = [this.data[second][0], this.data[second][1]];
		this.data[second] = [this.data[first][0], this.data[first][1]];
		this.data[first] = temp;
	}
}