function BrowseByCompetenceApp() {
	this.lastUpdateIsFromFlashMovie=true;

	this.appState={};
	// focus=[[competenceIDs], [EQFLevels]]
	// one empty list means all levels for competence or all competences for level
	// two empty lists: no selection
	
	this.appState.focus = [[],[]];
	this.appState.domainID = "1";
	this.lastUpdateIsFromFlashMovie=false;
	this.domainLabels = {};
	
	BrowseByCompetenceApp.baseConstructor.call(this, $("#searchComponent"));
}

BrowseByCompetenceApp.extend(PagedSearch);


// ------------------------------------------------
// First: load domains

BrowseByCompetenceApp.prototype.startUp = function (){
	this.componentController.init();
	this.initDOMElems();
	this.loadDomains();
}

BrowseByCompetenceApp.prototype.loadDomains = function (){

	var _this = this;
	
	var callback=function (results, msg) {
		//if(msg=="success" && $(results).find("domain").size()>0){
		if(msg=="success"){
			_this.onDomainsLoaded(results);
		} else {
			_this.messageBox.showError("Error loading domains.");
		}
	};
	
	// load results
	console.log("------- BrowseByCompetenceApp.loadDomains", {} , callback);
	
	this.messageBox.showWorking("Loading domains...");
	$.get(MACEConstants.toolsURL+"browseByCompetence/php/getDomains.php", {}, callback, "xml");	

}
BrowseByCompetenceApp.prototype.onDomainsLoaded = function (result){
	console.log("BrowseByCompetenceApp.onDomainsLoaded", result);
	this.messageBox.showWorking("Loading matrix...");
	// create domain tabs	
	var _this=this;
	$(result).find("domain").each(function(){
		
		var id="domainID_"+$(this).attr("id");
		var label=$(this).find("title").text();
		_this.domainLabels[$(this).attr("id")]=label;
		$("#domainTabs ul").append('<li class="ui-tabs-unselect"><a href="#'+id+'">'+label+'</a></li>');
		$("#domainTabs").append('<div id="'+id+'" class="ui-tabs-panel ui-tabs-hide"></div>');
	});	

	var _this=this;

	$("#domainTabs").tabs().bind('tabsselect', function(event, ui) {
	  	console.log("tabClicked "+ui.tab.toString().split("domainID_")[1]);
	   	_this.setDomainID(ui.tab.toString().split("domainID_")[1]);
	    return true;
	});	
	
	this.loadFacetCounts();
}


// ------------------------------------------------
// Second: load facet counts

BrowseByCompetenceApp.prototype.loadFacetCounts = function (result){
	console.log("------- BrowseByCompetenceApp.loadFacetCounts");
	// load counts first
	this.solrServiceConnector = new SolrServiceConnector(this);
	this.solrServiceConnector.setParams(new Query());
	this.solrServiceConnector.getResults();
}

	
BrowseByCompetenceApp.prototype.onFacetResult = function (facetCounts){
	this.facetCounts=facetCounts["lom.classification.taxonpath.taxon.competency.eqf"];
	console.log("------- BrowseByCompetenceApp.onFacetResult", this.facetCounts);
	this.embedFlashMovie();
}

// ------------------------------------------------
// Third: embed Flash

BrowseByCompetenceApp.prototype.embedFlashMovie=function(){

	// stringify facet counts
	var a=[];
	for (var x in this.facetCounts){
		a.push(x+":"+this.facetCounts[x].numItems);
	}
	a=a.join(",");
	
	
	var flashvars = {
		"domainID": this.appState.domainID,
	  	"serviceURL": MACEConstants.toolsURL+"browseByCompetence/php/getCompetencesForDomain.php?domainID={0}",
	  	"facetCounts": a
	};
	
	var params = {
		"name":	"competenceMatrix",
		"id":	"competenceMatrix"
	};
	
	var attributes = {
		"menu": "false",
		"salign":"TL",
		"scale":"noscale",
		"wmode":"opaque"
	};
	
	console.log("embed "+ MACEConstants.toolsURL+"browseByCompetence/swf/competence_matrix.swf");
	swfobject.embedSWF(MACEConstants.toolsURL+"browseByCompetence/swf/competence_matrix.swf", "competenceMatrix", "100%", "20", "9.0.0", MACEConstants.rootURL+"js/flashInstall/expressInstall.swf", flashvars, params, attributes);	
}

// finally: app ready

BrowseByCompetenceApp.prototype.onFlashReady=function(){
	console.log("BrowseByCompetenceApp.onFlashReady");
	this.onAppReady();	
}

BrowseByCompetenceApp.prototype.onAppReady = function(){
	console.log("BrowseByCompetenceApp.onAppReady");
	this.messageBox.hide();
	BrowseByCompetenceApp.superClass.onAppReady.call(this);
}

// ------------------------------------------------
// Query handling etc.

BrowseByCompetenceApp.prototype.setDomainID = function(id){
	this.appState.domainID=id;
	this.appState.focus=[[],[]];
	this.storeStateInURL();

}

