dojo.require("dojo.parser");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.cookie");
dojo.require("dojox.collections.Set");
dojo.require("dojox.rpc.Service");
dojo.require("ifpma.TooltipFromURL");

var SetOperations=dojox.collections.Set;

var done = function(items, request){
    console.log("Number of items located: " + items.length);
};

//Define a simple error handler.
var gotError = function(error, request){
    console.debug("The request to the store failed. " +  error);
}

var intersectionPages=null;

var countryName=null;
var countryPages=null;

function cleanArrayNulls(arr) {
	if (arr==null || arr.length==0 || (arr.length==1 && arr[0]==null))
		return null;
	else
		return arr;
}

function emptyField(field) {
       field.focus();
       field.focusNode.value="";
}


function fillField(field, value) {
       if (field.focusNode.value=="")
	       field.focusNode.value=value;
}


function selectById(ids) {
	var rootDiv = dojo.query("#search-toc li");
	var count=0;
	var countInCategory = 0;
	var category=null;
	rootDiv.forEach(
		function(element) {
		var sid=element.id;
		var nid=parseInt(sid) ;
		var visible = ids==null || ids.contains(nid);
		var styl = visible ? "block" :  "none" ;
		var container = element.parentNode.parentNode;
		if(category==null || category!==container) {
		if (category!=null)
			if(countInCategory==0) 
				category.style.display="none";
			else
				dojo.query(".sub-count", category)[0].innerHTML="("+countInCategory+")";
			container.style.display="block";
			category=container;
			countInCategory=0;
			}
		countInCategory+=visible;
		count+=visible;
		element.style.display=styl;
	    }
	)
	if (category!=null)
		if(countInCategory==0) 
			category.style.display="none";
		else
			dojo.query(".sub-count", category)[0].innerHTML="("+countInCategory+")";

	var displayCountryName = countryName!=null ? countryName : dijit.byId("country-chooser-input").value;
	var displayDiseaseName = diseaseName!=null ? diseaseName : dijit.byId("disease-chooser-input").value;
	var displayProgramName = programName!=null ? programName : dijit.byId("program-chooser-input").value;
	var displayPartnerName = partnerName!=null ? partnerName : dijit.byId("partner-chooser-input").value;

	var displayCompanyName = companyName!=null ? companyName : dijit.byId("company-chooser-input")!=null ? dijit.byId("company-chooser-input").value : null;
	var displayFicheId = ficheIdName!=null ? ficheIdName : dijit.byId("id-chooser-input")!=null ? dijit.byId("id-chooser-input").value : null;

	dojo.query("#count-label")[0].innerHTML= (count>1?""+count+" items":(count==0?"No items":"One item")) + 
	  " found for selection " + displayCountryName + ", " +displayDiseaseName + ", " +displayProgramName + ", " + 
	  displayPartnerName + (displayCompanyName!=null && dijit.byId("company-chooser-input")!=null ? ", "+displayCompanyName : "") +
		(displayFicheId!=null && dijit.byId("id-chooser-input")!=null ? ", "+displayFicheId : "") + ".";
}

function gotNewCountry(item) {
    if (stateStore.isItem(item)){
           var identityAttributes = stateStore.getIdentityAttributes(item);
           if(identityAttributes !== null){
 			  countryPages=cleanArrayNulls(stateStore.getValues(item, "value"));
			  countryName=stateStore.getValue(item, "key");
			  console.debug(countryName + " refers to pages " + countryPages);
			  console.dir(countryPages);
			  intersectionPages = calculateIntersection();
			  selectById(intersectionPages);
			  setRemember();
			  if (intersectionPages!=null && intersectionPages.count==0) {
				alert("Criteria yield no results. Unset some criteria.");
			  } else {
				console.debug("Intersection is: " + intersectionPages);
			}
           }else{
              failed(new Error("Unable to locate the list of attributes comprising the identity."));
           }
    }else{
        //This should never occur.
        throw new Error("gotNewCountry: Parameter ("+item+") is not item. Fatal.");
        }
}

function setCountry(value) {
	console.debug("Selected country: "+value);
	stateStore.fetchItemByIdentity({identity: value, onItem: gotNewCountry, onError: gotError});
}
		
var diseaseName=null;
var diseasePages=null;

