var baseURL = null;
var fromTemplate = true;

// overwrite onload method/event
//onload = init;

function init() {
	var s = window.location.href;
	var idx = s.lastIndexOf( "/" );
	baseURL = s.substring( 0, idx+1 ) + "control?";
	loadKeywords();
	loadDataseries();
	loadSpatialExtents();
	loadResponsibleParties();
	new Accordian( 'main_content',1 , 'header_highlight' );
}

/**
* sets the current date to three fields (YYYY-MM-DD) representing a date. The fields are identified
* by 
* $fieldBasename$YYYY 
* $fieldBasename$MM
* $fieldBasename$DD
*/
function setCurrentDate( fieldBasename ) {
	var date = new Date();	
	var year = getElement( fieldBasename + "YYYY" );
	year.value = date.getFullYear();	
	var month = getElement( fieldBasename + "MM" );
	var tmp = "" + (date.getMonth() + 1);
	if ( (date.getMonth() + 1) < 10 ) {
		tmp = "0" + (date.getMonth() + 1);	
	}
	month.value = tmp;
	var day = getElement( fieldBasename + "DD" );
	tmp = "" + date.getDate();
	if ( date.getDate() < 10 ) {
		tmp = "0" + date.getDate();	
	}
	day.value = tmp;	
}

/**
* reads list of available metadata sets
*/
function loadMetadataList(loadTemplate) {
	fromTemplate = loadTemplate;
	if ( loadTemplate ) {
		t = "Metadatensatz als Vorlage ausw&auml;hlen:";
	} else {
		t = "Metadatensatz zum Bearbeiten ausw&auml;hlen:";
	}
	submitGetRequest( baseURL + "action=getMetadataList", 
	
		function(result) {
			openDialog( result, t );
		}, 
		
		null, true );
}

/**
* reads list of available templates
*/
function loadTemplateList() {	
    var t = "Vorlage zum Bearbeiten ausw&auml;hlen:";
	
	submitGetRequest( baseURL + "action=getTemplateList", 
	
		function(result) {
			openDialog( result, t );
		}, 
		
		null, true );
}

/**
 * loads a metadata set from a CSW
 * @return
 */
function loadMetadata() {
	var select = getElement( "metadataList" );
	var fileId = select.options[select.options.selectedIndex].value;
	loadMetadatasetByFileId( fileId );
	var dialog = getElement( "dialog" );
	closeDialog();
}

function loadMetadatasetByFileId(fileId) {
	submitGetRequest( baseURL + "action=loadMetadataSet&id=" + fileId + "&istemplate=" + fromTemplate, 
			
			function(result) {
				setFormValues( JSON.parse( result, null ), fromTemplate );
			}, 
			
			null, true );	
}

/**
 * loads a metadata set from a CSW
 * @return
 */
function loadTemplate() {
	var select = getElement( "templateList" );
	var file = select.options[select.options.selectedIndex].value;
	submitGetRequest( baseURL + "action=loadTemplate&file=" + file, 
	
		function(result) {
			setFormValues( JSON.parse( result, null ), true );
		}, 
		
		null, true );

	var dialog = getElement( "dialog" );
	closeDialog();
}

/**
 * 
 * opens a dialog window that enables uploading a metadata set for editing
 */
function openUploadDialog() {
	var win = window.open('md_upload.jsp','upload', 'width=550,height=200,top=100,resizable=yes');
	win.focus();
}

/**
 * stores a metadata set within a CSW
 * @return
 */
function saveMetadataSet() {
	if ( fromTemplate ) {
		insertMetadataFromFields();
	} else {
		updateMetadataSet();
	}
}

/**
* creates/writes an new metadataset into the CSW
*/
function insertMetadataFromFields() {
	
	if ( !validateMD() ) {
		return;
	}
		
	var bean = createMetadataBean();
	bean.className = "insertMetadata";
	
	submitPostRequest( baseURL, 

		function(result) {
			if ( result.indexOf( ".ExceptionBean" ) > -1 ) {
				openException( JSON.parse( result ).message, 'Metadaten speichern' );
			} else {
				var s = 'Metadatensatz: ' + getInputValue( 'datasetTitle' ) + ' erfolgreich gespeichert.';
				openInformation( s, 'Metadaten speichern' );
				loadDataseries();
			}
		},
		
		JSON.stringify( bean ), null, true );
}

