//License.js 
// code to operate the intelligent license picker.
// v2.9, modified by Jon to update selection of licenses.
// Global methods.
generateRightsCode = function( someTerms ) {
	//console.log(someTerms);
	// Generate a binary code corresponding to correspondences in the complete list of terms above.
	// Ie, ["attribution", "combinations-none"] becomes 1010000....
	var rightsCode = "" ;
	for (var termCounter=0; termCounter < terms.length; termCounter++) {
		var termConfirmed = false ;
		for (var thisTermCounter=0; thisTermCounter < someTerms.length; thisTermCounter++) {
			if (someTerms[thisTermCounter] == terms[termCounter].id) {
				rightsCode += "1" ;
				termConfirmed = true ;
			}
		};
		if (!termConfirmed) rightsCode += "0" ;				
	};
	//console.log(rightsCode);
	return rightsCode ;
}
inferLicense = function(someTerms) { 
	// When rights are viewed on later reload, select a license based on the terms chosen, if appropriate.
	// Compare selected terms to existing licenses, and select one if there is a match. This is a condensed version of the code in setCorrelations, but without checkbox behaviors.
	// Note that LicenseManager will not be loaded, but License.js will be, so the licenses array will be defined, as will the .rightsCode property for any license.
	var termsArray = new Array();
	for(termName in someTerms){
		if(termName != 'custom-rights'){
			termsArray.push(termName);	
		}	
	}
	for (var licenseCounter=0; licenseCounter < licenses.length; licenseCounter++) {
		if ( licenses[licenseCounter].rightsCode == generateRightsCode(termsArray) ) {
			//glossDivsNamed['gloss-' + licenses[licenseCounter].id].style.display = 'block';
			return licenses[licenseCounter].id;
		}
	}
	return false;
}
// Many other methods are contextualized within LicenseManager, which is only available for input panels.
function LicenseManager(argObj) { 
	// argObj.containerEle is where the licenses, terms, and glosses will appear.
	// termsObj has the form {'attribution': '1','custom-rights': '','combinations-sharealike': '1', 'transformations-sharealike': 1,'view-source': '1'}.
	// poolType (= "creation" or "reference") changes default license terms.
	this.licenseDiv = (typeof argObj.containerEle != "undefined")? argObj.containerEle : document.body ; // The panel containing license form elements.
	this.termsObj = (typeof argObj.termsObj != "undefined")? argObj.termsObj : "No terms passed" ;
	this.poolType = (typeof argObj.poolType != "undefined")? argObj.poolType : "reference" ;
	this.currentRightsCode = "" ; // A string of 0s and 1s indicating which terms are now selected. Helps correlate licenses and terms.
	this.inputTags = gEBI(this.licenseDiv, "terms-right").getElementsByTagName("input");
	this.glossDivs = gEBI(this.licenseDiv, "glosses").getElementsByTagName("div");
	this.licenseInputs = gEBI(this.licenseDiv, "licenses-left").getElementsByTagName("input");
	
	//John added this to try to get it to run a bit faster
	this.inputTagsNamed = new Array();
	this.glossDivsNamed = new Array();
	this.licenseInputsNamed = new Array();
	
	for(var i=0; i<this.inputTags.length; i++) this.inputTagsNamed[this.inputTags[i].id] = this.inputTags[i];
	for(var i=0; i<this.glossDivs.length; i++) this.glossDivsNamed[this.glossDivs[i].id] = this.glossDivs[i];
	for(var i=0; i<this.licenseInputs.length; i++) this.licenseInputsNamed[this.licenseInputs[i].id] = this.licenseInputs[i]; 
	
	this.termShroud = gEBI(this.licenseDiv, "term-shroud");
	this.customInput = gEBI(this.licenseDiv, "custom-rights");
	
	//Methods	
	this.modifyRightsCode = function( indexToReplace, replacementDigit ) { // indexToReplace corresponds to the term just changed; replacementDigit is "0" or "1" as string.
		var currentRightsCodeBeginning = this.currentRightsCode.substring( 0, indexToReplace ) ;
		var currentRightsCodeEnding = this.currentRightsCode.substring( indexToReplace + 1, this.currentRightsCode.length ) ;
		this.currentRightsCode = currentRightsCodeBeginning + replacementDigit + currentRightsCodeEnding ;
	}
	
	this.activateButtonsAndGlosses = function( inputIds ) { // inputIds is an array of ids as strings.
		for (var idCounter=0; idCounter < inputIds.length; idCounter++) {
			//gEBI(this.licenseDiv, inputIds[idCounter]).checked = true ;
			this.inputTagsNamed[inputIds[idCounter]].checked = true;
			try {
				//gEBI(this.licenseDiv, "gloss-" + inputIds[idCounter]).style.display = "block" ;
				this.glossDivsNamed["gloss-" + inputIds[idCounter]].style.display = 'block';
				
			}
			catch(e) {
				alert(inputIds[idCounter] + "is causing a problem with gloss displays.")
			}
		};
	}
	
	this.setCorrelations = function(inputType, inputId) { // Called when rights options are clicked.
		if (inputType == "license") {
			// Hide all glosses.
	    	for (var glossCounter=0; glossCounter < this.glossDivs.length; glossCounter++) {
				this.glossDivs[glossCounter].style.display = "none" ;
			};
			// Set Public Domain (totally free) license terms.
			for (var inputCounter=0; inputCounter < this.inputTags.length; inputCounter++) {
				this.inputTags[inputCounter].checked = false ;
			};
			// Then add terms for license chosen by user.
			if (inputId == "all-rights-reserved") {
				this.termShroud.style.display = "block" ;
			}
			else {
				this.termShroud.style.display = "none" ;
				if (inputId != "public-domain") {
					this.inputTagsNamed['attribution'].checked = true;
					//gEBI(this.licenseDiv, "attribution").checked = true ;
				}
			}
			this.activateButtonsAndGlosses( licenses[ inputId ].terms ) ;
			//gEBI(this.licenseDiv, "gloss-" + inputId ).style.display = "block" ;
			this.glossDivsNamed['gloss-' + inputId].style.display = 'block';
			this.currentRightsCode = generateRightsCode( licenses[ inputId ].terms );
		}
		else { // inputType is "term"--update selected terms.
			// Change the digit corresponding to the right just added.
			//if ( gEBI(this.licenseDiv, inputId).checked ) { // User added a term.
			if(this.inputTagsNamed[inputId].checked){ //User added a term
				//gEBI(this.licenseDiv, "gloss-" + inputId ).style.display = "block" ;
				this.glossDivsNamed['gloss-' + inputId].style.display = "block";
				var digitToReplace = "1" ;
			}
			else { // User unclicked a term.
				//gEBI(this.licenseDiv,  "gloss-" + inputId ).style.display = "none" ;
				this.glossDivsNamed['gloss-' + inputId].style.display = "none";
				var digitToReplace = "0" ;
			}
			this.modifyRightsCode( terms[ inputId ].integer , digitToReplace ) ;
			// If the input changes a combinations or transformations right, adjust those dependencies to match.
			// Note that a user never unchecks a radio button, so all these digits to replace can be 0.
			switch ( inputId ) {
				case "combinations-allowed" :
					this.modifyRightsCode( terms[ "combinations-none" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-combinations-none" ).style.display = "none" ;
					this.glossDivsNamed['gloss-combinations-none'].style.display = "none";
					this.modifyRightsCode( terms[ "combinations-sharealike" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-combinations-sharealike" ).style.display = "none" ;
					this.glossDivsNamed['gloss-combinations-sharealike'].style.display = "none";
					break ;
				case "combinations-none" :
					this.modifyRightsCode( terms[ "combinations-allowed" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-combinations-allowed" ).style.display = "none" ;
					this.glossDivsNamed['gloss-combinations-allowed'].style.display = "none";
					this.modifyRightsCode( terms[ "combinations-sharealike" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-combinations-sharealike" ).style.display = "none" ;
					this.glossDivsNamed['gloss-combinations-sharealike'].style.display = "none";
					break ;
				case "combinations-sharealike" :
					this.modifyRightsCode( terms[ "combinations-allowed" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-combinations-allowed" ).style.display = "none" ;
					this.glossDivsNamed['gloss-combinations-allowed'].style.display = "none";
					this.modifyRightsCode( terms[ "combinations-none" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-combinations-none" ).style.display = "none" ;
					this.glossDivsNamed['gloss-combinations-none'].style.display = "none";
					break ;
				case "transformations-allowed" :
					this.modifyRightsCode( terms[ "transformations-none" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-none" ).style.display = "none" ;
					this.glossDivsNamed['gloss-transformations-none'].style.display = "none";
					this.modifyRightsCode( terms[ "transformations-sharealike" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-sharealike" ).style.display = "none" ;
					this.glossDivsNamed['gloss-transformations-sharealike'].style.display = "none";
					break ;
				case "transformations-none" :
					this.modifyRightsCode( terms[ "transformations-allowed" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-allowed" ).style.display = "none" ;
					this.glossDivsNamed['gloss-transformations-allowed'].style.display = "none";
					this.modifyRightsCode( terms[ "transformations-sharealike" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-sharealike" ).style.display = "none" ;
					this.glossDivsNamed['gloss-transformations-sharealike'].style.display = "none";
					break ;
				case "transformations-sharealike" :
					this.modifyRightsCode( terms[ "transformations-allowed" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-allowed" ).style.display = "none" ;
					this.glossDivsNamed['gloss-transformations-allowed'].style.display = "none";
					this.modifyRightsCode( terms[ "transformations-none" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-none" ).style.display = "none" ;
					this.glossDivsNamed['gloss-transformations-none'].style.display = "none";
					break ;
				case "all-rights-reserved" :
					this.termShroud.style.display = 'block';
					this.modifyRightsCode( terms[ "transformations-allowed" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-allowed" ).style.display = "none" ;
					this.glossDivsNamed['gloss-transformations-allowed'].style.display = "none";
					this.modifyRightsCode( terms[ "transformations-sharealike" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-none" ).style.display = "none" ;
					this.glossDivsNamed['gloss-transformations-sharealike'].style.display = "none";
					this.modifyRightsCode( terms[ "combinations-allowed" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-allowed" ).style.display = "none" ;
					this.glossDivsNamed['gloss-combinations-allowed'].style.display = "none";
					this.modifyRightsCode( terms[ "combinations-sharealike" ].integer , "0" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-none" ).style.display = "none" ;
					this.glossDivsNamed['gloss-combinations-sharealike'].style.display = "none";
					this.modifyRightsCode( terms[ "combinations-none" ].integer , "1" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-allowed" ).style.display = "none" ;
					this.glossDivsNamed['gloss-combinations-none'].style.display = "block";
					this.modifyRightsCode( terms[ "transformations-none" ].integer , "1" ) ;
					//gEBI(this.licenseDiv,  "gloss-transformations-none" ).style.display = "none" ;
					this.glossDivsNamed['gloss-transformations-none'].style.display = "block";					
					break ;
			}
			// Reset all license glosses in preparation.
			for (var glossCounter=0; glossCounter < licenses.length; glossCounter++) {
				//gEBI(this.licenseDiv,  "gloss-" + licenses[glossCounter].id ).style.display = "none" ;
				this.glossDivs['gloss-' + licenses[glossCounter].id].style.display = "none";
			};
			// Compare selected terms to existing licenses, and select one if there is a match.
			var licenseMatches = false ;
			for (var licenseCounter=0; licenseCounter < licenses.length; licenseCounter++) {
				if ( licenses[licenseCounter].rightsCode == this.currentRightsCode ) {
					//gEBI(this.licenseDiv,  licenses[licenseCounter].id ).checked = true ;
					this.licenseInputsNamed[licenses[licenseCounter].id].checked = true;
					//gEBI(this.licenseDiv,  "gloss-" + licenses[licenseCounter].id ).style.display = "block" ;
					this.glossDivsNamed['gloss-' + licenses[licenseCounter].id].style.display = 'block';
					licenseMatches = true ;
				}
				else {
					//gEBI(this.licenseDiv,  licenses[licenseCounter].id ).checked = false ;
					this.licenseInputsNamed[licenses[licenseCounter].id].checked = false;
				}
			};
			if ( !licenseMatches ) {
				//gEBI(this.licenseDiv, "gloss-no-license").style.display = "block" ;
				this.glossDivsNamed['gloss-no-license'].style.display='block';
			}
			else {
				//gEBI(this.licenseDiv, "gloss-no-license").style.display = "none" ;
				this.glossDivsNamed['gloss-no-license'].style.display = 'none';
			}
		}
	}
	
	// Add event listeners to all checkboxes and radio buttons.
	for (var licenseCounter=0; licenseCounter < this.licenseInputs.length; licenseCounter++) {
		this.licenseInputs[licenseCounter].lm = this;
		this.licenseInputs[licenseCounter].onclick = function() { this.lm.setCorrelations("license", this.id) } ;
	};
	for (var termCounter=0; termCounter < this.inputTags.length; termCounter++) {
		this.inputTags[termCounter].lm = this;
		this.inputTags[termCounter].onclick = function() { this.lm.setCorrelations("term", this.id) } ;
	};
	// Set terms on load, if any have been stored in the database.
	if ( this.termsObj == "No terms passed" ) {
		// If no terms already chosen, set the default license.
		if (this.poolType == "reference") {
			//gEBI(this.licenseDiv, "all-rights-reserved").checked = true ;
			this.licenseInputsNamed['all-rights-reserved'].checked = true;
			this.setCorrelations("license", "all-rights-reserved") ;
		}
		else {
			//gEBI(this.licenseDiv, "open-art").checked = true ;
			this.licenseInputsNamed['open-art'].checked = true;
			this.setCorrelations("license", "open-art") ;
		}
	}
	else {
		// Need to initialize rightsCode if it's not created by a default license. (Choice of "public domain" is arbitrary.)
		//gEBI(this.licenseDiv, "public-domain").checked = true ;
		this.licenseInputsNamed['public-domain'].checked = true;
		this.setCorrelations("license", "public-domain") ;
		// Now begin reading data passed to LicenseManager.		
		this.customInput.value = this.termsObj["custom-rights"] ;
		for (prop in this.termsObj) { // Assumes only true properties are passed.
			if (prop != "custom-rights") {
				//gEBI(this.licenseDiv, prop).checked = true ;
				this.inputTagsNamed[prop].checked = true;
				this.setCorrelations("term", prop);
			}
		}
	}
}

function toggleDisplay( ele ) {
    var expandingContentDiv = ele.parentNode.getElementsByTagName('div')[0];
    if (expandingContentDiv.style.display=="block") { // Putting this option first prevents misfiring based on no display defined yet.
        expandingContentDiv.style.display="none";
		ele.innerHTML = "[Show terms]"
    }
    else {
        expandingContentDiv.style.display="block";
		ele.innerHTML = "[Hide terms]"
    }
}

//Setting up the terms array
terms = [] ; // An array of Term objects.

function Term( termArg ) {
	// Register information for this term.
	this.id = termArg ;
	// Create handles for future reference.
	terms.push(this) ;
	terms[termArg] = this ;
	terms[termArg].integer = terms.length - 1 ;
}

// Terms are instantiated in order of the interface, to make the rightsCodes more legible.
new Term("all-rights-reserved") ;
new Term("attribution") ;
new Term("noncommercial") ;
new Term("registration") ;
new Term("view-source") ;
new Term("combinations-allowed") ;
new Term("combinations-sharealike") ;
new Term("combinations-none") ;
new Term("transformations-allowed") ;
new Term("transformations-sharealike") ;
new Term("transformations-none") ;

// Register all licenses in a licenses array.
licenses = [] ;
function License( argObj ) {
	// Register information for this license.
	this.id = argObj.licenseId ;
	this.terms = argObj.terms ;
	// Create handles for future reference.
	licenses.push(this) ;
	licenses[argObj.licenseId] = this ;
	licenses[argObj.licenseId].integer = licenses.length - 1 ;
	
	
	// Create a terms code for future comparisons.
	this.rightsCode = generateRightsCode( this.terms ) ;
}
new License( {
	licenseId: "public-domain",
	terms: [
		"combinations-allowed",
		"transformations-allowed"
	]
} ) ;
new License( {
	licenseId: "all-rights-reserved",
	terms: [
		"all-rights-reserved",
		"combinations-none",
		"transformations-none"
	]
} ) ;
new License( {
	licenseId: "open-art",
	terms: [
		"attribution",
		"view-source",
		"noncommercial",
		"registration",
		"combinations-sharealike",
		"transformations-sharealike"
	]
} ) ;
new License( {
	licenseId: "gpl",
	terms: [
		"attribution",
		"view-source",
		"combinations-sharealike",
		"transformations-sharealike"
	]
} ) ;
new License( {
	licenseId: "lgpl",
	terms: [
		"attribution",
		"view-source",
		"combinations-allowed",
		"transformations-sharealike"
	]
} ) ;
new License( {
	licenseId: "ccby",
	terms: [
		"attribution",
		"combinations-allowed",
		"transformations-allowed"
	]
} ) ;
new License( {
	licenseId: "ccby-sa",
	terms: [
		"attribution",
		"combinations-sharealike",
		"transformations-sharealike"
	]
} ) ;
new License( {
	licenseId: "ccby-nc-nd",
	terms: [
		"attribution",
		"noncommercial",
		"combinations-none",
		"transformations-none"
	]
} ) ;
/* Wendy Seltzer says these are now deprecated:
new License( {
	licenseId: "ccsampling+",
	terms: [
		"attribution",
		"combinations-none",
		"transformations-allowed"
	]
} ) ;
new License( {
	licenseId: "ccnc-sampling+",
	terms: [
		"attribution",
		"combinations-none",
		"transformations-allowed",
		"noncommercial"
	]
} ) ;
*/
function gEBI(startNode, id){
    var nodeQueue = [];
    var childNodes = startNode.childNodes;
    for (var i = 0; i < childNodes.length; i++) {
        var node = childNodes[i];
        if (node.nodeType == 1) {
            nodeQueue[nodeQueue.length] = node;
        }
    }

    while (nodeQueue.length) {
        node = nodeQueue.shift();
        if (node.id == id) {
            return node;
        }
        childNodes = node.childNodes;
        for (i = 0; i < childNodes.length; i++) {
            node = childNodes[i];
            if (node.nodeType == 1) {
                nodeQueue[nodeQueue.length] = node;
            }
        }
    }
    return null;		
}
/* This seems to be breaking IE7 :( */
/**
Element.prototype.getElementById = function(id){
    var nodeQueue = [];
    var childNodes = this.childNodes;
    for (var i = 0; i < childNodes.length; i++) {
        var node = childNodes[i];
        if (node.nodeType == 1) {
            nodeQueue[nodeQueue.length] = node;
        }
    }

    while (nodeQueue.length) {
        node = nodeQueue.shift();
        if (node.id == id) {
            return node;
        }
        childNodes = node.childNodes;
        for (i = 0; i < childNodes.length; i++) {
            node = childNodes[i];
            if (node.nodeType == 1) {
                nodeQueue[nodeQueue.length] = node;
            }
        }
    }
    return null;	
} */
if (typeof Loader != "undefined") {
	Loader.registerFile('License.js');
}
