//create the clusters
/*
function calcclusters() {
	
	for (var i = 0; i < _distribute.length; i++) {
	
		if(typeof(_clusters[i]) == "undefined") {
			
			_clusters[i] = new Array();
			
			_clusters[i].push(_distribute[i]);
		}
	} 
	
	for (var i = 0; i < _clusters.length; i++) {
		
		var _closest = 0;
		var _maxval = 0;
		
		for (var j = 0; j < _distribute.length; j++) {
		
			if (i != j) {
			
				var _tmpval = (_coocmatrix[i][j] / _coocmatrix[i][i]) * (_coocmatrix[i][j] / _coocmatrix[j][j]);
				
				if (_tmpval > _maxval) {
					_maxval = _tmpval;
					_closest = j;
				}
				
				console.log(_cooctermlist[i]["term"] + " x " + _cooctermlist[j]["term"] + ": " + _tmpval);
			}
		}
		
		_clusters[i].push(_closest)
	}
	
	screenMsgOut();
}*/

function recalcclusters() {
	
	screenMsgIn("thinking...");
	
	_distribute = new Array();
	_clusters = new Array();
	
	for(var i = 0; i < _coocmatrix.length; i++) {
		_distribute.push(i);
	}
	
	window.setTimeout("calcclusters()",50);
}


//create the clusters
function calcclusters() {
	
	_noClusters = $('#interface_noclusters').val();
	
	if (typeof(_clusters[0]) == "undefined") {
		
		for (var i = 0; i < _noClusters; i++) {
	
			_clusters[i] = new Array();
			
			var _myword = Math.floor(Math.random() * _distribute.length);
			
			_clusters[i].push(_distribute.splice(_myword, 1));
		}
		
	} else {
		
		var _tmpwords = new Array();
		var _tmpclusters = new Array;
		for (var i = 0; i < _noClusters; i++) {
			_tmpclusters.push(i);
		}
		
		for (var i = 0; i < _noClusters; i++) {

			var _myword  = Math.floor(Math.random() * _distribute.length);
			
			var _whereto = getDestinationCluster(_tmpclusters,_myword)
			
			_clusters[_whereto].push(_distribute.splice(_myword,1));
			_tmpclusters.splice(jQuery.inArray(_whereto,_tmpclusters),1);
			
            
            if (_distribute.length == 0) {
                shuffleclusters();
                return;
            }
		
		}
		
		//console.log("---");
		
		
	}
	
	calcclusters();
}

/*
// shuffle the words around
function shuffleclusters() {
	
	var _loopcounter = 0;
	var _whichcluster = Math.floor(Math.random() * _noClusters);
	
	for(var i = 0; i < _shuffleIter; i++) {
		
		for(var j = 0; j < _noClusters; j++) {
			
			var _bestwordindex = getBestWordFromOther(j);
			var _worstwordindex = getWeakestWord(j);
			var _worstword = _clusters[j][_worstwordindex];
			
			var _bestword = _clusters[_bestwordindex[0]].splice(_bestwordindex[1],1,_worstword);
			
			console.log(j + ": got " + _termlist[_bestword]["term"] + ", gave " + _termlist[_worstword]["term"]);
			
			_clusters[j].splice(_worstwordindex,1,_bestword);
			
		}
	}
	
	screenMsgOut();
}*/

function shuffleclusters(){

    var _loopcounter = 0;
    var _whichcluster = Math.floor(Math.random() * _noClusters);
    
    for (var i = 0; i < _shuffleIter; i++) {
    
        var _whichplace = Math.floor(Math.random() * _clusters[_whichcluster].length);
        
        var _newcluster = getBestDestinationCluster(_clusters[_whichcluster][_whichplace]);
        
        if (_whichcluster == _newcluster) {
            _loopcounter++;
        } else {
            _loopcounter = 0;
        }
        
        if (_loopcounter > 20) {
        
            _whichplace = getWeakestWord(_whichcluster);
            
            //console.log("weakest word: " + _whichplace + "(" + _termlist[_clusters[_whichcluster][_whichplace]]["term"] + ")");
            
            var _newcluster = getOtherDestinationCluster(_clusters[_whichcluster][_whichplace], _whichcluster);
            
            //console.log("goes to cluster " + _newcluster);
        }
        
        
        //console.log(_termlist[_clusters[_whichcluster][_whichplace]]["term"] + ": " +  _whichcluster + " => " + _newcluster);
        
        _clusters[_newcluster].push(_clusters[_whichcluster].splice(_whichplace, 1))
        
        _whichcluster = _newcluster;
        
    }
    
	dispClustersTagcloud();
    screenMsgOut();
}


