/**
 * A simple LOM object.
 *
 * Be aware this only is used for converting single loaded LOM XML into an object.
 * Multiple (e.g. search result lists) are created in PHP.
 *
 * @param {jQuery Object} xml The whole LOM XML as jQuery
 */
function LOM($lomXml){

	//console.log("new LOM", $lomXml);
	this.$xml = $lomXml;
	
	if ($lomXml.find("general").length > 1) {
		console.warn("Converting from LOM XML resulted in too many same elements.");
	}
	
	// The id of the LOM (i.e. the metaMetadata identifier)
	// Gets the only entry, or if multiple tries to find the oai one, or if not found, the first one.
	if ($lomXml.find("metaMetadata > identifier").length > 1) {
		// NB The contains-jQuery does work in IE only if patched jQuery! http://dev.jquery.com/ticket/1612
		//if ($lomXml.find("metaMetadata > identifier > catalog:contains('oai')").length > 0) {
		var $oaiCatalog = $lomXml.find("metaMetadata > identifier > catalog").filter(function(i){
			return $(this).text().startsWith("oai");
		});
		if ($oaiCatalog.length > 0) {
			this.id = $oaiCatalog.siblings("entry").text();
		}
		else {
			this.id = $lomXml.find("metaMetadata > identifier > entry:first").text()
		}
	}
	else {
		this.id = $lomXml.find("metaMetadata > identifier > entry").text();
	}
	
	// The title of the LO
	// try to find the English title
	this.title = $lomXml.find("general > title > string[language='en']").text();
	// else: pick the first one
	if (!this.title) {
		this.title = $lomXml.find("general > title > string:first").text();
	}
	
	this.shortTitle = LOM.createShortTitle(this.title);
	
	// The description of the LO
	// try to find the English description
	this.description = $lomXml.find("general > description > string[language='en']").text();
	// else: pick the first one
	if (!this.description) {
		this.description = $lomXml.find("general > description > string:first").text();
	}
	// Strips tags (as jQuery changes entity encoded angle brackets "&gt" in real ones "<" )
	this.description = this.description.replace(/<.*?>/g, "");
	
	// The original URL in repository (technical location)
	this.repositoryURL = $lomXml.find("technical > location").filter(function(index){
		return $(this).text().startsWith("http");
	}).text();
	this.url = this.repositoryURL;
	
	if (this.url == null || this.url == "") {
		this.url = this.repositoryURL = MACEConstants.detailsBaseSrc + this.id;
	}
	
	this.resourceTypes = [];
	var _this = this;
	$lomXml.find("educational > learningResourceType > value").each(function(){
		_this.resourceTypes.push($(this).text());
	});
	
	// NB: Because jQuery lacks correct namespace handling, weird construction
	this.resourceKind = null;
	var $lokValue = $lomXml.find("general mace\\:value");
	if ($lokValue.length > 0 && $lokValue.parent()[0].tagName == "mace:learningObjectKind") {
		this.resourceKind = $lokValue.text();
	}
	
	this.languageCode = $lomXml.find("general > language").text() || $lomXml.find("educational > language").text() || "en";
	this.language = LOM.languageMap[this.languageCode];
	if (Utils.isUndefined(this.language)) {
		this.language = this.languageCode;
	}
	
	// number of classification terms
	this.classificationNumber = $lomXml.find("classification > taxonPath").size();
	
	/*
	 dbpedia ID
	 */
	var _this = this;
	$lomXml.find("relation > resource > identifier").each(function(){
		if ($(this).find("catalog").text() == "dbpedia") {
			_this.dbpediaID = $(this).find("entry").text().split("dbpedia:http://dbpedia.org/resource/").join("");
			console.log("found dbpedia ID", _this.dbpediaID);
		}
	});
	
	/*
	 catalogID
	 */
	// Gets catalog from metaMetadata-ID
	this.catalog = this.id.substring(4, this.id.indexOf("."));
	
	var _this = this;
	$lomXml.find("metaMetadata > identifier > catalog").each(function(){
		var t = $(this).text();
		if (t != "oai") {
			_this.catalogID = t.toLowerCase().split("\n").join("").split("\r").join("").split(" ").join("");
		}
	});
	
	if (Utils.isUndefined(this.catalogID)) {
		this.catalogID = this.catalog;
	}
	this.catalog = LOM.guessCatalog(this.catalogID);
}

LOM.createShortTitle = function(title){
	var shortTitle = null;
	// An abbreviated title to fit better into small spaces
	if (title.length > LOM.shortTitleLength) {
		shortTitle = title.replace(new RegExp("^(.{0," + (LOM.shortTitleLength - 3) + "}\\b).*"), "$1...");
	}
	else {
		shortTitle = title;
	}
	return shortTitle;
}


