/*                    
                            __
                           /  \
   -__     <------------- |    |------->
      --__/               \    /       |
        /             __ --   --___     |
       /  _____      /____         )    |
      /  <     ---__   _   >- _/  )     |
     /  /       <   --     - _   )      |
    /  /    /\ |   |--________ \/        |
    \ /    |   |     |                   |--__   
     /    /    |      |                  |    ---_
    /_   _| __ |      |     neuecouch.de |
   <______|   \|_     _|________________<     
                <______|

                
                
Diversity Management, Version 1.0.0
Copyright (c) 2004-2005 neuecouch.de
Alle Urheber- und Leistungsschutzrechte vorbehalten

Achtung: Diese Anwendung ist keine Freeware. 
Diese Software wird Ihnen gemaess den Bestimmungen 
eines Lizenzabkommens zur Verfuegung gestellt und 
darf nur unter den darin beschriebenen Bestimmungen 
eingesetzt werden. Die Datei license.html finden
Sie Im Hauptverzeichnis von Simple Newsletter.

Internet: http://www.neuecouch.de
E-Mail:   setzen@neuecouch.de

*/   
/** 
 * gets an object from the source.
 * 
*/
function getObj(name){
  var obj;
  var style;
  if (document.getElementById)  {
  	this.obj = document.getElementById(name);
  	if(!this.obj) return;
	this.style = document.getElementById(name).style;
  }
  else if (document.all)  {
	this.obj = document.all[name];
	if(!this.obj) return;
	this.style = document.all[name].style;
  }  else if (document.layers)  {
	this.obj = getObjNN4(document,name);
	this.style = this.obj;
  }
}

/** 
 * helper function for getObj()
*/
function getSimpleObj(name){
  var obj;
  if (document.getElementById)  {
  	this.obj = document.getElementById(name);
  }  else if (document.all)  {
	this.obj = document.all[name];
  }  else if (document.layers)  {
	this.obj = getObjNN4(document,name);
  }
}


/**
 * helper function for getObj()
*/
function getObjNN4(obj,name){
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)	{
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}

/** 
 * a random value from 0 to n.
 * @return integer
*/
function rand ( n ) {
  return ( Math.floor ( Math.random ( ) * n + 1 ) );
}

/** 
 * returns a random value which is guaranteed to 
 * lie between min and max.
 * swapping min and max has no effect.
*/
function min_rand( min, max ) {
  var myMin = Math.min(min, max);
  var myMax = Math.max(min, max);
  return Math.floor(
  	myMin + (
  		Math.random() * ( myMax - myMin )
  	)
  );
}

/** 
 * writes a message to the error log.
 * @param message string
 * @access public
 * @return void
*/
function _doLog( message ) {
	if( null != theLogger ) {
		theLogger.innerHTML = _imageCounter; // message;
	} 
}

/** 
 * the game ticker. 
 * is sets the timeout to nextImage() according 
 * to a value between _minTime and _maxTime
 * @uses _minTime
 * @uses _maxTime
 * @uses nextImage()
 * @access public
 * @param void
 * @return void
*/
function _call() {
	_doLog(" <br/> ");
	var theResult = min_rand(_minTime, _maxTime);
	//_doLog(theResult);	
	setTimeout("nextImage()", theResult);

}

/** 
 * checks whether the image is already in use somewhere.
 * the method contains of two parts.
 * the first part looks whether the image was shown in this run,
 * in order to avoid too much repeating.
 * the second part looks whether an image of the same folder
 * is currently being displayed, in order to disallow two or more
 * images to be displayed at the same time.
 * @param theImage an url to an image.
 * @return boolean
 * @access public
*/
function _isUsed( theImage ) {
	
	// cache is full. reset the cache.
  	if ( imagesUsed.length >= Math.floor( matrix.length )) {
		_doLog("resetting used images index.");
		_initUsedCache();
	}
	
	// first part. see whether the image is in the cache.
	for( var i=0; i < imagesUsed.length; i++ ) {
   	 	if (imagesUsed[i] == theImage) {
    		_doLog("("+imagesUsed.length+"/" + matrix.length + ") " + theImage + " was used already");
       		return true;
    	}	
  	}
  	
  	_doLog(theImage + " is not in cache.");
	// second part: see whether an image of the same folder is being
	// displayed.  
	for ( var oIndex = 0; oIndex < theObjects.length; oIndex++ ) {
     	var cur = new getObj(theObjects[oIndex]);
     	if( _findFolder(cur.obj.src) == _findFolder(theImage)) {
     		_doLog("<br/>!!! another object (" + theObjects[oIndex] + ") uses this one.");
     		return true;
     	}
    		
    }

    // update the cache. 
	imagesUsed[ imagesUsed.length ] = theImage;
	return false;
}