function createMetadataBean() {
	var bean = new MetadataBean();	
	bean.hlevel = getSelectedValue( 'hlevel' );
	bean.parentId = getSelectedValue( 'parentId');
	if (bean.parentId == "_none_"  ) {
		bean.parentId = null;
	}
	bean.contactRole = getSelectedValue( 'contactRole'); 
	bean.topCat = getSelectedValue( 'topCat' );	
	bean.pocRole = getSelectedValue( 'pocRole' );
	bean.contactIndividualName = getInputValue( 'contactIndividualName' ) ;
	bean.contactOrganisationName = getInputValue( 'contactOrganisationName' );
	bean.contactDeliveryPoint = getInputValue( 'contactDeliveryPoint' );
	bean.contactCity = getInputValue( 'contactCity' ) ;
	bean.contactPostalCode = getInputValue( 'contactPostalCode' ) ;
	bean.contactCountry = getInputValue( 'contactCountry' );
	bean.contactVoice = getInputValue( 'contactVoice' );
	bean.contactEmailAddress = getInputValue( 'contactEmailAddress' );
	bean.contactFacsimile = getInputValue( 'contactFacsimile' );
	bean.geogrDescription = getSelectedValue( 'geogrDescription' );	
	bean.crs = getSelectedValue( 'CRS' );
	bean.scale = getInputValue( 'scale' );	
	bean.datasetTitle = getInputValue( 'datasetTitle' );
	bean.abstract_ = getInputValue( 'abstract' );	
	bean.keywords = getAllValues( 'keywords' );
	bean.inspireDataTheme = getSelectedValue( 'inspireDataTheme' );
	bean.identifier = getInputValue( 'datasetId' );
	var tmp0 = getInputValue( 'creationYYYY' );
	if ( tmp0 != null && tmp0 != '' ) {
		var tmp1 = getDateValue( getInputValue( 'creationMM' ) );
		var tmp2 = getDateValue( getInputValue( 'creationDD' ) );
		bean.creation = tmp0 + '-' + tmp1 + '-' + tmp2;
	}
	tmp0 = getInputValue( 'publicationYYYY'  );
	if ( tmp0 != null && tmp0 != '' ) {
		var tmp1 = getDateValue( getInputValue( 'publicationMM' ) );
		var tmp2 = getDateValue( getInputValue( 'publicationDD' ) );
		bean.publication = tmp0 + '-' + tmp1 + '-' + tmp2;
	}
	tmp0 = getInputValue( 'revisionYYYY' );
	if ( tmp0 != null && tmp0 != '') {	
		var tmp1 = getDateValue( getInputValue( 'revisionMM' ) );
		var tmp2 = getDateValue( getInputValue( 'revisionDD' ) )
		bean.revision = tmp0 + '-' + tmp1 + '-' + tmp2;		
	}
	tmp0 = getInputValue( 'beginYYYY' );
	if ( tmp0 != null && tmp0 != '') {	
		var tmp1 = getDateValue( getInputValue( 'beginMM' ) );
		var tmp2 = getDateValue( getInputValue( 'beginDD' ) )
		bean.begin = tmp0 + '-' + tmp1 + '-' + tmp2;
	}
	tmp0 = getInputValue( 'endYYYY' );
	if ( tmp0 != null ) {	
		var tmp1 = getDateValue( getInputValue( 'endMM' ) );
		var tmp2 = getDateValue( getInputValue( 'endDD' ) )
		bean.end = tmp0 + '-' + tmp1 + '-' + tmp2;
	}
	bean.pocIndividualName = getInputValue( 'pocIndividualName' );
	bean.pocOrganisationName = getInputValue( 'pocOrganisationName' );
	bean.pocDeliveryPoint = getInputValue( 'pocDeliveryPoint' );
	bean.pocCity = getInputValue( 'pocCity' );
	bean.pocPostalCode = getInputValue( 'pocPostalCode' );
	bean.pocCountry = getInputValue( 'pocCountry' );
	bean.pocVoice = getInputValue( 'pocVoice' );
	bean.pocEmailAddress = getInputValue( 'pocEmailAddress' );
	bean.pocFacsimile = getInputValue( 'pocFacsimile' );
	bean.lineage = getInputValue( 'lineage' );
	bean.transferOnline = getInputValue( 'transferOptOnline' );
	bean.transferFormatName = getSelectedValue( 'transferOptFormatName' );
	tmp0 = getSelectedValue( 'accessConstraints' );
	if ( tmp0 == 'none' ) {
		bean.accessConstraints = null;
	} else {
		bean.accessConstraints = tmp0;
	}
	return bean;
}