LOM.shortTitleLength = 40;
LOM.languageMap = {
	"bg": "Bulgarian",
	"cs": "Czech",
	"da": "Danish",
	"nl": "Dutch",
	"en": "English",
	"et": "Estonian",
	"fi": "Finnish",
	"fr": "French",
	"de": "German",
	"el": "Greek",
	"hu": "Hungarian",
	"ga": "Irish",
	"it": "Italian",
	"lv": "Latvian",
	"lt": "Lithuanian",
	"mt": "Maltese",
	"pl": "Polish",
	"pt": "Portuguese",
	"ro": "Romanian",
	"sk": "Slovak",
	"sl": "Slovenian",
	"es": "Spanish",
	"sv": "Swedish",
	
	"hr": "Croatian",
	"li": "Limburgish",
	"ru": "Russian",
	"zh": "Chinese"
};

Catalog = function(name, URL, iconURL){
	this.name = name;
	this.URL = URL;
	this.iconURL = iconURL;
}

/**
 * Guesses a catalog based on the catalog name from the contentId.
 *
 * (See func_inc_global.php get_catalog_fromID() for same functionality)
 *
 * @param {Object} contentId
 */
LOM.guessCatalogFromId = function(contentId) {
	var key = "";
	var prefix = contentId.substring(0, contentId.indexOf(":"));
	var suffix = contentId.substring(contentId.indexOf(":") + 1, contentId.length);
	
	if (prefix == "oai") {
		// Gets first string after prefix
		// e.g. oai:dynamo.asro.kuleuven.be:1MD, oai:oaicat.iconda.org:2
		key = suffix.substring(0, suffix.indexOf("."));
	}
	else if (prefix == 'mace') {
		// Gets first string after prefix
		// e.g. mace:rwo:1MD, mace:external:2MD
		key = suffix.substring(0, suffix.indexOf(":"));
	}
	else {
		// Uses prefix
		// e.g. dbpedia:162419b3-3e1a-11de
		key = prefix;
	}
	
	var catalog = LOM.guessCatalog(key);
	if (catalog.URL == "") {
		console.log("\tcontentId=" + contentId + ", suffix=" + suffix);
	}
	return catalog;
}

/**
 * Tries to create a catalog based on a key string.
 * Key is either from LOM.catalog, or from the beginning of the ID.
 */