function dispClustersTagcloud() {
	
	var _html = "";
		
	for (var i = 0; i < _clusters.length; i++) {
	  	
		_clusters[i].sort(clusterSortAlpha);
		
		// calculate biggest and smallest
		// ---------------------------------------------------------------------
		var _biggest = 0;
		var _smallest = 1000;
	
		for (var j = 0; j < _clusters[i].length; j++) {
		
			if (parseInt(_cooctermlist[_clusters[i][j]]["counter"]) > _biggest) {
				
				_biggest = _cooctermlist[_clusters[i][j]]["counter"];	
			}
			
			if (parseInt(_cooctermlist[_clusters[i][j]]["counter"]) < _smallest) {
				
				_smallest = _cooctermlist[_clusters[i][j]]["counter"];	
			}
		}
		
		_biggest -= _smallest;
		
		
		// display cluster termclouds
		// ---------------------------------------------------------------------
		_html += '<div class="cluster" id="cluster_'+i+'">';
		
		for (var j = 0; j < _clusters[i].length; j++) {
			
			var _tmpsize = _cooctermlist[_clusters[i][j]]["counter"] - _smallest;
		
			if(_tmpsize != 0) {
				
				_tmpsize = Math.round(_tmpsize / _biggest * (_styles.length - 1));
			}
			
			var _id = _cooctermlist[_clusters[i][j]]["id_alpha"];	  	
	  		_html += '<div class="term_div" id="cluster_' + i + '_tagcontainer_' + j + '"><span class="term" id="clustertagspan_' + _id + '" onclick="dispResult(' + _id + ');" style="' + _clusterStyles[_tmpsize] + '">' + removeX(_cooctermlist[_clusters[i][j]]["term"]) + '</span><span class="term_frequency">(' + _cooctermlist[_clusters[i][j]]["counter"]  + ')</span></div>';
	  	
		}
		
		_html += '</div><br /><br />';
	  
	}
	
	$("#clusters").html(_html);
}


function switchToCluster() {
	
	// interface operations
	// ---------------------------------------------------------------------
	$("#box_results").fadeOut();$("#box_results").fadeOut();
	
    //displayclusters();
 	
 
 	var _termlist_copy = _termlist.slice();
	_termlist_copy.sort(keySortCounter);
 
 	var _top = 0;

	var _positions = new Array();
	
    for (var i = 0; i < _termlist_copy.length; i++) {
		
		_positions[i] = {
			"left": $("#tagcontainer_"+_termlist_copy[i]["id_alpha"]).offset().left - $("#terms").offset().left,
			"top":_top + $("#terms").offset().top - $("#tagcontainer_"+_termlist_copy[i]["id_alpha"]).offset().top
		}
		
		_top += $("#tagcontainer_"+_termlist_copy[i]["id_alpha"]).height();
    }
	
	_transcounter = 0;
	
	
	
	for (var i = 0; i < _termlist_copy.length; i++) {
		
		_transcounter++;
		
		$("#tagcontainer_" + _termlist_copy[i]["id_alpha"]).animate({
            "left":"-=" + _positions[i].left,
            "top": "+=" + _positions[i].top + "px"
        }, 1600, function() {
			_transcounter--;
			
			if(_transcounter == 0) {
				
				setInterface("cluster");
				$("#box_results").fadeIn();
				$("#box_clusters").fadeIn();
			}
		});	
    }
}


function switchToCloud() {
	
	// interface operations
	// ---------------------------------------------------------------------
	$("#box_clusters").fadeOut();
	$("#box_results").fadeOut();
	
	for (var i = 0; i < _termlist.length; i++) {
		
		_transcounter++;
		
		$("#tagcontainer_" + _termlist[i]["id_alpha"]).animate({
            "left":"0px",
            "top": "0px"
        }, 1600, function() {
			_transcounter--;
			
			if(_transcounter == 0) {
				
				setInterface("cloud");
				$("#box_results").fadeIn();
			}
		});		
    }
}

// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------

function getWeakestWord(_id) {
	
	var _word = 0;
	var _minvalue = 10000;
	
	for(var i = 0; i < _clusters[_id].length; i++) {
	
		var _tmpvalue = 0;
		
		for (var j = 0; j < _clusters[_id].length; j++) {
			
			if (i != j) {
				_tmpvalue += (_coocmatrix[i][j] / _coocmatrix[i][i]) * (_coocmatrix[i][j] / _coocmatrix[j][j]);
			}
				
		}
		
		
		if(_tmpvalue < _minvalue) {
			_minvalue = _tmpvalue;
			_word = i;
		}
	}
	
	return _word;
}


//returns the best destination cluster for a given word
function getDestinationCluster(_tmpclusters,_word) {

	var _destination = 0;
	var _maxvalue = 0;

	for(var i = 0; i < _tmpclusters.length; i++) {
    
		var _tmpvalue = 0;
    
		for(var j = 0; j < _clusters[_tmpclusters[i]].length; j++) {
      		
			if(_word != _clusters[_tmpclusters[i]][j]) {
				_tmpvalue += (_coocmatrix[_word][_clusters[_tmpclusters[i]][j]] / _coocmatrix[_word][_word]) * (_coocmatrix[_word][_clusters[_tmpclusters[i]][j]] / _coocmatrix[_clusters[_tmpclusters[i]][j]][_clusters[_tmpclusters[i]][j]]);
			}
		}
		
		if(_tmpvalue > _maxvalue) {
			_maxvalue = _tmpvalue;
			_destination = _tmpclusters[i];
		}
		
		//console.log(_tmpvalue + " " + _maxvalue + " " + _tmpclusters[i]);
	}
  
  	//console.log(_destination);
	return _destination;
}

/*
function getBestWordFromOther(_cluster) {
	
	var _bestvalue = 0;
	var _word = 0;
	
	for (var i = 0; i < _noClusters; i++) {
	
		if(i != _cluster) {
			
			for (var j = 0; j < _clusters[i].length; j++) {
				
				var _tmpvalue = 0;
				
				for (var k = 0; k < _clusters[_cluster].length; k++) {
				
					_tmpvalue += (_coocmatrix[_clusters[i][j]][_clusters[_cluster][k]] / _coocmatrix[_clusters[i][j]][_clusters[i][j]]) * (_coocmatrix[_clusters[i][j]][_clusters[_cluster][k]] / _coocmatrix[_clusters[_cluster][k]][_clusters[_cluster][k]]);
				}
				
				if(_tmpvalue > _bestvalue) {
					_word = [i,j];
					_bestvalue = _tmpvalue;
				}			
			}
		}
	}
	
	return _word;
}
*/

function getBestDestinationCluster(_word){

    var _destination = 0;
    var _maxvalue = 0;
    
    for (var i = 0; i < _clusters.length; i++) {
    
        var _tmpvalue = 0;
        
        for (var j = 0; j < _clusters[i].length; j++) {
        
            if (_word != _clusters[i][j]) {
                _tmpvalue += _coocmatrix[_word][_clusters[i][j]];
            }
        }
        
        if (_tmpvalue > _maxvalue) {
            _maxvalue = _tmpvalue;
            _destination = i;
        }
    }
    
    return _destination;
}


//returns the best destination cluster for a given word but not where it comes from

function getOtherDestinationCluster(_word,_origin) {

	var _destination = 0;
	var _maxvalue = 0;

	for(var i = 0; i < _clusters.length; i++) {
    
		var _tmpvalue = 0;
    
		for(var j = 0; j < _clusters[i].length; j++) {
      		
			if(_word != _clusters[i][j]) {
				_tmpvalue += _coocmatrix[_word][_clusters[i][j]] / _coocmatrix[_clusters[i][j]][_clusters[i][j]];
			}
		}
		
		if(_tmpvalue > _maxvalue && i != _origin) {
			_maxvalue = _tmpvalue;
			_destination = i;
		}
	}
  
	return _destination;
}


function clusterSortAlpha(a,b) {
	
	if (_cooctermlist[a]["term"] < _cooctermlist[b]["term"]) {
		return -1;
	} else {
		return 1;
	}
}

