function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

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

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

function setPortalContextCallback(result) {
	portalContext = result;
}

// httpsessionchecker
var sessionChecker = Seam.Component.getInstance("httpSessionChecker");
var timeoutMillis = 30*60*1000+3000;
var sessionTimeoutInterval = null;

    function startSessionTimeoutCheck() {
        sessionTimeoutInterval = setInterval('sessionChecker.isNewSession(alertTimeout)', timeoutMillis);
    }

    function stopSessionTimeoutCheck() {
        if (sessionTimeoutInterval) {
        	clearInterval(sessionTimeoutInterval);
        }
    }

    function resetSessionTimeoutCheck() {
        stopSessionTimeoutCheck();
        startSessionTimeoutCheck();
    }

    function alertTimeout(newSession) {
 		if (newSession) {
			clearInterval(sessionTimeoutInterval);
			showExpirationMessageWithRichModalPanel();
       }
    }
    
	function showExpirationMessageWithRichModalPanel(){
		Richfaces.showModalPanel('expirationMessagePanel');
	}
    
 
 // url encode decode
 var Url = {

	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}


// portal js code

//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 lenght 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 textSearched=document.getElementById('pageForm:textSearchURL').value;
	
	if (textSearched != null) {
		if (validateTextSearched(textSearched)) {					
			textSearched = Url.encode(textSearched);			
			location.href= portalContext +'/resource/contentObject/textSearched/'+textSearched+'/pageNumber/'+1;
			return false;
		}
	}
	else {
		alert('Η λέξη αναζήτησης πρέπει να έχει τουλάχιστον 3 χαρακτήρες');
		return false;
	}					
}


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

function isEnterKeyPressed(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));
        if(key==13){
			return true;
		}
		else {
			return false;
		}
	
    }
}

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 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);
	var date  = document.getElementById(dateComponentId).value;
	if (date == '' || date == null){
		date = '1900-01-01';
	}
	
	return date;
}
				
function parseParametersForQueryRefinementAndSubmit(pageNumber){
	
	var textSearched=document.getElementById('pageForm:textSearchedInQueryRefinement').value;
						
	if (textSearched != null){
		if (validateTextSearched(textSearched)) {
			textSearched = Url.encode(textSearched);
		}
		else {
			return false;
		}	
	}
	else {
		textSearched = 'noTextSearch';
	}						
	
	var selectedContentObjectType = getValueFromSelectOneMenu('pageForm:contentObjectTypesMenu');  
	var selectedTopicFirstLevel  = getValueFromSelectOneMenu('pageForm:subjectTaxonomyFirstLevelSelectOneMenu');
	var selectedTopicSecondLevel  = getValueFromSelectOneMenu('pageForm:subjectTaxonomySecondLevelSelectOneMenu');
							
	var fromDate  = getValueFromDateField('pageForm:fromDateString');
	var toDate  = getValueFromDateField('pageForm:toDateString');
							
	if ( ( textSearched == ''  || textSearched == 'noTextSearch')
		&& selectedContentObjectType == '0'
		&& selectedTopicFirstLevel == '0' 
		&& selectedTopicSecondLevel == '0'
		&& fromDate  == '1900-01-01'
		&& toDate  == '1900-01-01'){
		
		alert('Παρακαλώ εισάγετε τουλάχιστον ένα κριτήριο για να γίνει η αναζήτηση');
		 return false;
	}
						
	var resourceRequestURL = portalContext + '/resource/contentObject';
	if (selectedContentObjectType != 0) {
		resourceRequestURL = resourceRequestURL + '/contentTypes/' + selectedContentObjectType;
	}
	
	if (selectedTopicSecondLevel != 0) {
		resourceRequestURL = resourceRequestURL + '/topicNames/' + selectedTopicSecondLevel + '/searchInSubtopics/true';
	}
	else if (selectedTopicFirstLevel != 0) {
		resourceRequestURL = resourceRequestURL + '/topicNames/' + selectedTopicFirstLevel + '/searchInSubtopics/true';
	}

	if (fromDate != '1900-01-01') {
		resourceRequestURL = resourceRequestURL + '/fromDateInclusive/' + fromDate;
	}
	
	if (toDate != '1900-01-01') {
		resourceRequestURL = resourceRequestURL + '/toDateInclusive/' + toDate;
	}
	
	if (textSearched != 'noTextSearch') {
		resourceRequestURL = resourceRequestURL + '/textSearched/' + textSearched;
	}
	
	resourceRequestURL = resourceRequestURL + '/pageNumber/' + pageNumber;
	
	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);
}