function getDateValue(value) {
	if ( value == null || value == '' || value == 'undefined' || value == 'null' ) {
		value = '01';
	} else {
		return value;
	}
}

/**
* updates an already existing metadataset within the CSW
*/
function updateMetadataSet() {
	if ( !validateMD() ) {
		return;
	}
		
	var bean = createMetadataBean();
	bean.className = "updateMetadata";
	
	submitPostRequest( baseURL, 

		function(result) {
			if ( result.indexOf( ".ExceptionBean" ) > -1 ) {
				openException( JSON.parse( result ).message, 'Metadaten aktualisieren' );
			} else {
				var s = 'Metadatensatz: ' + getInputValue( 'datasetTitle' ) + ' erfolgreich aktualisiert.';
				openInformation( s, 'Metadaten aktualisieren' );
				loadDataseries();
			}
		},
		
		JSON.stringify( bean ), null, true );
}

/**
 * deletes a metadata set from a CSW
 * @return
 */
function deleteMetadataSet(){
	openConfirm("M&ouml;chten Sie den Datensatz mit dem Titel " + getInputValue( 'datasetTitle' ) + " wirklich l&ouml;schen?", "L&ouml;schen best&auml;tigen", "deleteMetadataSetHandler()" );
}

/**
 * will be invoked after a metadata set has been deleted
 * @return
 */
function deleteMetadataSetHandler() {
	var id = getInputValue( 'datasetId' );
	submitGetRequest( baseURL + "action=deleteMetadata&id=" + id, 
	
		function(result) {
			if ( result.indexOf( ".ExceptionBean" ) > -1 ) {
				openException( JSON.parse( result ).message, 'Metadaten l&ouml;schen' );
			} else {
				var s = 'Metadatensatz: ' + getInputValue( 'datasetTitle' ) + ' erfolgreich gel&ouml;scht.';
				openInformation( s, 'Metadaten l&ouml;schen' );
				clearForm();
				loadDataseries();
			}
		}, 
		
		null, true );
}

/**
* loads available keywords. This method will be invoked when loading the editor page
*/
function loadKeywords() {

	submitGetRequest( baseURL + "action=getKeywords", 
	
		function(result) {
			// inline function definition
			var keywords = JSON.parse( result, null );
		
			var select = getElement("keywordsBase");
			//remove all entries
			select.innerHTML = "";
			for ( var i = 0; i < keywords.length; i++) {
				appendOption( select, keywords[i], keywords[i] );			
			}
		}, 
		
		null, true );
}

function loadResponsibleParties() {

	submitGetRequest( baseURL + "action=getResponsibleParties", 
	
		function(result) {
			// inline function definition
			var respParties = JSON.parse( result, null );		
			var select = getElement( "contactRespParties" );
			var select2 = getElement( "pocRespParties" );
			//remove all entries
			select.innerHTML = "";
			select2.innerHTML = "";
			appendOption( select, '----------------', '----------------' );
			appendOption( select2, '----------------', '----------------' );
			for ( var i = 0; i < respParties.length; i++ ) {
				appendOption( select, respParties[i].displayName, respParties[i].displayName );
				appendOption( select2, respParties[i].displayName, respParties[i].displayName );
			}
		}, 
		
		null, true );
}

