var LinkBox = new Class({
	
	options: {
		numOfShownItems: 3,
		currentItem: 0
	},
	
	initialize: function(elementLinkBox) {
		this.elementLinkBox = elementLinkBox;
		this.elementLinkBoxNavigation = this.elementLinkBox.getElement('DIV.navigation');
		
		this.items = this.elementLinkBox.getElements('DIV.items DIV.item');
		
		
		this.showItems(0);
		
		
		this.buttonUp = this.elementLinkBox.getElement('DIV.navigation A.up');
		if($defined(this.buttonUp)) {
			this.buttonUp.erase('href');
			this.buttonUp.addEvent('click', this.eventUp.bind(this));
		}
		
		this.buttonDown = this.elementLinkBox.getElement('DIV.navigation A.down');
		if($defined(this.buttonDown)) {
			this.buttonDown.erase('href');
			this.buttonDown.addEvent('click', this.eventDown.bind(this));
		}
		
		
		if(this.items.length<=3 && this.items.length>0) {
			this.elementLinkBoxNavigation.setStyle('display', 'none');
			
			var tElement = this.elementLinkBox.getParent().getNext();
			if($defined(tElement)) {
				tElement.addClass('close_empty');
			}
			
			var tSeparator = this.items[this.items.length-1].getElement('DIV.separator');
			if($defined(tSeparator)) 
					tSeparator.setStyle('display', 'none');
		}
	},
	
	showItems: function(fromItem) {
		for(var i=0; i<this.items.length; i++) {
			var tSeparator = this.items[i].getElement('DIV.separator');
			
			if(i < fromItem || i >= (fromItem+this.options.numOfShownItems)) {
				this.items[i].setStyle('display', 'none');
				
				
				if($defined(tSeparator)) 
					tSeparator.setStyle('display', 'none');
			} else {
				this.items[i].setStyle('display', 'block');
				
				if($defined(tSeparator)) {
					if(i < (fromItem+this.options.numOfShownItems-1)) {
						tSeparator.setStyle('display', 'block');
					} else {
						tSeparator.setStyle('display', 'none');
					}
				}
			}
		}
	},
	
	eventUp: function() {
		if(this.options.currentItem>0)
			this.options.currentItem = this.options.currentItem - 1;
		
		this.showItems(this.options.currentItem);
	},
	
	eventDown: function() {
		if(this.options.currentItem<(this.items.length-this.options.numOfShownItems))
			this.options.currentItem = this.options.currentItem + 1;
		
		this.showItems(this.options.currentItem);
	}
	
});

var TopMenuItem = new Class({
	
	options: {
		active: false
	},
	
	initialize: function(elementTopMenuItem) {
		this.elementTopMenuItem = elementTopMenuItem;
		
		
		this.EventDivNormal = this.elementTopMenuItem.getElement('DIV.event_normal');
		this.EventDivOver = this.elementTopMenuItem.getElement('DIV.event_over');
		
		
		this.buttonLink1 = this.EventDivNormal.getElement('A');
		
		if($defined(this.buttonLink1)) {
			this.buttonLink1.addEvent('mouseover', this.eventMouseOver.bind(this));
			this.buttonLink1.addEvent('mouseout', this.eventMouseOut.bind(this));
		}
		
		this.buttonLink2 = this.EventDivOver.getElement('A');
		
		if($defined(this.buttonLink2)) {
			this.buttonLink2.addEvent('mouseover', this.eventMouseOver.bind(this));
			this.buttonLink2.addEvent('mouseout', this.eventMouseOut.bind(this));
		}	
		
		if(this.elementTopMenuItem.get('class').contains('active')) {
			this.eventMouseOver();
			
			this.options.active = true;
		}
	},
	
	eventMouseOver: function() {
		if(!this.options.active) {
			this.EventDivNormal.setStyle('display', 'none');
			this.EventDivOver.setStyle('display', 'block');
		}
	},
	
	eventMouseOut: function() {
		if(!this.options.active) {
			this.EventDivNormal.setStyle('display', 'block');
			this.EventDivOver.setStyle('display', 'none');
		}
	}
	
});



var SubMenuItem = new Class({
	
	options: {
		imageSufix: 'over',
		active: false
	},
	
	initialize: function(elementSubMenuItem) {
		this.elementSubMenuItem = elementSubMenuItem;
		
		this.EventDivNormal = this.elementSubMenuItem.getElement('DIV.event_normal');
		this.EventDivOver = this.elementSubMenuItem.getElement('DIV.event_over');
		
		
		this.buttonLink1 = this.EventDivNormal.getElement('A');
		
		if($defined(this.buttonLink1)) {
			this.buttonLink1.addEvent('mouseover', this.eventMouseOver.bind(this));
			this.buttonLink1.addEvent('mouseout', this.eventMouseOut.bind(this));
		}
		
		this.buttonLink2 = this.EventDivOver.getElement('A');
		
		if($defined(this.buttonLink2)) {
			this.buttonLink2.addEvent('mouseover', this.eventMouseOver.bind(this));
			this.buttonLink2.addEvent('mouseout', this.eventMouseOut.bind(this));
		}
		
		
		if(this.elementSubMenuItem.get('class').contains('active')) {
			this.eventMouseOver();
			
			this.options.active = true;
		}
	},
	
	eventMouseOver: function() {
		if(!this.options.active) {
			this.EventDivNormal.setStyle('display', 'none');
			this.EventDivOver.setStyle('display', 'block');
		}
	},
	
	eventMouseOut: function() {
		if(!this.options.active) {
			this.EventDivNormal.setStyle('display', 'block');
			this.EventDivOver.setStyle('display', 'none');
		}
	}
	
});



