var portalContext;
var portalRemoting = Seam.Component.getInstance("portalRemoting");

function setPortalContext() {
	portalRemoting.getPortalContext(setPortalContextCallback);
}

function setPortalContextCallback(result) {
	portalContext = result;
}



//The function getObjNN4(obj,name) returns the object for "name". It starts the search in "obj"
//This function is needed to find nested elements in a page.
function getObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == name)
			foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}    

//The function returns the style object
function getStyleObject(objectId) {
	if(document.getElementById && document.getElementById(objectId)) {
		return document.getElementById(objectId).style;
	} else if (document.all && document.all(objectId)) {
		return document.all(objectId).style;
	} else if (document.layers && document.layers[objectId]) {
		return getObjNN4(document,objectId);
	} else {
		return false;
	}
} 

//The function hides or shows a page element.
//show an element
//changeObjectVisibility('myObjectId', 'block');
//hide an element
//changeObjectVisibility('myObjectId', 'none');
function changeObjectVisibility(objectId, newVisibility) {
	var styleObject = getStyleObject(objectId, document);
	if(styleObject) {
		styleObject.display = newVisibility;
		return true;
	} 
	else {
		return false;
	}
}

function validateTextSearched(textSearched) {

	//Trim value
	textSearched = textSearched.replace(/^\s*/, "").replace(/\s*$/, "");

	//Check if length is less than 3 characters if there is a value
	//Must escape less than
	if (textSearched.length < 3){
		alert('Η λέξη αναζήτησης πρέπει να έχει τουλάχιστον 3 χαρακτήρες');
		return false;
	}

	//Search for invalid characters
	if (textSearched.indexOf('[') != -1 ||
			textSearched.indexOf(']') != -1 ||
			textSearched.indexOf('\\') != -1 ||
			textSearched.indexOf('/') != -1 ||
			textSearched.indexOf('^') != -1 ||
			textSearched.indexOf('$') != -1 ||
			textSearched.indexOf('.') != -1 ||
			textSearched.indexOf('|') != -1 ||
			textSearched.indexOf('?') != -1 ||
			textSearched.indexOf('*') != -1 ||
			textSearched.indexOf('+') != -1 ||
			textSearched.indexOf(')') != -1 ||
			textSearched.indexOf('(') != -1 ||
			textSearched.indexOf('{') != -1 ||
			textSearched.indexOf('}') != -1 ||
			textSearched.indexOf('&amp;') != -1) {
		alert('Η λέξη αναζήτησης περιέχει μη επιτρεπτούς χαρακτήρες:[,],{,},\\,/,^,$,.,|,?,*,+,(,),&amp;');
		return false;
	}

	return true;
}


function submitTextSearch(){

	var textSearchElement = document.getElementById('pageForm:search-box');

	if (textSearchElement != null){
		var textSearched=textSearchElement.value;

		if (textSearched != null) {
			//Trim value
			textSearched = textSearched.replace(/^\s*/, "").replace(/\s*$/, "");

			if (textSearched.length == 0){
				location.href = portalContext+ '/advancedSearch';
			}
			else{
				if (validateTextSearched(textSearched)) {					
					textSearched = Url.encode(textSearched);
					
					location.href='portal'+'/resource/contentObject/contentTypes/basicText,audio,video,event,timeLineEvent,binaryFile,incomeDeclaration,location,organization,person,photo,url/textSearched/'+textSearched+'/pageNumber/'+1+'/t/search';
				}
				else {
					alert('Η λέξη αναζήτησης πρέπει να έχει τουλάχιστον 3 χαρακτήρες');
				}
			}
		}
		else {
			location.href = portalContext+'/advancedSearch';
		}
	}
	else {
		location.href = portalContext+'/advancedSearch';
	}
}


function loadResourceListPage(resourceRequestURL, pageNumber) {
	resourceRequestURL = resourceRequestURL.replace(/pageNumber\/[0-9]+/, "pageNumber/" + pageNumber);
	location.href=portalContext + resourceRequestURL;
	return true;
}