function gotNewDisease(item) {
    if (diseaseStore.isItem(item)){
           var identityAttributes = diseaseStore.getIdentityAttributes(item);
           if(identityAttributes !== null){
			  diseasePages=cleanArrayNulls(diseaseStore.getValues(item, "value"));
			  diseaseName=diseaseStore.getValue(item, "key");
			  console.debug(diseaseName + " refers to pages " + diseasePages);
			  console.dir(diseasePages);
			  intersectionPages = calculateIntersection();
			  selectById(intersectionPages);
			  setRemember();
			  if (intersectionPages!=null && intersectionPages.count==0) {
				alert("Criteria yield no results. Unset some criteria.");
			  } else {
				console.debug("Intersection is: " + intersectionPages);
			}
           }else{
              failed(new Error("Unable to locate the list of attributes comprising the identity."));
           }
    }else{
        //This should never occur.
        throw new Error("gotNewDisease: Parameter ("+item+") is not item. Fatal.");
        }
}

function setDisease(value) {
	console.debug("Selected disease: "+value);
	diseaseStore.fetchItemByIdentity({identity: value, onItem: gotNewDisease, onError: gotError});
}
		
var programName=null;
var programPages=null;

function gotNewProgram(item) {
    if (programStore.isItem(item)){
           var identityAttributes = programStore.getIdentityAttributes(item);
           if(identityAttributes !== null){
 			  programPages=cleanArrayNulls(programStore.getValues(item, "value"));
			  programName=programStore.getValue(item, "key");
			  console.debug(programName + " refers to pages " + programPages);
			  console.dir(programPages);
			  intersectionPages = calculateIntersection();
			  selectById(intersectionPages);
			  setRemember();
			  if (intersectionPages!=null && intersectionPages.count==0) {
				alert("Criteria yield no results. Unset some criteria.");
			  } else {
				console.debug("Intersection is: " + intersectionPages);
			}
           }else{
              failed(new Error("Unable to locate the list of attributes comprising the identity."));
           }
    }else{
        //This should never occur.
        throw new Error("gotNewProgram: Parameter ("+item+") is not item. Fatal.");
        }
}

function setProgram(value) {
	console.debug("Selected program: "+value);
	programStore.fetchItemByIdentity({identity: value, onItem: gotNewProgram, onError: gotError});
}
		
var partnerName=null;
var partnerPages=null;

function gotNewPartner(item) {
    if (partnerStore.isItem(item)){
           var identityAttributes = partnerStore.getIdentityAttributes(item);
           if(identityAttributes !== null){
 			  partnerPages=cleanArrayNulls(partnerStore.getValues(item, "value"));
			  partnerName=partnerStore.getValue(item, "key");
			  console.debug(partnerName + " refers to pages " + partnerPages);
			  console.dir(partnerPages);
			  intersectionPages = calculateIntersection();
			  selectById(intersectionPages);
			  setRemember();
			  if (intersectionPages!=null && intersectionPages.count==0) {
				alert("Criteria yield no results. Unset some criteria.");
			  } else {
				console.debug("Intersection is: " + intersectionPages);
			}
           }else{
              failed(new Error("Unable to locate the list of attributes comprising the identity."));
           }
    }else{
        //This should never occur.
        throw new Error("gotNewPartner: Parameter ("+item+") is not item. Fatal.");
        }
}

function setPartner(value) {
	console.debug("Selected partner "+value);
	partnerStore.fetchItemByIdentity({identity: value, onItem: gotNewPartner, onError: gotError});
}

var companyName=null;
var companyPages=null;

function gotNewCompany(item) {
    if (companyStore.isItem(item)){
           var identityAttributes = companyStore.getIdentityAttributes(item);
           if(identityAttributes !== null){
 			  companyPages=cleanArrayNulls(companyStore.getValues(item, "value"));
			  companyName=companyStore.getValue(item, "key");
			  console.debug(companyName + " refers to pages " + companyPages);
			  console.dir(companyPages);
			  intersectionPages = calculateIntersection();
			  selectById(intersectionPages);
			  setRemember();
			  if (intersectionPages!=null && intersectionPages.count==0) {
				alert("Criteria yield no results. Unset some criteria.");
			  } else {
				console.debug("Intersection is: " + intersectionPages);
			}
           }else{
              failed(new Error("Unable to locate the list of attributes comprising the identity."));
           }
    }else{
        //This should never occur.
        throw new Error("gotNewCompany: Parameter ("+item+") is not item. Fatal.");
        }
}

function setCompany(value) {
	console.debug("Selected company "+value);
	companyStore.fetchItemByIdentity({identity: value, onItem: gotNewCompany, onError: gotError});
}

var ficheIdName=null;
var ficheIdPages=null;