var LinkBoxItem = new Class({
	
	options: {
		imageSufix: 'over',
		active: false
	},
	
	initialize: function(elementSubMenuItem) {
		this.elementSubMenuItem = elementSubMenuItem;
		
		this.EventDivNormal = this.elementSubMenuItem.getElement('DIV.event_normal');
		this.EventDivOver = this.elementSubMenuItem.getElement('DIV.event_over');
		
		
		this.buttonLink1 = this.EventDivNormal.getElement('A');
		
		if($defined(this.buttonLink1)) {
			this.buttonLink1.addEvent('mouseover', this.eventMouseOver.bind(this));
			this.buttonLink1.addEvent('mouseout', this.eventMouseOut.bind(this));
		}
		
		this.buttonLink2 = this.EventDivOver.getElement('A');
		
		if($defined(this.buttonLink2)) {
			this.buttonLink2.addEvent('mouseover', this.eventMouseOver.bind(this));
			this.buttonLink2.addEvent('mouseout', this.eventMouseOut.bind(this));
		}
		
		
		if(this.elementSubMenuItem.get('class').contains('active')) {
			this.eventMouseOver();
			
			this.options.active = true;
		} else {
			this.eventMouseOut();
			
			this.options.active = false;
		}
	},
	
	eventMouseOver: function() {
		if(!this.options.active) {
			this.EventDivNormal.setStyle('display', 'none');
			this.EventDivOver.setStyle('display', 'block');
		}
	},
	
	eventMouseOut: function() {
		if(!this.options.active) {
			this.EventDivNormal.setStyle('display', 'block');
			this.EventDivOver.setStyle('display', 'none');
		}
	}
	
});



var Form = new Class({
	
	options: {
	},
	
	initialize: function(eForm) {
		
		this.eForm = eForm;
		this.eMessages = this.eForm.getElement('DIV.messages');
		
		
		var i = 0;
		var fields = new Array();		
		var textfields = this.eForm.getElements('DIV.field INPUT.textfield');
		textfields.each(function(element, index) {
			fields[i] = new TextField(element);
			
			i++;
		});
		
		var textfields = this.eForm.getElements('DIV.field TEXTAREA.textfield');
		textfields.each(function(element, index) {
			fields[i] = new TextField(element);
			
			i++;
		});
		this.textfields = fields;

		var i = 0;
		var fields = new Array();		
		var checkboxes = this.eForm.getElements('DIV.field INPUT.checkbox');
		checkboxes.each(function(element, index) {
			fields[i] = new CheckBox(element);
			
			i++;
		});
		this.checkboxes = fields;
		
		var i = 0;
		var fields = new Array();		
		var comboboxes = this.eForm.getElements('DIV.field SELECT.combobox');
		comboboxes.each(function(element, index) {
			fields[i] = new ComboBox(element);
			
			i++;
		});
		this.comboboxes = fields;
		
		
		this.buttonDiv = this.eForm.getElement('DIV.button');
		if($defined(this.buttonDiv)) {
			this.buttonDiv.addEvent('mouseover', this.eventButtonMouseOver.bind(this));
			this.buttonDiv.addEvent('mouseout', this.eventButtonMouseOut.bind(this));
			
			this.buttonDivEventNormal = this.buttonDiv.getElement('DIV.event_normal');
			this.buttonDivEventOver = this.buttonDiv.getElement('DIV.event_over');
		}
		
		if (!this.buttonDiv.hasClass('customClick'))
			this.buttonDiv.addEvent('click', this.eventFormSubmit.bind(this));
		
		
		this.eForm.addEvent('submit', this.eventFormSubmit.bind(this));
		
			//added for maps form
		this.buttonEvents = this.eForm.getElement('div.buttonEvent');
		if ($defined(this.buttonEvents)) {
			this.buttonEvents.addEvent('click', this.displayDate.bind(this));
		}
		
		this.buttonPartners = this.eForm.getElement('div.buttonPartner');
		if ($defined(this.buttonPartners)) {
			this.buttonPartners.addEvent('click', this.hideDate.bind(this));
		}
		
			//added for registration link button for article
		this.registerButton = this.eForm.getElement('div.registerButton');
		if($defined(this.registerButton)) {
			this.registerButton.addEvent('mouseover', this.eventRegisterButtonMouseOver.bind(this));
			this.registerButton.addEvent('mouseout', this.eventRegisterButtonMouseOut.bind(this));
			
			this.registerButtonEventNormal = this.registerButton.getElement('DIV.event_normal');
			this.registerButtonEventOver = this.registerButton.getElement('DIV.event_over');
		}
			
		
	},
	
	eventButtonMouseOver: function() {
		this.buttonDivEventNormal.setStyle('display', 'none');
		this.buttonDivEventOver.setStyle('display', 'block');
	},
	
	eventButtonMouseOut: function() {
		this.buttonDivEventNormal.setStyle('display', 'block');
		this.buttonDivEventOver.setStyle('display', 'none');
	},
	
	eventRegisterButtonMouseOver: function() {
		this.registerButtonEventNormal.setStyle('display', 'none');
		this.registerButtonEventOver.setStyle('display', 'block');
	},
	
	eventRegisterButtonMouseOut: function() {
		this.registerButtonEventNormal.setStyle('display', 'block');
		this.registerButtonEventOver.setStyle('display', 'none');
	},
	
	validation: function() {
		this.eMessages.empty();
		
		for(var i=0; i<this.textfields.length; i++) {
			this.textfields[i].eField = $(this.textfields[i].fId);
			if(!this.textfields[i].validation()) {
				this.eMessages.grab(this.textfields[i].eMessage);
				
				return false;
			}
		}
		
		for(var i=0; i<this.checkboxes.length; i++) {
			if(!this.checkboxes[i].validation()) {
				this.eMessages.grab(this.checkboxes[i].eMessage);
				
				return false;
			}
		}
		
		for(var i=0; i<this.comboboxes.length; i++) {
			if(!this.comboboxes[i].validation()) {
				return false;
			}
		}
		
		return true;
	},
	
	eventFormSubmit: function() {
		if(this.validation()) {
			for(var i=0; i<this.textfields.length; i++) {
				if(this.textfields[i].isValueEmpty()) {
					this.textfields[i].eField.set('value', '');
				} else if (this.textfields[i].eField.type=='password' && typeof MD5=='function') {
					this.textfields[i].eField.set('value', MD5(this.textfields[i].eField.get('value')));
				}
			}
			
			this.eForm.submit();
		}
		
		return false;
	},
	
	displayDate:function(){
		this.dateFields = this.eForm.getElement('div.events_date');
		this.dateFields.setStyle('display', 'block');
		
		this.eventsActive = this.eForm.getElement('div.buttonEvent div.event_active');
		this.eventsActive.setStyle('display', 'block');

		this.eventsNormal = this.eForm.getElement('div.buttonEvent div.event_normal');
		this.eventsNormal.setStyle('display', 'none');

		this.partnersNormal = this.eForm.getElement('div.buttonPartner div.event_normal');
		this.partnersNormal.setStyle('display', 'block');

		this.partnersActive = this.eForm.getElement('div.buttonPartner div.event_active');
		this.partnersActive.setStyle('display', 'none');
		
		if (typeof submitSearch == 'function') submitSearch();
	},
	
	hideDate:function(){
		this.dateFields = this.eForm.getElement('div.events_date');
		this.dateFields.setStyle('display', 'none');	
		
		this.eventsActive = this.eForm.getElement('div.buttonEvent div.event_active');
		this.eventsActive.setStyle('display', 'none');

		this.eventsNormal = this.eForm.getElement('div.buttonEvent div.event_normal');
		this.eventsNormal.setStyle('display', 'block');

		this.partnersNormal = this.eForm.getElement('div.buttonPartner div.event_normal');
		this.partnersNormal.setStyle('display', 'none');

		this.partnersActive = this.eForm.getElement('div.buttonPartner div.event_active');
		this.partnersActive.setStyle('display', 'block');

		if (typeof submitSearch == 'function') submitSearch();
	}
	
});