BrowseByCompetenceApp.prototype.onStateChange=function(event){	
	console.log("BrowseByCompetenceApp.onStateChange 1", this.appState);
	BrowseByCompetenceApp.superClass.onStateChange.call(this, event);
	console.log("BrowseByCompetenceApp.onStateChange 2", this.appState);	
	// DOMAIN

	var domainID=SWFAddress.getParameter("domainID");
	this.appState.domainID = (Utils.isUndefined(domainID) || domainID=="") ? "1" : domainID;
	console.log("BrowseByCompetenceApp.onStateChange 3", this.appState);	
	
	$("#domainTabs").tabs('select', '#domainID_' + this.appState.domainID);
	
	// ID
	var focus = SWFAddress.getParameter("focus");
	if(!Utils.isUndefined(focus) && focus.indexOf("/")>-1) {
		this.appState.focus=focus.split("/");
		this.appState.focus[0] = (this.appState.focus[0] == "") ? [] : this.appState.focus[0].split(",");	
		this.appState.focus[1] = (this.appState.focus[1] == "") ? [] : this.appState.focus[1].split(",");	
	} else {
		this.appState.focus=[[],[]];
	}
	
	console.log("BrowseByCompetenceApp.onStateChange 4", this.appState);		
		
	if(!this.lastUpdateIsFromFlashMovie){
		this.updateFlashMovie();	
	} else {
		this.lastUpdateIsFromFlashMovie=false;
	}
	console.log("BrowseByCompetenceApp.onStateChange 5", this.appState);			

		
	this.buildQueryAndLoadResults();
	console.log("BrowseByCompetenceApp.onStateChange 6", this.appState);			
}
	
BrowseByCompetenceApp.prototype.buildQueryAndLoadResults=function(event){	
	this.query = new Query();
	this.query.addLOMConstraint("lom.classification.taxonpath.taxon.id.domain", this.appState.domainID,  this.domainLabels[this.appState.domainID]);
	
	// focus=[[competenceIDs], [EQFLevels]]
	// one empty list means all levels for competence or all competences for level
	// two empty lists: no selection
	var f=this.appState.focus;
	/*
	if(f[0].length){
		// takes only one ID at the moment
		var id = f[0][0];
		try {
			var label=MACE.labelDict["lom.classification.taxonpath.taxon.id.competency"][id];
		} catch (e) {
			var label=id;
		}
		this.query.addLOMConstraint("lom.classification.taxonpath.taxon.id.competency", id, label);
	} 
	if(f[1].length){
		var eqf = f[1][0];
		this.query.addLOMConstraint("lom.classification.taxonpath.taxon.competency.eqf", eqf, "EQF:"+eqf);
	} 
	*/
	if(f[0].length && f[1].length){
		// cell click
		var id = f[0][0];
		try {
			var label=MACE.labelDict["lom.classification.taxonpath.taxon.id.competency"][id];
		} catch (e) {
			var label=id;
		}
		var eqf = f[1][0];
		this.query.addLOMConstraint("lom.classification.taxonpath.taxon.competency.eqf", id+"_"+eqf, label);
	} else if (f[1].length){
		var eqf = f[1][0];
		this.query.addLOMConstraint("lom.classification.taxonpath.taxon.eqf", eqf, "EQF:"+eqf);
	} else if (f[0].length){
		var id = f[0][0];
		try {
			var label=MACE.labelDict["lom.classification.taxonpath.taxon.id.competency"][id];
		} catch (e) {
			var label=id;
		}
		this.query.addLOMConstraint("lom.classification.taxonpath.taxon.id.competency", id, label);	
	} 

		
	this.updateWindowTitle();
	var p=Number(SWFAddress.getParameter("page"));
	this.loadResults(p);
}

// store application state in URL
// -> will call onStateChange via SWFAddress listener
BrowseByCompetenceApp.prototype.storeStateInURL=function(){
	var q="?";
	q+= "domainID="+this.appState.domainID;
	q+= "&focus="+ this.appState.focus.join("/");
	q+= "&page="+this.currentPage;
	SWFAddress.setValue(q);
}

BrowseByCompetenceApp.prototype.onFlashHeightChanged=function(h){
	$("#competenceMatrix").css("height", h);
}

/** FLASH EVENT handler **/

BrowseByCompetenceApp.prototype.onFocusChange=function (focus){
	console.log("BrowseByCompetenceApp.onFocusChange", focus);
	if(focus.toString()!=this.appState.focus.toString()){
		this.appState.focus=focus;
		this.lastUpdateIsFromFlashMovie=true;
		this.storeStateInURL();	
	}

}

BrowseByCompetenceApp.prototype.updateFlashMovie=function (){
	var f=Utils.getFlashMovie("competenceMatrix");
	if(f && f.setDomainID && f.setFocus){
		f.setDomainID(this.appState.domainID);
		f.setFocus(this.appState.focus);
	}
}