/** 
 * computes the next image to be displayed.
 * this method is being called recursively through _call() .
 * @param void
 * @return void
 * @access public
*/
function nextImage() {
	
	if(!_gameRunning) {
		_doLog("game is stopped.");
		_call();
		return;
	}
	
	_replaceImage( theObjects[ rand( theObjects.length ) - 1 ] );
	
	// end of game.
	if ( _imageCounter++ > _maxIterations ) {
	  _doLog("finished.");
	  return;
	}	
	// continue the game. recursion.
	_call();

}

/**
 * replaces the image of layerName 
 * with a new random image.
 * @param layerName string
 * @return void
 * @access public
*/
function _replaceImage( layerName ) {
	_doLog("using layer " + layerName);
	
	var nextImage;
	var safetyCounter = 0;
	do {
		nextImage = matrix[ rand( matrix.length ) - 1];
		if (safetyCounter++ > (matrix.length + matrix.length )) {
			_doLog("<br/>safetycounter reached.");
			_initUsedCache();
			break;
		}
	} while ( _isUsed( nextImage) );
	
	_setImage(layerName, nextImage);
}
/** 
 * 
*/
function _setImage( layerName, imageUrl ) {
	var theNewImage = new getObj(layerName);
	theNewImage.obj.src = imageUrl;
}


/** 
 * shuffles a given array.
 * @param o array
 * @return the shuffled array
 * @access public
*/
function array_shuffle(o){
	for( var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
}

/** 
 * avoid duplicate images to be shown.
 * initializes the 'used images' cache.
 * @param void
 * @access public
*/
function _initUsedCache() {
	imagesUsed = new Array();
	for(var i = 0; i < theObjects.length; i++) {
		var theImage = new getObj(theObjects[i]);
		if( null == theImage.obj) {
			continue;
		}
		imagesUsed[ imagesUsed.length ] = theImage.obj.src;
	}
}

/** 
 * finds the folder of an image by the path to the image
 * @param imgUrl string
 * @return string
 * @access public
*/
function _findFolder( imgUrl ) {
	var a = imgUrl.split("/");
	return a[ a.length - 2 ];
}


/**
 * finds all images which are located within a given folder.
 * @param folder the folder name to look into
 * @return array
 * @access public
*/
function _findImagesIn( folder ) {
	var result = new Array();
	var _counter = 0;
	for ( var i = 0; i < matrix.length; i++ ) {
		if ( _findFolder(matrix[i]) == folder ) {
			result[ _counter++ ] = matrix[i];
		}
	}
	return result;
}

/**
 * redirects to the user's own images.
 * 
*/
function _doRedirect( theObject ) {
	
	if(!_gameRunning) {
		_swapGameState();
		_initUsedCache();
		for(var i = 0; i < theObjects.length; i++) {
			_replaceImage(theObjects[i]);	
		}
		_setRandomImageQuote();
		return;
	}
	
	_doLog("<br/>");
	var theFolder = _findFolder( theObject.src );
	
	_doLog( theFolder + " to be clicked. ");
	
	var imagesInFolder = array_shuffle( _findImagesIn( theFolder ));
	
	if( imagesInFolder.length < theObjects.length ) {
		_doLog("<br/>!!! error in game: the images in the folder are fewer than the objects to replace into.");
		_doLog("<br/>!!! replacing the images in folder with the matrix.");
		imagesInFolder = matrix;
	}
	
	_doLog(imagesInFolder + " found. ");
	
	for(var i = 0; i < theObjects.length; i++) {
		_setImage(theObjects[i], imagesInFolder[i]);
	}
	
	
		
	// set the game to running again.
	_swapGameState();
	_replaceQuote( theFolder );
	
}	

/** 
 * 
*/
function _setRandomImageQuote() {
	var q = new getObj( theQuoteObject );
	q.obj.innerHTML = '<img  id="theQuote" src="' + theRandomQuotes[ rand( theRandomQuotes.length - 1)]+ '" alt="" title="" />';
}


/** 
 * replaces the quote.
*/
function _replaceQuote( theFolder ) {
	var q = new getObj( theQuoteObject );
	q.obj.innerHTML = theQuoteHeader + theQuotes[theFolder];
}


/**
 * swaps the game state from running mode into 
 * stop mode.
 * the stop mode is reached when the user has clicked 
 * on an image and is viewing the images of one person.
*/
function _swapGameState() {
	_gameRunning = !_gameRunning;
}