var TextField = new Class({
	
	options: {
	},
	
	initialize: function(eField) {
		this.eField = eField;		
		this.eLabel = this.eField.getPrevious();
		this.eMessage = new Element('div', {'class': 'message'});
		
		
		this.fValue = this.eField.get('value');
		this.fType = this.eField.get('type');
		this.fId = this.eField.get('id'); 
		
		this.eLabelValue = this.eLabel.get('text').trim();
		
		if(this.fType=='password' && this.isValueEmpty()) {
			this.eField.set('type', 'text');
		}
		
		if(this.eField.get('value').length==0) {
			this.eField.set('value', this.eLabelValue);
		}
		
		if(this.fId == 'password' || this.fId == 'password_repeat'){
			v = this.eLabelValue;
			changeInputType(this.eField,'text',v,false,true);
			//populateElement(this.fId, v, 'password');
		}else{
			this.eField.addEvent('focus', this.eventFieldFocus.bind(this));
		}
		
		//this.eField.addEvent('focus', this.eventFieldFocus.bind(this));
		this.eField.addEvent('blur', this.eventFieldBlur.bind(this));
	},
	
	isValueEmpty: function() {
		if(this.eField.get('value').length==0 || this.eField.get('value')==this.eLabelValue)
			return true;
		
		return false;
	},
	
	validation: function() {
		if(this.eField.hasClass('required') && this.isValueEmpty()) {
			this.eField.addClass('error');
			
			this.eMessage.grab(new Element('img', {'src': 'fileadmin/templates/biu/images/form_message_error_icon.gif'}));
			
			var errormessage = document.getElementById(this.eField.get('id') + '_errormessage_' + 'required');
			if($defined(errormessage)) {
				this.eMessage.appendText(errormessage.innerHTML);
			}
			
			return false;
		} else if((this.eField.hasClass('required-institution') && $('institution').get('checked')) && this.isValueEmpty()) {
			this.eField.addClass('error');
			
			this.eMessage.grab(new Element('img', {'src': 'fileadmin/templates/biu/images/form_message_error_icon.gif'}));
			
			var errormessage = document.getElementById(this.eField.get('id') + '_errormessage_' + 'required-institution');
			if($defined(errormessage)) {
				this.eMessage.appendText(errormessage.innerHTML);
			}
			
			return false;
		} else if(!this.isValueEmpty() && (this.eField.hasClass('password_repeat') && this.eField.get('value') != $('password_repeat').get('value'))) {
			this.eField.addClass('error');
			
			this.eMessage.grab(new Element('img', {'src': 'fileadmin/templates/biu/images/form_message_error_icon.gif'}));
			
			var errormessage = document.getElementById(this.eField.get('id') + '_errormessage_' + 'password_repeat');
			if($defined(errormessage)) {
				this.eMessage.appendText(errormessage.innerHTML);
			}
			
			return false;
		} else if(this.eField.hasClass('email') && !this.isValueEmpty()) {
				if(!this.validationCheckEmail()) {
					this.eField.addClass('error');
					
					
					this.eMessage.grab(new Element('img', {'src': 'fileadmin/templates/biu/images/form_message_error_icon.gif'}));
					
					var errormessage = document.getElementById(this.eField.get('id') + '_errormessage_' + 'email');
					if($defined(errormessage)) {
						this.eMessage.appendText(errormessage.innerHTML);
					}
					
					
					return false;
				} else {
					this.eField.removeClass('error');
				}
		} else {
			this.eField.removeClass('error');
		}
				
		return true;
	},
	
	validationCheckEmail: function() {
		with(this.eField) {
			atpos = value.indexOf("@");
			dotpos = value.lastIndexOf(".");
			
			if(atpos<1 || dotpos-atpos<2) 
				return false;
		}
		
		return true;
	},
	
	eventFieldFocus: function() {
		if(this.fType=='password') 
			this.eField.set('type', 'password');
		
		if(this.isValueEmpty()) {
			this.eField.set('value', '');
		} else {
			
		}
	},
	
	eventFieldBlur: function() {
		if(this.isValueEmpty()) {
			if(this.fType=='password')
				this.eField.set('type', 'text');
			
			this.eField.set('value', this.eLabelValue);
		} else {
			if(this.fType=='password') 
				this.eField.set('type', 'password');
		}
	}
	
});