// event js code
function generateTextSearchURLForEvents(){
	var textSearched=document.getElementById('search-box').value;

	if (textSearched != null) {
		if (validateTextSearched(textSearched)) {					
			textSearched = Url.encode(textSearched);
//			var currentDate = document.getElementById('currentDate').title;	
//			location.href= portalContext + '/resource/event/location/greece/fromDateInclusive/' + currentDate + '/discreteDates/false/textSearched/'+textSearched+'/pageNumber/'+1;

			var textSearchURL = portalContext + '/resource/event/location/greece/textSearched/'+textSearched+'/pageNumber/'+1;
			return textSearchURL;
		}
	}
	else {
		alert('Η λέξη αναζήτησης πρέπει να έχει τουλάχιστον 3 χαρακτήρες');
	}
    
	return 'minLengthNotValid';
}

var dateRangeSelected=null;
function processEventDateSelection() {
	var eventDateMenu  = document.getElementById('pageForm:eventDate');
	if (eventDateMenu.value == 'dateRange') {
		changeObjectVisibility('pageForm:eventDateRangeSelector', 'block');
		dateRangeSelected=true;
	}
	else {
		changeObjectVisibility('pageForm:eventDateRangeSelector', 'none');
		dateRangeSelected=false;
	}
}

function processEventWhatSelection() {
	var eventTypeMenu  = document.getElementById('pageForm:eventWhat');
	if (eventTypeMenu.value == 'moreEventWhat') {
		changeObjectVisibility('pageForm:moreEventCategories', 'block');
		changeObjectVisibility('pageForm:moreEventTypes', 'block');
	}
	else {
		changeObjectVisibility('pageForm:moreEventCategories', 'none');
		changeObjectVisibility('pageForm:moreEventTypes', 'none');
	//	parseParametersForEventQueryRefinementAndImmediatelySubmit();
	}
}


function generateUrlForCycleSelection(){
	
	
	var cycle = getValueFromSelectOneMenu('pageForm:cycle');
												
	var resourceRequestURL = portalContext + '/resource/event';
	
	resourceRequestURL = resourceRequestURL + '/location/greece';
	
	if (cycle != 0) {
		resourceRequestURL = resourceRequestURL + '/cycle/' + cycle;
	}
	
	resourceRequestURL = resourceRequestURL + '/pageNumber/1/t/festivals';
	
	return resourceRequestURL;
}


function generateEventQueryURL(){
	changeObjectVisibility('_viewRoot:status.start', 'block');
	
	var textSearched=document.getElementById('textSearchedInQueryBox').value;
						
	if (textSearched != null && textSearched != ''){
		if (validateTextSearched(textSearched)) {
			textSearched = Url.encode(textSearched);
		}
		else {
			return 'minLengthNotValid';
		}	
	}
	else {
		textSearched = 'noTextSearch';
	}				
												
	
	var isFreeEvent  = document.getElementById('pageForm:isFreeEvent').checked;
	
	var fromDate  = getValueFromDateField('pageForm:txtStartDateInputDate');
	var toDate  = getValueFromDateField('pageForm:txtEndDateInputDate');
	var eventDate = document.getElementById('pageForm:eventDate').value;
		
	var eventCategory  = getValueFromSelectOneMenu('pageForm:eventCategory');
	var eventType  = getValueFromSelectOneMenu('pageForm:eventType');
	var venueType  = getValueFromSelectOneMenu('pageForm:venueType');
	var location  = getValueFromSelectOneMenu('pageForm:locationType');
	var cycle = getValueFromSelectOneMenu('pageForm:cycle');
												
	var resourceRequestURL = portalContext + '/resource/event';
	
	if (location != 0) {
		resourceRequestURL = resourceRequestURL + '/location/' + location;
	}
	
	if (venueType != 0) {
		resourceRequestURL = resourceRequestURL + '/venueType/' + venueType;
	}
	
	if (eventType != 0) {
		resourceRequestURL = resourceRequestURL + '/eventType/' + eventType;
	}
	
	if (eventCategory != 0) {
		resourceRequestURL = resourceRequestURL + '/eventCategory/' + eventCategory;
	}
	
	if (cycle != 0) {
		resourceRequestURL = resourceRequestURL + '/cycle/' + cycle;
	}
	
	if (isFreeEvent != 0) {
		resourceRequestURL = resourceRequestURL + '/free/true';
	}
	
	if (eventDate !='dateRange' && eventDate !='allDates') {
		resourceRequestURL = resourceRequestURL + '/period/' + eventDate;
	}
	else if (eventDate == 'dateRange') {
		if (fromDate != '1900-01-01') {
			resourceRequestURL = resourceRequestURL + '/fromDateInclusive/' + fromDate;
		}
	
		if (toDate != '1900-01-01') {
			resourceRequestURL = resourceRequestURL + '/toDateInclusive/' + toDate;
		}
	}
	
	if (textSearched != 'noTextSearch') {
		resourceRequestURL = resourceRequestURL + '/textSearched/' + textSearched;
	}
	
	resourceRequestURL = resourceRequestURL + '/pageNumber/' + 1;
	
	//location.href = resourceRequestURL;
	return resourceRequestURL;
}