LOM.guessCatalog = function(key){
	var catalog = new Catalog();
	
	if (!Utils.isUndefined(key) && key != null) 
		key = key.toLowerCase();
	
	/*
    * Arch'it (it)
      digital architecture magazine
    * Archiplanet (en)
      Wiki for architecture
    * architonic (en de it fr es)
      Products, Materials and Concepts in Architecture and Design
    * ARIADNE (en)
      Literature and documents
    * CUMINCAD (en)
      articles, in full or as references, from all major CAAD conferences worldwide
    * DYNAMO (en)
      DYNAmic Memory Online - case base containing more than 1000 reviewed architectural projects
    * ICONDA (en)
      The International CONstruction DAtabase
    * WINDS (en de)
      Web-based INtelligent Design tutoring System - architectural and construction course material
	*/
	
	switch (key) {
		case "dynamo":
			catalog.name = "DYNAMO";
			catalog.URL = "http://dynamo.asro.kuleuven.be";
			catalog.iconURL = MACEConstants.rootURL + "img/repositories/dynamo.gif";
			catalog.description = "DYNAmic Memory Online: more than 1000 reviewed architectural cases";
			break;
			
		case "winds":
			catalog.name = "WINDS";
			catalog.URL = "http://raft-app.fit.fraunhofer.de/cgi-bin/WebObjects/ale-ng";
			catalog.iconURL = MACEConstants.rootURL + "img/repositories/winds.gif";
			catalog.description = "Web-based INtelligent Design tutoring System: architectural and construction course material";
			break;
			
		case "deirb":
		case "iconda":
		case "oaicat":
			catalog.name = "ICONDA";
			catalog.URL = "http://www.irbdirekt.de/iconda/ppv.htm";
			catalog.iconURL = MACEConstants.rootURL + "img/repositories/iconda.gif";
			catalog.description = "The International CONstruction DAtabase";
			break;
			
		case "mace:rwo":
		case "dbpedia":
		case "rwo":
			catalog.name = "dbpedia";
			catalog.URL = "http://dbpedia.org";
			catalog.iconURL = MACEConstants.rootURL + "img/repositories/rwo.gif";
			catalog.description = "Extracted structured information from Wikipedia by the community";
			break;
			
		case "mace:external":
		case ":external:www":
		case "external:www":
		case "external":
			catalog.name = "web";
			catalog.URL = "";
			catalog.iconURL = MACEConstants.rootURL + "img/repositories/external.gif";
			catalog.description = "External web pages";
			break;
			
		case "cumincad":			
		case "cumincad:works":
		case "cumincad : works":
			catalog.name = "CUMINCAD";
			catalog.URL = "http://cumincad.scix.net/cgi-bin/works/Home";
			catalog.iconURL = MACEConstants.rootURL + "img/repositories/cumincad.gif";
			catalog.description = "References and full articles from all major CAAD conferences worldwide";
			break;
		
		case "archiplanet":	
		case "archiplanet.org":
			catalog.name = "archiplanet";
			catalog.URL = "http://www.archiplanet.org/wiki/Main_Page";
			// TODO: create thumbnail
			catalog.iconURL = MACEConstants.rootURL + "img/repositories/archiplanet.gif";
			catalog.description = "Wiki for architecture";
			break;
			
		case "www.nextroom.at":
			catalog.name = "nextroom";
			catalog.URL = "http://www.nextroom.at";
			// TODO: create thumbnail
			catalog.iconURL = MACEConstants.rootURL + "img/repositories/nextroom.gif";
			catalog.description = "European architecture webzine";
			break;

		case "arch'it":			
		case "www.architettura.supereva.com":
			catalog.name = "arch'it";
			catalog.URL = "http://architettura.it";
			// TODO: create thumbnail
			catalog.description = "Digital architecture magazine";
			catalog.iconURL = MACEConstants.rootURL + "img/repositories/archit.gif";
			break;
			
		case "columbus":
		case "columbus-portal.eu":
			catalog.name = "Columbus";
			catalog.URL = "http://www.columbus-portal.eu/";
			// TODO: create thumbnail
			catalog.description = "Innovative eLearning marketplace";
			catalog.iconURL = MACEConstants.rootURL + "img/repositories/columbus.gif";
			break;
			
		case "architonic.com":
		case "www.architonic.com":
			catalog.name = "Architonic";
			catalog.URL = "http://www.architonic.com/";
			// TODO: create thumbnail
			catalog.description = "Products, Materials and Concepts in Architecture and Design";
			catalog.iconURL = MACEConstants.rootURL + "img/repositories/architonic.gif";
			break;	
			
		case "architecture.it":
			catalog.name = "Architecture.it";
			catalog.URL = "http://www.architecture.it/";
			catalog.description = "Italian architectural portal";
			break;
		
		case "mimoa.eu":
			catalog.name = "MIMOA";
			catalog.URL = "http://mimoa.eu/";
			catalog.description = "mi modern architecture - a free user generated Modern Architecture guide with addresses and maps";
			break;
		
		case "copyrightbookshop.be":
			catalog.name = "copyrightbookshop";
			catalog.URL = "http://www.copyrightbookshop.be";
			catalog.description = "Art and Architecture Bookshop";
			break;
		
		case "whc.unesco.org":
			catalog.name = "UNESCO World Heritage List of Sites";
			catalog.URL = "http://whc.unesco.org/";
			catalog.description = "UNESCO List of heritage sites";
			break;
		
		case "cad-3d.blogspot.com":
			catalog.name = "CAD-3D";
			catalog.URL = "http://cad-3d.blogspot.com/";
			catalog.description = "Blog on CAD, CAAD and 3D tools for use in architecture";
			break;
		
		case "caadasro":
			catalog.name = "CAAD@ASRO";
			catalog.URL = "http://caad.asro.kuleuven.be";
			catalog.description = "CAAD Tutorials for students of Architecture";
			break;
		
		case "macerepodb":
			catalog.name = "ASRO MACE repo DB";
			catalog.URL = "http://caad.asro.kuleuven.be/MACEREPODB/";
			catalog.description = "Database of architectural repositories";
			break;
		
		case "baufo.irbdirekt.de":
			catalog.name = "BAUFO";
			catalog.URL = "http://www.irbdirekt.de/baufo/";
			catalog.description = "Descriptions of building research projects";
			break;
		
		case "retro.seals.ch":
			catalog.name = "Baugedächtnis Schweiz Online";
			catalog.URL = "http://retro.seals.ch/";
			catalog.description = "Digitized journals 'Memory of Swiss construction'";
			break;
		
		case "archdaily.com":
			catalog.name = "Arch Daily";
			catalog.URL = "http://www.archdaily.com";
			catalog.description = "aily blog with project reviews";
			break;	
			
		default:
			console.warn("unrecognized catalog", key);
			catalog.name = key;
			catalog.URL = "";
			catalog.iconURL = "";
	}
	
	return catalog;
}