var CheckBox = new Class({
	
	options: {
	},
	
	initialize: function(eField) {
		this.eField = eField;
		this.eLabel = this.eField.getNext();
		this.eMessage = new Element('div', {'class': 'message'});
	},
	
	isChecked: function() {
		if(this.eField.get('checked'))
			return true;
		
		return false;
	},
	
	validation: function() {
		
		
		if(this.eField.hasClass('required') && !this.isChecked()) {
			this.eLabel.addClass('error');
			
			
			this.eMessage.grab(new Element('img', {'src': 'fileadmin/templates/biu/images/form_message_error_icon.gif'}));
			
			var errormessage = document.getElementById(this.eField.get('id') + '_errormessage_' + 'required');
			if($defined(errormessage)) {
				this.eMessage.appendText(errormessage.innerHTML);
			}
			
			
			return false;
		} else {
			this.eLabel.removeClass('error');
		}
		
		return true;
	}
	
});

var ComboBox = new Class({
	
	options: {
	},
	
	initialize: function(eField) {
		this.eField = eField;
	},
	
	validation: function() {
		return true;
	}
	
});

var InstitutionButton = new Class({
    options: {
	},
	
	initialize: function(eField) {
		this.eField = eField;
		this.eForm = eField.getParent('form');//.getParent();
		
		if($defined(this.eField)) {
			this.eField.addEvent('click', this.eventClick.bind(this));
		}
		
		this.eventClick();
	},
	
	eventClick: function() {
		var fields = this.eForm.getElements('DIV.institution');
		var checked = this.isChecked();
		
		fields.each(function(element, index) {
			if(checked) {
				element.setStyle('display', 'block');
			} else {
				element.setStyle('display', 'none');
			}
		});
	},
	
	isChecked: function() {
		if(this.eField.get('checked'))
			return true;
		
		return false;
	}
	
});


var custButton = new Class({
    options: {
	},
	
	initialize: function(button) {
		this.button = button;
		
		if($defined(this.button)) {
			this.button.addEvent('mouseover', this.mouseOver.bind(this));
			this.button.addEvent('mouseout', this.mouseOut.bind(this));
			
			this.buttonEventNormal = this.button.getElement('DIV.event_normal');
			this.buttonEventOver = this.button.getElement('DIV.event_over');
		}
	},
	
	mouseOver: function() {
		this.buttonEventNormal.setStyle('display', 'none');
		this.buttonEventOver.setStyle('display', 'block');
	},
	
	mouseOut: function() {
		this.buttonEventNormal.setStyle('display', 'block');
		this.buttonEventOver.setStyle('display', 'none');
	}
	
});




var ImageGallery = new Class({
	
	options: {
		currentItem: 0
	},
	
	initialize: function(elementImageGallery) {
		this.elementImageGallery = elementImageGallery;
		this.images = this.elementImageGallery.getElements('DIV.images DIV.image');
		
		
		this.buttonPrevious = this.elementImageGallery.getElement('DIV.navigation A.previous');
		if($defined(this.buttonPrevious)) {
			this.buttonPrevious.erase('href');
			this.buttonPrevious.addEvent('click', this.eventPrevious.bind(this));
		}
		
		this.buttonNext = this.elementImageGallery.getElement('DIV.navigation A.next');
		if($defined(this.buttonNext)) {
			this.buttonNext.erase('href');
			this.buttonNext.addEvent('click', this.eventNext.bind(this));
		}
		
		
		this.navigationLabel = this.elementImageGallery.getElement('DIV.navigation DIV.label');
		
		
		this.showImage(this.options.currentItem);
	},
	
	showImage: function(index) {
		if($defined(this.navigationLabel)) 
			this.navigationLabel.set('text', (index+1) + ' von ' + (this.images.length));
		
		
		for(var i=0; i<this.images.length; i++) 
			this.images[i].setStyle('display', 'none');
		
		
		this.images[index].setStyle('display', 'block');
	},
	
	eventPrevious: function() {
		if(this.options.currentItem>0)
			this.options.currentItem = this.options.currentItem - 1;
		
		this.showImage(this.options.currentItem);
	},
	
	eventNext: function() {
		if(this.options.currentItem<(this.images.length-1))
			this.options.currentItem = this.options.currentItem + 1;
		
		this.showImage(this.options.currentItem);
	}
	
});



var VotingForm = new Class({
	
	options: {
		currentValue: 0,
		markedStar: 0
	},
	
	initialize: function(elementVotingForm) {
		this.elementVotingForm = elementVotingForm;
		
		this.elementVotingFormValue = this.elementVotingForm.getElement('INPUT');
		this.options.currentValue = this.elementVotingFormValue.get('value');
		
		this.options.markedStar = this.elementVotingFormValue.get('value')-1;
		
		var stars = new Array();
		var starelements = this.elementVotingForm.getElements('DIV.items DIV.item');
		starelements.each(function(element, index) {
			stars[index] = element;
		});
		this.stars = stars;
		
		
		for(var i=0; i<this.stars.length; i++) {
			this.stars[i].addEvent('click', this.eventStarClick.bind(this, i));
			
			this.stars[i].addEvent('mouseover', this.eventStarMouseOver.bind(this, i));
			this.stars[i].addEvent('mouseout', this.eventStarMouseOut.bind(this, i));
		}
		
		this.eventStarMouseOut();
	},
	
	submitVotingForm: function() {
		//this.elementVotingForm.submit();
		var req = new Request({
		              method: 'get',
		              url: this.elementVotingForm.action+'&tx_biuarticle_pi2[vote_numofstars]='+this.elementVotingFormValue.get('value'),
		              onComplete: function(response) { 
										var decodedResponse = JSON.decode(response);
										if (decodedResponse['success']) {
											this.callingForm.options.markedStar = parseInt(decodedResponse['result'])-1;
											this.callingForm.eventStarMouseOut();
										} else {
											$('article_error_message').setStyle('display','block');
											$('article_error_message').innerHTML = decodedResponse['result'];
										}
								  }
		          });
		req.callingForm = this;
		req.send();		
	},
	
	eventStarClick: function(value) {
		this.options.currentValue = value;
		
		this.elementVotingFormValue.set('value', value+1);
		
		this.submitVotingForm();
	},
	
	eventStarMouseOver: function(value) {
		for(var i=0; i<this.stars.length; i++) {
			if(i<=value) {
				this.stars[i].getElement('DIV.star_normal').setStyle('display', 'none');
				this.stars[i].getElement('DIV.star_over').setStyle('display', 'block');
			} else {
				this.stars[i].getElement('DIV.star_normal').setStyle('display', 'block');
				this.stars[i].getElement('DIV.star_over').setStyle('display', 'none');
			}
		}
	},
	
	eventStarMouseOut: function() {
		for(var i=0; i<this.stars.length; i++) {
			if(i<=this.options.markedStar) {
				this.stars[i].getElement('DIV.star_normal').setStyle('display', 'none');
				this.stars[i].getElement('DIV.star_over').setStyle('display', 'block');
			} else {
				this.stars[i].getElement('DIV.star_normal').setStyle('display', 'block');
				this.stars[i].getElement('DIV.star_over').setStyle('display', 'none');
			}
		}
	}
	
});