function gotNewFicheId(item) {
	if (ficheIdStore.isItem(item)){
		var identityAttributes = ficheIdStore.getIdentityAttributes(item);
		if(identityAttributes !== null){
			ficheIdPages=cleanArrayNulls(ficheIdStore.getValues(item, "value"));
			ficheIdName=ficheIdStore.getValue(item, "key");
			console.debug(ficheIdName + " refers to pages " + ficheIdPages);
			console.dir(ficheIdPages);
			intersectionPages = calculateIntersection();
			selectById(intersectionPages);
			setRemember();
			if (intersectionPages!=null && intersectionPages.count==0) {
				alert("Criteria yield no results. Unset some criteria.");
			} else {
				console.debug("Intersection is: " + intersectionPages);
			}
		}else{
			failed(new Error("Unable to locate the list of attributes comprising the identity."));
		}
	}else{
			//This should never occur.
			throw new Error("gotNewFicheId: Parameter ("+item+") is not item. Fatal.");
	}
}

function setFicheId(value) {
	console.debug("Selected ficheId "+value);
	ficheIdStore.fetchItemByIdentity({identity: value, onItem: gotNewFicheId, onError: gotError});
}

function calculateIntersection() {
	var stack = [];
	if (countryPages!=null) {
		stack.push(countryPages);
	}
	
	if (diseasePages!=null) {
		stack.push(diseasePages);
	}
	
	if (programPages!=null) {
		stack.push(programPages);
	}
	
	if (partnerPages!=null) {
		stack.push(partnerPages);
	}
	
	if (companyPages!=null) {
		stack.push(companyPages);
	}
	
	if (ficheIdPages!=null) {
		stack.push(ficheIdPages);
	}
	
	if (stack.length==0)
		return null;
	
	if (stack.length==1)
		return  SetOperations.union(stack.pop(), []);
	
	var res = stack.pop();
	while (stack.length!=0) {
		res = SetOperations.intersection(res, stack.pop());
	}
	return res;
}

function getJson() {
	return dojo.toJson([countryName, countryPages, diseaseName, diseasePages, programName, programPages,
		partnerName, partnerPages, companyName, companyPages, ficheIdName, ficheIdPages]);
}


dojo.addOnLoad(function() {
	if (dijit.byId("remember-input")==null)
		return;
	// With one parameter, reads the cookie
	console.debug("cookie is "+dojo.cookie("ifpma-partnerships-search.cookie"));
	var remembered = dojo.fromJson(dojo.cookie("ifpma-partnerships-search.cookie"));
	if (remembered!=null) {
		countryName = remembered[0];
		countryPages = remembered[1];
		if (countryName!=null) dijit.byId("country-chooser-input").setValue(countryName);
		diseaseName = remembered[2];
		diseasePages = remembered[3];
		if (diseaseName!=null) dijit.byId("disease-chooser-input").setValue(diseaseName);
		programName = remembered[4];
		programPages = remembered[5];
		if (programName!=null) dijit.byId("program-chooser-input").setValue(programName);
		partnerName = remembered[6];
		partnerPages = remembered[7];
		if (partnerName!=null) dijit.byId("partner-chooser-input").setValue(partnerName);
		if (dijit.byId("company-chooser-input")!=null) {
			companyName = remembered[8];
			companyPages = remembered[9];
			if (companyName!=null) dijit.byId("company-chooser-input").setValue(companyName);
		}
		if (dijit.byId("id-chooser-input")!=null) {
			ficheIdName = remembered[10];
			ficheIdPages = remembered[11];
			if (ficheIdName!=null) dijit.byId("id-chooser-input").setValue(ficheIdName);
		}

		dijit.byId("remember-input").setValue(true);
		intersectionPages = calculateIntersection();
	} else  {
		dijit.byId("remember-input").setValue(false);
	}
	selectById(intersectionPages);
	dojo.byId("chooser-area").style.display="block";
	dojo.byId("count-label").style.display="block";
	dojo.byId("search-toc").style.display="block";
	}
);

function setRemember(set) {
	if (set==null) set = dijit.byId("remember-input").getValue();
	if (set) {
	// Calling dojo.cookie with two parameters sets a cookie
		var json = getJson();
		dojo.cookie("ifpma-partnerships-search.cookie",json);
	} else {
		// Third parameter is an object with other cookie options.  Here, setting the expires
		// property to -1 deletes the cookie
		dojo.cookie("ifpma-partnerships-search.cookie","Value Doesn't matter",{expires: -1});
		console.debug("cookie should now be null: "+dojo.cookie("ifpma-partnerships-search.cookie"));
	}
}