function submitTextSearchOnEnterKey(e) {
	var evt=(e)?e:(window.event)?window.event:null;
	if(evt){
		var key=(evt.charCode)?evt.charCode:((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
		// alert("key pressed" + key);
		if(key==13){
			submitTextSearch();
		}	

	}
}

function callFunctionOnEnterKey(e, func, arg) {
	var evt=(e)?e:(window.event)?window.event:null;
 	if(evt){
        var key=(evt.charCode)?evt.charCode:((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
       // alert("key pressed" + key);
        if(key==13){
        return func(arg);
		}	
	
    }
}

function generateTextSearchURL(){
	var textSearched=document.getElementById('pageForm:search-box').value;

	if (textSearched != null) {
		if (validateTextSearched(textSearched)) {					
			textSearched = Url.encode(textSearched);

			var textSearchURL = portalContext +'/resource/contentObject/contentTypes/basicText,audio,video,binaryFile,person,photo,timeLineEvent,url,event,portalSectionObject/textSearched/'+textSearched+'/pageNumber/'+1+'/t/search';
			return textSearchURL;
		}
	}
	else {
		alert('Η λέξη αναζήτησης πρέπει να έχει τουλάχιστον 3 χαρακτήρες');
	}
    
	return 'minLengthNotValid';
}


function getValueFromSelectOneMenu(menuId){

	var selectOneMenu  = document.getElementById(menuId);
	if (selectOneMenu != null){
		var selectedValue = selectOneMenu.value;

		if (selectedValue == 'org.jboss.seam.ui.NoSelectionConverter.noSelectionValue'){
			selectedValue = '0';
		}
	}
	else{
		selectedValue = '0';
	}

	return selectedValue;
}

function getValueFromDateField(dateComponentId){
	var dateField = document.getElementById(dateComponentId);

	if (dateField != null){
		var date  = dateField.value;
		if (date == '' || date == null){
			date = '1900-01-01';
		}
	}
	else{
		date = '1900-01-01';
	}

	return date;
}

function parseParametersForQueryRefinementAndSubmit(pageNumber){
	parseParametersForQueryRefinementAndSubmitInternal(pageNumber, false);
}

function parseParametersForQueryRefinementAndCreateRSS(pageNumber){
	parseParametersForQueryRefinementAndSubmitInternal(pageNumber, true);
}

function storeValueSelectedFromRichCaledar(richCalendarComponent, inputHiddenIdToStoreTo){
	
	if (richCalendarComponent != null){
		var selectedDate=richCalendarComponent.getSelectedDateString('dd-MM-yyyy'); 
		document.getElementById(inputHiddenIdToStoreTo).value=selectedDate;
	}
	else{
		document.getElementById(inputHiddenIdToStoreTo).value='';
	}
}

function parseParametersForQueryRefinementAndSubmitInternal(pageNumber,rss){

	var fromDate  = getValueFromDateField('pageForm:fromDateString');
	var toDate  = getValueFromDateField('pageForm:toDateString');    

	if (rss && (fromDate != '1900-01-01' || toDate != '1900-01-01')) {
		alert('Δεν είναι δυνατή η δημιουργία RSS με την ύπαρξη ημερομηνιών στα κριτήρια της αναζήτησης');
		return false;
	}
	
	var textSearchedElement = document.getElementById('pageForm:textSearchInAdvancePage');

	var textSearched = 'noTextSearch';

	if (textSearchedElement != null){
		var textSearched= textSearchedElement.value;

		if (textSearched != null){
			//Trim value
			textSearched = textSearched.replace(/^\s*/, "").replace(/\s*$/, "");

			if (textSearched.length > 0 && validateTextSearched(textSearched)) {
				textSearched = Url.encode(textSearched);
			}
			else{
				textSearched = 'noTextSearch';
			}		
		}
		else {
			textSearched = 'noTextSearch';
		}						
	}

	var selectedContentObjectType = getValueFromSelectOneMenu('pageForm:contentTypesMenu');
	

	var selectedWhatTopic  = getValueFromSelectOneMenu('pageForm:subjectTopic');
	var selectedWhereVenueTopic  = getValueFromSelectOneMenu('pageForm:whereVenue');
	var selectedHowTopic  = getValueFromSelectOneMenu('pageForm:how');
	var selectedOrganizationTopic  = getValueFromSelectOneMenu('pageForm:organizationWho');

	var  relatedPersonSystemNameHidden = document.getElementById('pageForm:relatedPersonSystemNameHidden');
	var selectedRelatedPersonSystemName  = null;

	if (relatedPersonSystemNameHidden != null && relatedPersonSystemNameHidden.value != null){
		selectedRelatedPersonSystemName  = relatedPersonSystemNameHidden.value;
	}
	
	var dateProperty = null;
	var  locationNameHidden = document.getElementById('pageForm:locationNameHidden');
	var selectedLocationName  = null;
	
	var searchArchiveElement = document.getElementById('pageForm:searchArchive');
	

	if (locationNameHidden != null && locationNameHidden.value != null){
		selectedLocationName  = locationNameHidden.value;
	}



	var atLeastOneQeuryParameterIsSpecified = false;

	var resourceRequestURL = portalContext+'/resource/contentObject';
	
	var representation = '/t/search';
	
	if (selectedContentObjectType != 0) {
		resourceRequestURL = resourceRequestURL + '/contentTypes/' + selectedContentObjectType;
		
		
		if (selectedContentObjectType == 'event'){
			dateProperty = 'startDate';
		}
		
		if (selectedContentObjectType.indexOf(',') == -1)
		{
			atLeastOneQeuryParameterIsSpecified = true;
		}
		
	}

	if (selectedWhatTopic != 0) {
		resourceRequestURL = resourceRequestURL + '/what/' + selectedWhatTopic ;
		atLeastOneQeuryParameterIsSpecified = true;
	}

	if (selectedWhereVenueTopic != 0) {
		resourceRequestURL = resourceRequestURL + '/whereVenue/' + selectedWhereVenueTopic ;
		atLeastOneQeuryParameterIsSpecified = true;
	}
	
	if (selectedHowTopic != 0) {
		resourceRequestURL = resourceRequestURL + '/how/' + selectedHowTopic ;
		atLeastOneQeuryParameterIsSpecified = true;
	}

	if (selectedOrganizationTopic != 0) {
		resourceRequestURL = resourceRequestURL + '/organizationWho/' + selectedOrganizationTopic ;
		atLeastOneQeuryParameterIsSpecified = true;
	}

	if (selectedLocationName != null && selectedLocationName.length > 0) {
		resourceRequestURL = resourceRequestURL + '/location/' + selectedLocationName ;
		atLeastOneQeuryParameterIsSpecified = true;
	}

	
	if (selectedRelatedPersonSystemName != null && selectedRelatedPersonSystemName.length > 0) {
		resourceRequestURL = resourceRequestURL + '/relatedPersonSystemNames/' + selectedRelatedPersonSystemName ;
		atLeastOneQeuryParameterIsSpecified = true;
	}

	if (dateProperty != null){
		resourceRequestURL = resourceRequestURL + '/dateProperty/' + dateProperty;
		atLeastOneQeuryParameterIsSpecified = true;
	}
	
	if (fromDate != '1900-01-01') {
		resourceRequestURL = resourceRequestURL + '/fromDateInclusive/' + fromDate;
		atLeastOneQeuryParameterIsSpecified = true;
	}

	if (toDate != '1900-01-01') {
		resourceRequestURL = resourceRequestURL + '/toDateInclusive/' + toDate;
		atLeastOneQeuryParameterIsSpecified = true;
	}

	if (textSearched != 'noTextSearch') {
		resourceRequestURL = resourceRequestURL + '/textSearched/' + textSearched;
		atLeastOneQeuryParameterIsSpecified = true;
	}

	if (searchArchiveElement != null && searchArchiveElement.checked)
	{
		resourceRequestURL = resourceRequestURL + '/searchArchive/true';
	}
	
	if (atLeastOneQeuryParameterIsSpecified){
		
		if (rss){
			representation = '/resourceRepresentationType/rss_2.0';
		}
		
		resourceRequestURL = resourceRequestURL + '/pageNumber/' + pageNumber+ representation;
	}
	else{
		alert('Παρακαλώ εισάγετε τουλάχιστον ένα κριτήριο για να γίνει η αναζήτηση');
		return false;
	}

	location.href = resourceRequestURL;
	return true;
}

function processFirstLevelTopicSelection(secondLevelMenuId) {
	var secondLevelMenu = document.getElementById(secondLevelMenuId);
	if (secondLevelMenu != null) {
		secondLevelMenu.value = 'org.jboss.seam.ui.NoSelectionConverter.noSelectionValue';
	}

	parseParametersForQueryRefinementAndSubmit(1);
}


function assignSuggestedSelectItemValueToComponentValue(component, sgcomponent){
	
	if (component != null && sgcomponent != null && sgcomponent.getSelectedItems() != null){
		component.value=sgcomponent.getSelectedItems().pluck('value');
	}
	
	return true;
}

function showFormSubmissionMessage(messagePanel){
	if (document.getElementById('pageForm:successfulFormSubmission').value == 'true') {
		messagePanel.show()
	};
}