function setResponsibleParty(select) {
	var val = getSelectedValue( select.id );
	if ( val != '----------------' ) {
		var pre = 'contact';
		if ( select.id.indexOf( 'poc' ) == 0 ) {
			pre = 'poc';
		}
		submitGetRequest( baseURL + "action=getResponsibleParties", 
				
				function(result) {
					// inline function definition
					var respParties = JSON.parse( result, null );		
					for ( var i = 0; i < respParties.length; i++ ) {
						if ( respParties[i].displayName == val ) {
							setInputValue( pre + 'IndividualName', respParties[i].individualName );
							setInputValue( pre + 'OrganisationName', respParties[i].organisationName );
							setSelectedValue( pre + 'Role', respParties[i].role );
							setInputValue( pre + 'DeliveryPoint', respParties[i].street );
							setInputValue( pre + 'City', respParties[i].city );
							setInputValue( pre + 'PostalCode', respParties[i].postalCode );
							setInputValue( pre + 'Country', respParties[i].country );
							setInputValue( pre + 'Voice', respParties[i].voice );
							setInputValue( pre + 'Facsimile', respParties[i].facsimile );
							setInputValue( pre + 'EmailAddress', respParties[i].email );
						}
					}
				}, 
				
				null, true );
	}
}

function takeKeywords() {
	var kws = getSelectedValues( "keywordsBase" );
	var select = getElement( "keywords" );
	for ( var i = 0; i < kws.length; i++ ) {
		appendOption( select, kws[i], kws[i] );
	}
}

function removeKeywords() {
	var kws = getSelectedValues( "keywords" );
	var select = getElement( "keywords" );
	var ar = new Array();
	for ( var i = 0; i < select.options.length; i++) {
		if ( select.options[i].selected ){
			ar.push( select.options[i] );
		}
	}
	for ( var i = 0; i < ar.length; i++) {
		removeElement( ar[i] );
	}
	
}

/**
* loads available keywords. This method will be invoked when loading the editor page
*/
function loadSpatialExtents() {

	submitGetRequest( baseURL + "action=getSpatialExtents", 
	
		function(result) {
			// inline function definition
			var spatialExtents = JSON.parse( result, null );
			
			var select = getElement( "geogrDescription" );
			//remove all entries
			select.innerHTML = "";
			for ( var i = 0; i < spatialExtents.length; i++) {
				appendOption( select, spatialExtents[i]['name'], spatialExtents[i]['id'] );				
			}
		}, 
		
		null, true );
}

/**
* loads available dataseries that may be parents for new metadata sets. This method 
* will be invoked when loading the editor page
*/
function loadDataseries() {

	submitGetRequest( baseURL + "action=getParents", 
	
		function(result) {
			// inline function definition
			var parents = JSON.parse( result, null );
			var select = getElement( "parentId" );
			//remove all entries
			select.innerHTML = "";
			appendOption( select, "kein Elternobjekt augew\u00E4hlt", "_none_" );
			for ( var i = 0; i < parents.length; i++) {
				var idx = parents[i].indexOf(";");
				appendOption( select, parents[i].substring( idx+1, parents[i].length ), parents[i].substring( 0, idx ) );
			}
		}, 
		
		null, true );
}

/**
* clears metadata form
*/
function clearForm() {
	fromTemplate = true;
	submitGetRequest( baseURL + "action=clearForm", 
	
		function(result) {
			setFormValues( JSON.parse( result, null ) );
		}, 
		
		null, true );
}