var Institution = new Class({
	options: {
	},

	initialize: function(gLatLng, iId, institutionType) {
		this.gLatLng = gLatLng;
		this.iId = iId;
		if (gLatLng)
			this.gMarker = new GMarker(gLatLng, {icon:institutionType.getGIcon()});
		else
			this.gMarker = null;
	},

	clickOnMap: function() {
		institutionMap.locatePartner(this.iId);
	},
	
	getMarker: function() {
		return this.gMarker;
	},
	
	setListener: function(val) {
		this.listener = val;
	},
	
	getListener: function() {
		return this.listener;
	}
});

var InstitutionType = new Class({
	initialize: function(itId, imageSrc) {
		this.itId = itId;
		this.gIcon = new GIcon(G_DEFAULT_ICON);
		this.gIcon.image = imageSrc;	
		this.gIcon.shadow = 'none';	
	},

	getGIcon: function() {
		return this.gIcon;
	}
});

var InstitutionMap = new Class({
	options: {
		pageNum: 3,
		partnerPidList: '0',
		eventPidList: '0',
		templatePartnerDetail: '',
		templateEventDetail: '',
		templatePartnerList: '',
		templateEventList: '',
		eidUrl: '/index.php?eID=biu_partner',
		currentRequestId: 0,
		idMapLoader: 'map_loader',
		idMapBrowser: 'map_browser',
		idMapResults: 'map_results'
	},
	
	initialize: function(options) {
		$extend(this.options, options || {});
		this.keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
		this.partners = [];
		this.events = [];

		this.options.templatePartnerDetail 		= this.decode64(this.options.templatePartnerDetail);
		this.options.templateEventDetail 		= this.decode64(this.options.templateEventDetail);
		this.options.templatePartnerList 		= this.decode64(this.options.templatePartnerList);
		this.options.templateEventList 			= this.decode64(this.options.templateEventList);
		
		if (GBrowserIsCompatible()) {
			this.map = new GMap2(document.getElementById("g_map"));
			this.map.setCenter(new GLatLng(51.12, 10.24), 6);
			this.map.setUIToDefault();
			this.map.removeControl(GSmallZoomControl);
			//this.map.addControl(new GLargeMapControl3D());
			this.map.removeMapType(G_HYBRID_MAP);
			//this.map.addControl(new GOverviewMapControl());
			this.map.addControl(new GMapTypeControl());
			this.map.setMapType(G_NORMAL_MAP);
		}	
	},
	
	getGMap: function() {
		return this.map;
	},
	
		// searchPartners, searchEvents, partnerDetail
	request: function(requestType, data) {
		prepData = {'tx_biupartner_pi1[requestId]': 		++this.options.currentRequestId,
			        'tx_biupartner_pi1[eventPidList]': 		this.options.eventPidList,
			        'tx_biupartner_pi1[partnerPidList]': 	this.options.partnerPidList,
			        'tx_biupartner_pi1[pageNum]': 			this.options.pageNum,
	                'tx_biupartner_pi1[requestType]':		requestType};
		data = data || {};
		dataTransf = {};
		$(institutionMap.options.idMapLoader).setStyle('display','block');
		$(institutionMap.options.idMapBrowser).innerHTML = '';
		$(institutionMap.options.idMapResults).innerHTML = '';

		for ( var i in data )
		{
			dataTransf['tx_biupartner_pi1['+i+']'] = data[i];
		} 
		$extend(prepData, dataTransf || {});
		var req = new Request({
              method: 'get',
              url: this.options.eidUrl,
              'data': prepData,
              onComplete: institutionMap.processResponse
        	});
		req.requestType = requestType;
		req.send();		
	},
	
	processResponse: function(response) {
		var decodedResponse = JSON.decode(response);
		if (decodedResponse['requestId']==institutionMap.options.currentRequestId &&
			$(institutionMap.options.idMapResults)) {
			if (decodedResponse['status']==200) {
				switch(decodedResponse['requestType']) {
					case 'searchPartners':
						eventTemplate = false;
						partnerTemplate = institutionMap.options.templatePartnerList;
						
						institutionMap.listState = {
								requestType: 	decodedResponse['requestType'],
								sword:			decodedResponse['sword'],
								institutionType:decodedResponse['institutionType']
						};
						institutionMap.currentResults = decodedResponse;

						break;

					case 'partnerDetail':
						eventTemplate = institutionMap.options.templateEventDetail;
						partnerTemplate = institutionMap.options.templatePartnerDetail;
						
						institutionMap.listState = {
								requestType: 	decodedResponse['requestType'],
								iId:			decodedResponse['iId']
						};
						institutionMap.currentResults = decodedResponse;
						
						break;

					case 'searchEvents':
						eventTemplate = institutionMap.options.templateEventList;
						partnerTemplate = false;
						
						institutionMap.listState = {
								requestType: 	decodedResponse['requestType'],
								sword:			decodedResponse['sword'],
								startDate:		decodedResponse['startDate'],
								endDate:		decodedResponse['endDate'],
								institutionType:decodedResponse['institutionType']
						};
						institutionMap.currentResults = decodedResponse;
						
						break;
						
					default:
						break;
				}

				result = '';
				var map = institutionMap.getGMap();
				
					// add gMap markers 
				map.clearOverlays();
				for (i=0; decodedResponse['partners'] && i<decodedResponse['partners'].length; i++) {
					partner = decodedResponse['partners'][i];
					institutionMap.partners[partner['uid']] = partner;
					var latlng = null;
					if (partner['glatlng']) {
						latlng = new GLatLng(parseFloat(partner['glatlng'][1]), parseFloat(partner['glatlng'][0]));
					}
			    	var institution = new Institution (latlng, partner['uid'], institutionTypes[partner['tx_edsrfeuserregister_institution_type']]);
					institutions[partner['uid']] = institution;
					
					if (partner['glatlng']) {
				        GEvent.addListener(institution.getMarker(),"click", institution.clickOnMap.bind(institution));
				        map.addOverlay(institution.getMarker());
					}
				}
					// render results
				institutionMap.goToPage(0);
		
			} else {
				alert('Oops, an error occured on the server. Please try again later.');
			}
		}
	},
	
	renderPageBrowser: function(currentPage, totalPages) {
		if (totalPages>1) {
			if ($(institutionMap.options.idMapBrowser)) {
				counter = totalPages;
				p = currentPage;
				left = 2;
				right = 2;
				result = '';
				left = left>p?p:left;
				
				if (p>0) {
						// show link to the previous page
                    result += '<div class="previous"><a href="/" onclick="javascript:institutionMap.goToPage('+(p-1)+'); return false;"><img src="fileadmin/templates/biu/images/arrows_left.gif" border="0" alt=""/></a></div>';
					if (left<p) {
						result += '<div class="hiddenpages">...</div>';
					}
					for (i=0; i<left; i++) {
						result += '<div class="page"><a href="/" onclick="javascript:institutionMap.goToPage('+(p-left+i)+'); return false;">'+(p-left+i+1)+'</a></div>';
					}
				}
				
				result += '<div class="page active">'+(p+1)+'</div>';
				
				right = right>(counter-p-1)?(counter-p-1):right;
				
				if (right>0) {
					for (i=0; i<right; i++) {
						result += '<div class="page"><a href="/" onclick="javascript:institutionMap.goToPage('+(p+i+1)+'); return false;">'+(p+i+2)+'</a></div>';
					}
					if (p+right<counter-1) {
						result += '<div class="hiddenpages">...</div>';
					}
                    result += '<div class="previous"><a href="/" onclick="javascript:institutionMap.goToPage('+(p+1)+'); return false;"><img src="fileadmin/templates/biu/images/arrows_right.gif" border="0" alt=""/></a></div>';
				}

				return result;
			}
		} else {
			return '';
		}		
	},
	
	renderPartner: function (template, partner) {
        content = template.replace(/\n/gm, '');
        content = content.replace(/###COMPANY###/g,		partner['company']);
        content = content.replace(/###UID###/g,			partner['uid']);
        content = content.replace(/###ZIP###/g, 		partner['zip']);
        if (partner['image']) {
        	content = content.replace(/###IMAGE###/g,	partner['image']);					        	
        } else {
        	content = content.replace(/(.*)<\!\-\-\s*###NO_IMAGE###\s*\-\-\>(.*)<!--\s*###NO_IMAGE###\s*\-\->(.*)/g, '$1$3');
        }
        if (partner['www']) {
        	content = content.replace(/###WEBSITE###/g,	partner['www']);					        	
        	content = content.replace(/###WEBSITE_URL###/g,	partner['www_url']);					        	
        } else {
        	content = content.replace(/(.*)<\!\-\-\s*###NO_WEBSITE###\s*\-\-\>(.*)<!--\s*###NO_WEBSITE###\s*\-\->(.*)/g, '$1$3');
        }
        content = content.replace(/###CITY###/g, 		partner['city']);
        content = content.replace(/###ITYPE###/g, 		partner['tx_edsrfeuserregister_institution_type']);
        short_text = partner['tx_edsrfeuserregister_description'].replace(/([^>]?)\n/g, '$1<br />\n');
        content = content.replace(/###DESC###/g, 	short_text);
        if (short_text.length>100) 
        	short_text = short_text.substring(0, 100)+'...';
        content = content.replace(/###SHORT_DESC###/g, 	short_text);
        content = content.replace(/###ADDRESS###/g, 	partner['address'].replace(/([^>]?)\n/g, '$1<br />\n'));
        
        return content;
	},
	
	renderEvent: function (template, eventS) {
        content = template.replace(/\n/gm, '');
        content = content.replace('###TITLE###', 		eventS['title']);
        content = content.replace('###COMPANY###',		eventS['company']);
        content = content.replace('###UID###', 			eventS['uid']);
        content = content.replace('###COMPANY_UID###',	eventS['company_uid']);
        content = content.replace('###START_DATE###',	this.formatDate(eventS['start_date']));
        if (eventS['end_date'] && eventS['end_date']!=0) {
            content = content.replace('###END_DATE###',	this.formatDate(eventS['end_date']));
        } else {
        	content = content.replace(/(.*)<\!\-\-\s*###NO_END_DATE###\s*\-\-\>(.*)<!--\s*###NO_END_DATE###\s*\-\->(.*)/g, '$1$3');
        }
        if (eventS['image']) {
        	content = content.replace('###IMAGE###', 	eventS['image']);					        	
        } else {
        	content = content.replace(/(.*)<\!\-\-\s*###NO_IMAGE###\s*\-\-\>(.*)<!--\s*###NO_IMAGE###\s*\-\->(.*)/g, '$1$3');
        }
        short_text = eventS['description'].replace(/([^>]?)\n/g, '$1<br />\n');
        content = content.replace('###DESC###', 		short_text);
        if (short_text.length>100) 
        	short_text = short_text.substring(0, 100)+'...';
        content = content.replace('###SHORT_DESC###', 	short_text);
        
        return content;
	},
	
	goToPage: function(p) {
		$(institutionMap.options.idMapLoader).setStyle('display','block');
		$(institutionMap.options.idMapBrowser).innerHTML = '';
		$(institutionMap.options.idMapResults).innerHTML = '';
		
		decodedResponse = institutionMap.currentResults;
		result = '';
		var k = 0;
		
		pageNum = institutionMap.options.pageNum;
		gotoPage = p;
			// render results
		if (institutionMap.listState.requestType=='partnerDetail') {
			pageNum = 1;
			gotoPage = 0;
		}
		
		for (i=gotoPage*pageNum; decodedResponse['partners'] && i<decodedResponse['partners'].length; i++) {
			partner = decodedResponse['partners'][i];
			if (partnerTemplate && k++ < pageNum)
				result += institutionMap.renderPartner(partnerTemplate, partner);
		}
		
		if (institutionMap.listState.requestType=='partnerDetail') {
			pageNum = institutionMap.options.pageNum-1;
			gotoPage = p;
		}

		k = 0;
		for (i=gotoPage*pageNum; decodedResponse['events'] && i<decodedResponse['events'].length; i++) {
			eventS = decodedResponse['events'][i];
			if (eventTemplate && k++ < pageNum)
				result += institutionMap.renderEvent(eventTemplate, eventS);
		}		

		$(institutionMap.options.idMapLoader).setStyle('display','none');
		if (result.length==0) result = noResultsFound;
		$(institutionMap.options.idMapResults).innerHTML = result;

		if ($(institutionMap.options.idMapBrowser))
			$(institutionMap.options.idMapBrowser).innerHTML = institutionMap.renderPageBrowser(p, decodedResponse['pages']);
		
		/*
			// old logic with additional request per page
		data = this.listState || {};
		$extend(data, {'p': p});
		this.request('', data);
		*/
	},
	
	encode64: function (input) {
	   var output = "";
	   var chr1, chr2, chr3;
	   var enc1, enc2, enc3, enc4;
	   var i = 0;

	   do {
	      chr1 = input.charCodeAt(i++);
	      chr2 = input.charCodeAt(i++);
	      chr3 = input.charCodeAt(i++);

	      enc1 = chr1 >> 2;
	      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
	      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
	      enc4 = chr3 & 63;

	      if (isNaN(chr2)) {
	         enc3 = enc4 = 64;
	      } else if (isNaN(chr3)) {
	         enc4 = 64;
	      }

	      output = output + this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) + this.keyStr.charAt(enc3) + this.keyStr.charAt(enc4);
	   } while (i < input.length);
	   
	   return output;
	},

	decode64: function (input) {
	   var output = "";
	   var chr1, chr2, chr3;
	   var enc1, enc2, enc3, enc4;
	   var i = 0;

	   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
	   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

	   do {
	      enc1 = this.keyStr.indexOf(input.charAt(i++));
	      enc2 = this.keyStr.indexOf(input.charAt(i++));
	      enc3 = this.keyStr.indexOf(input.charAt(i++));
	      enc4 = this.keyStr.indexOf(input.charAt(i++));

	      chr1 = (enc1 << 2) | (enc2 >> 4);
	      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
	      chr3 = ((enc3 & 3) << 6) | enc4;

	      output = output + String.fromCharCode(chr1);

	      if (enc3 != 64) {
	         output = output + String.fromCharCode(chr2);
	      }
	      if (enc4 != 64) {
	         output = output + String.fromCharCode(chr3);
	      }
	   } while (i < input.length);

	   return output;
	},
	
	formatDate: function(timestamp)
	{
	  var dt = new Date(timestamp * 1000);
	  return dt.getDate()+"."+(dt.getMonth()+1)+"."+(""+dt.getFullYear()).substring(2,4);
	},
	
	locatePartner: function (iId) {
		marker = institutions[iId].getMarker();
		if (marker) marker.openInfoWindowHtml('<strong>'+this.partners[iId]['company']+'</strong><br />'+
					this.partners[iId]['address'].replace(/([^>]?)\n/g, '$1<br />\n')+'<br />'+
					this.partners[iId]['zip']+' '+this.partners[iId]['city']+'<br />'+
					'<a href="/" onclick="javascript:institutionMap.request(\'partnerDetail\', {iId:'+iId+'}); return false;" style="color:#80A335;font-weight:bold;">'+viewPartnerDetail+'</a>');
		return false;
	}
});



var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
		
BrowserDetect.init();


var SimpleSelectStyle = new Class(
{
    Implements: Options,
   
    options :
    {   
        select_class : '',
        form_id : '',
        left_padding : 4
    },
   
    initialize: function(options)
    {
        this.setOptions(options);
        if ($chk(this.options.select_class))
        {          
            this.selects = $chk($(this.options.form_id)) ? $(this.options.form_id).getElements('select') : $$('select.'+this.options.select_class) ;
            this.selects.each(this.style_selects.bind(this));
        }
    },
   
    style_selects : function(select_el)
    {      
        var select_el_width = select_el.getSize().x;   
        var value = select_el.getFirst().get('value');     
        var text = select_el.getFirst().get('text');
   
        select_el.getElements('option').each(function(o){ if(o.selected == true){ value = o.get('value'); text = o.get('text'); } });
       
        //var span = new Element('span',{'class':this.options.select_class}).set('text',text).inject(select_el,'before').setStyles({'width':select_el_width - this.options.left_padding,'display':'inline-block','position':'relative','padding-left':this.options.left_padding});
        var span = new Element('span',{'class':this.options.select_class}).set('text',text).inject(select_el,'before');
        try {
        	span.setStyles({'width':(select_el_width - this.options.left_padding),'display':'block','position':'absolute','padding-left':this.options.left_padding});
        } catch(err){}
       
        //select_el.addClass(this.options.select_class).setProperty('size',1).setStyles({'width':select_el_width + span.getStyle('border-left-width').toInt() + span.getStyle('border-right-width').toInt(),'opacity':.01,'display':'inline-block','position':'relative','margin-left':-(select_el_width + span.getStyle('border-left-width').toInt() + span.getStyle('border-right-width').toInt())}).addEvent('change',function(){span.set('text',this.options[this.options.selectedIndex].get('text'));});
		select_el.addClass(this.options.select_class).setProperty('size',1).setStyles({'width':select_el_width + span.getStyle('border-left-width').toInt() + span.getStyle('border-right-width').toInt(),'opacity':.01,'display':'block','position':'relative'}).addEvent('change',function(){span.set('text',this.options[this.options.selectedIndex].get('text'));});
    }   
});
 
function divWrap(el, divClass){  
       x = new Element('div', {'class':divClass});
	   el.inject(x);
	   return x; 
}  

function verifyForm(formEl) {
	formEl.getElements('input, textarea').each(function(item) {
		if (item.retrieve('label_text') == item.value) item.value = '';
	});

	return true;
}

function changeInputType(
	  oldElm, // a reference to the input element
	  iType, // value of the type property: 'text' or 'password'
	  iValue, // the default value, set to 'password' in the demo
	  blankValue, // true if the value should be empty, false otherwise
	  noFocus) {  // set to true if the element should not be given focus
	  if(!oldElm || !oldElm.parentNode || (iType.length<4) || 
	    !document.getElementById || !document.createElement) return;
	  var isMSIE=/*@cc_on!@*/false; //http://dean.edwards.name/weblog/2007/03/sniff/
	  if(!isMSIE){
	    var newElm=document.createElement('input');
	    newElm.type=iType;
	  } else {
	    var newElm=document.createElement('span');
	    newElm.innerHTML='<input type="'+iType+'" name="'+oldElm.name+'">';
	    newElm=newElm.firstChild;
	  }
	  var props=['name','id','className','size','tabIndex','accessKey'];
	  for(var i=0,l=props.length;i<l;i++){
	    if(oldElm[props[i]]) newElm[props[i]]=oldElm[props[i]];
	  }
	  newElm.onfocus=function(){return function(){
	    if(this.hasFocus) return;
	    var newElm=changeInputType(this,'password',iValue,
	      (this.value.toLowerCase()==iValue.toLowerCase())?true:false);
	    if(newElm) newElm.hasFocus=true;
	  }}();
	  newElm.onblur=function(){return function(){
	    if(this.hasFocus)
	    if(this.value=='' || (this.value.toLowerCase()==iValue.toLowerCase())) {
	      changeInputType(this,'text',iValue,false,true);
	    }
	  }}();
	 // hasFocus is to prevent a loop where onfocus is triggered over and over again
	  newElm.hasFocus=false;
	  // some browsers need the value set before the element is added to the page
	  // while others need it set after
	  if(!blankValue) newElm.value=iValue;
	  oldElm.parentNode.replaceChild(newElm,oldElm);
	  if(!isMSIE && !blankValue) newElm.value=iValue;
	  if(!noFocus || typeof(noFocus)=='undefined') {
	    window.tempElm=newElm;
	    setTimeout("tempElm.hasFocus=true;tempElm.focus();",1);
	  }
	  return newElm;
}

window.addEvent('domready', function(){
	if (!(BrowserDetect.browser=='Explorer') || !(BrowserDetect.version<7)) {
		$$('select').each(function(item) {
			x = item.clone().addClass('select_special');
			item.getParent().addClass("custom_select clearfix");
			if (item.getParent().getParent().getElement('label[for='+item.id+']'))
				item.getParent().getParent().getElement('label[for='+item.id+']').getParent().setStyle('display', 'block');
				
				//generate three wrapper div elements
	     	t = divWrap(divWrap(divWrap(x, "special_input_outer_2"), "special_input_outer_1"), "special_input_outer_0");  
				
				//switch original input box with the new one with wrapper div elements
			t.injectAfter(item);
			item.dispose();
		});
		var selects = new SimpleSelectStyle({select_class:'select_special'});
	}
});

window.addEvent('domready', function() {
		
	var linkboxes = $$('DIV.linkbox');
	
    linkboxes.each(function(element, index) {
		var navCheck = element.getElement('DIV.navigation');
		
		if(navCheck.getStyle('display')!='none') {
			var tLinkBox = new LinkBox(element);
		}
    });
	
	var topmenuitems = $$('DIV.navigation_main DIV.items DIV.item');
	
    topmenuitems.each(function(element, index) {
		var tTopMenuItem = new TopMenuItem(element);
    });
	
	
	var submenuitems = $$('DIV.navigation_sub DIV.items DIV.item');
	
    submenuitems.each(function(element, index) {
		var tSubMenuItem = new SubMenuItem(element);
    });
	
	
	var linkboxitems = $$('DIV.content_link_box DIV.items DIV.item');
	
    linkboxitems.each(function(element, index) {
		var tLinkBoxItem = new LinkBoxItem(element);
    });
	
	
	var forms = $$('DIV.form FORM');
	
    forms.each(function(element, index) {
		var tForm = new Form(element);
    });
    
    if ($('institution')) {
    	var tInstitutionButton = new InstitutionButton($('institution'));
    }
    
	var votingforms = $$('DIV.voting FORM');
	
    votingforms.each(function(element, index) {
		var tVotingForm = new VotingForm(element);
    });
	
	var buttons = $$('div.custButton');
	buttons.each(function(element, index) {
		var tCustButton = new custButton(element);
    });
	
	
	
	
});


