// Entango Utility Custom Duplicate Checker
/*jslint browser: true */ /*global window */
if(window.Ent_Utility === undefined){var Ent_Utility = {};Ent_Utility.entango = true;}
if((typeof Ent_Utility === "object") && (Ent_Utility !== null) && (Ent_Utility.entango === true)){
	if(!Ent_Utility.customDuplicateChecker){
		Ent_Utility.customDuplicateChecker = {};
		// After Douglas Crockford, "JavaScript: The Good Parts"
		Ent_Utility.customDuplicateChecker.walkThePage = function walk(node,func){
			func(node);
			node = node.firstChild;
			while(node){
				walk(node,func);
				node = node.nextSibling;
			}
		};
		Ent_Utility.customDuplicateChecker.searchById = function(){
			var found = {};
			Ent_Utility.customDuplicateChecker.walkThePage(document.body, function(node){
				var id = (node.nodeType === 1) && node.getAttribute("id");
				if((typeof id === "string") && (id.indexOf("clientField.") === 0)){
					if(id.length > 12){id = id.substring(12);}
					else{id = "";}
					if(!found[id]){found[id] = [];}
					found[id][found[id].length] = node.type;
				}
			});
			return found;
		};
		Ent_Utility.customDuplicateChecker.searchByName = function(){
			var found = {};
			Ent_Utility.customDuplicateChecker.walkThePage(document.body, function(node){
				var name = (node.nodeType === 1) && node.getAttribute("name");
				if((typeof name === "string") && (name.indexOf("clientField.") === 0)){
					if(name.length > 12){name = name.substring(12);}
					else{name = "";}
					if(!found[name]){found[name] = [];}
					found[name][found[name].length] = node.type;
				}
			});
			return found;
		};
		Ent_Utility.customDuplicateChecker.search = function(){
			var alertMsg = "";
			var alertStart = "Warning! Duplicate custom fields found in page.\n\n";
			var idMsg = "";
			var ids = Ent_Utility.customDuplicateChecker.searchById();
			for(var id in ids){if(ids.hasOwnProperty(id) && (ids[id].length > 1)){idMsg += "(" + ids[id].length + ") " + id + "\n";}}
			if(idMsg.length > 0){alertMsg += alertStart + "Duplicate client field ids:\n" + idMsg;}
			var nameMsg = "";
			var names = Ent_Utility.customDuplicateChecker.searchByName();
			for(var name in names){
				if(names.hasOwnProperty(name) && (names[name].length > 1)){
					for(var index = 0; index < names[name].length; index++){
						if(names[name][index] !== "radio"){
							nameMsg += "(" + names[name] + ") " + name + "\n";
							break;
						}
					}
				}
			}
			if(nameMsg.length > 0){alertMsg += (alertMsg.length === 0 ? alertStart : "\n") + "Duplicate client field names:\n" + nameMsg;}
			if(alertMsg.length > 0){alert(alertMsg);}
		};
	}
}
else{alert("Ent_Utility already defined outside Entango code.");}