function setFormValues(metadata, createId) {
	setSelectedValue( 'hlevel', metadata.hlevel );
	setSelectedValue( 'parentId', metadata.parentId );
	setInputValue( 'contactIndividualName', metadata.contactIndividualName );
	setInputValue( 'contactOrganisationName', metadata.contactOrganisationName );
	setSelectedValue( 'contactRole', metadata.contactRole );
	setInputValue( 'contactDeliveryPoint', metadata.contactDeliveryPoint );
	setInputValue( 'contactCity', metadata.contactCity );
	setInputValue( 'contactPostalCode', metadata.contactPostalCode );
	setInputValue( 'contactCountry', metadata.contactCountry );
	setInputValue( 'contactVoice', metadata.contactVoice );
	setInputValue( 'contactFacsimile', metadata.contactFacsimile );
	setInputValue( 'contactEmailAddress', metadata.contactEmailAddress );

	setInputValue( 'datasetTitle', metadata.datasetTitle );
	setInputValue( 'abstract', metadata.abstract_ );
	setSelectedValue( 'topCat', metadata.topCat );
	
	clearSelect( 'keywords' );
	if ( metadata.keywords != null ) {
		var sel = getElement( 'keywords' );
		for ( var i = 0; i < metadata.keywords.length; i++ ) {
			appendOption( sel, metadata.keywords[i], metadata.keywords[i] );
		}
	}
	
	setInputValue( 'datasetId', metadata.identifier );
	if ( createId != null && createId ) {
		createIdentifier();
	}
	setSelectedValue( 'geogrDescription', metadata.geogrDescription );
	if ( metadata.crs != null ) {
		setSelectedValue( 'CRS', metadata.crs );
	}
	if ( metadata.scale != null ) {
		setInputValue( 'scale', metadata.scale );
	}

	if ( metadata.creation != null && metadata.creation != '' ) {
		var tmp = validateDateForISO( metadata.creation );
		setInputValue( 'creationYYYY', tmp[0] );
		setInputValue( 'creationMM', tmp[1] );
		setInputValue( 'creationDD', tmp[2] );
	} else {
		setInputValue( 'creationYYYY', '' );
		setInputValue( 'creationMM', '' );
		setInputValue( 'creationDD', '' );
	}
	if ( metadata.publication != null && metadata.publication != '' ) {
		var tmp = validateDateForISO( metadata.publication );
		setInputValue( 'publicationYYYY', tmp[0] );
		setInputValue( 'publicationMM', tmp[1] );
		setInputValue( 'publicationDD', tmp[2] );
	} else {
		setInputValue( 'publicationYYYY', '' );
		setInputValue( 'publicationMM', '' );
		setInputValue( 'publicationDD', '' );
	}
	if ( metadata.revision != null && metadata.revision != '' ) {
		var tmp = validateDateForISO( metadata.revision );
		setInputValue( 'revisionYYYY', tmp[0] );
		setInputValue( 'revisionMM', tmp[1] );
		setInputValue( 'revisionDD', tmp[2] );
	} else {
		setInputValue( 'revisionYYYY', '' );
		setInputValue( 'revisionMM', '' );
		setInputValue( 'revisionDD', '' );
	}
	if ( metadata.begin != null && metadata.begin != '' ) {
		var tmp = validateDateForISO( metadata.begin );
		setInputValue( 'beginYYYY', tmp[0] );
		setInputValue( 'beginMM', tmp[1] );
		setInputValue( 'beginDD', tmp[2] );
	}
	if ( metadata.end != null && metadata.end != '' ) {
		var tmp = validateDateForISO( metadata.end );
		setInputValue( 'endYYYY', tmp[0] );
		setInputValue( 'endMM', tmp[1] );
		setInputValue( 'endDD', tmp[2] );
	}
	setInputValue( 'pocIndividualName', metadata.pocIndividualName );
	setInputValue( 'pocOrganisationName', metadata.pocOrganisationName );
	setSelectedValue( 'pocRole', metadata.pocRole );
	setInputValue( 'pocDeliveryPoint', metadata.pocDeliveryPoint );
	setInputValue( 'pocCity', metadata.pocCity );
	setInputValue( 'pocPostalCode', metadata.pocPostalCode );
	setInputValue( 'pocCountry', metadata.pocCountry );
	setInputValue( 'pocVoice', metadata.pocVoice );
	setInputValue( 'pocFacsimile', metadata.pocFacsimile );	
	setInputValue( 'pocEmailAddress', metadata.pocEmailAddress );	
	setInputValue( 'lineage', metadata.lineage );
	setInputValue( 'transferOptOnline', metadata.transferOnline );	
	if ( metadata.transferFormatName != null ) {
		setSelectedValue( 'transferOptFormatName', metadata.transferFormatName );
	}
	if ( metadata.accessConstraints != null ) {
		setSelectedValue( 'accessConstraints', metadata.accessConstraints );
	}
}

function validateDateForISO(date) {
	var tmp = date.split( '-' );
	if ( tmp[1].length < 2 ) { 
		tmp[1] = '0' + tmp[1];
	}
	if ( tmp[2].length < 2 ) { 
		tmp[2] = '0' + tmp[2];
	}
	return tmp;
}

function selectMetadataSet( select ) {
    var p = getElement( "DESC" );
    p.innerHTML = select.options[select.options.selectedIndex].title;
}

function openHelp(element) {
	submitGetRequest( baseURL + "action=getHelp&language=de&element=" + element, 
	
		function(result) {
			// inline function definition
			openDialog( result, "Hilfe" );
		}, 
		
		null, true );
}

function createIdentifier() {
	var id = new UUID();
	setInputValue( 'datasetId', id );
}