window.addEvent('domready', function() {
	PhotographerEditForm.implement(new Options);
	
	new AdvancedSearch();
	new PhotoGrapherDetails();
	new PhotographerEditForm({'containers' : $$('dd.multivalued')});
	
	// add insert-action to links in thesaurus popup
	$$('ul.terms li span').addEvent('click', function(ev) {
		new Event(ev).stop();
		window.parent.currentField.setProperty('value', this.getText());
		window.parent.SqueezeBox.close();
	});
	// add action to get underlying terms to links in thesaurus popup
	$$('ul.terms li').addEvent('click', function(ev) {
		new Event(ev).stop();
		
		ul = this.getElementsBySelector('ul.nauwere_term');
		if (ul[0]) {
			if (ul[0].toggleClass('hidden'));
			this.toggleClass('open');
		}
		
		/*
		var term = this.getFirst().getText();
		var domein = $('domein').getProperty('value');
		
		var jSonRequest = new Json.Remote('/index.php?option=com_nfm_fotografen&view=thesaurus&tmpl=component&ajax=1&domein='+domein+'&ruimere_term='+term, {
			onComplete: function(terms) {
				window.console.log(terms);
			}
		}).send();
		*/
	});
	
	// add insert-action to links in names popup
	$$('ul.photographernames li span').addEvent('click', function(ev) {
		new Event(ev).stop();
		window.parent.currentField.setProperty('value', this.getText());
		window.parent.SqueezeBox.close();
	});
	
});

var currentField = null;
var nameField = null;

/**
 * Advanced search form
 * User can add or remove search conditions
 */
var AdvancedSearch = new Class({
	
	initialize : function()
	{
		var self = this;
		
		// set delete row actions for all delete buttons
		$$('ul.advancedSearch li.delete img').each(function(img) {
			self.setDeleteRowAction(img);
		});
		
		// set add row action for add button
		self.setAddRowAction();
	},
	
	/**
	 * show or hide the submit button, depending on if there are search rows present or not
	 */
	checkRowsPresent : function()
	{
		if ($('searchRows').getChildren().length > 0) {
			// there are search rows present - show the submit button
			$$('ul#buttons li.submit').setStyle('display', 'block'); // 
		} else {
			// there are no search rows present - hide the submit button
			$$('ul#buttons li.submit').setStyle('display', 'none');
		}
	},

	/**
	 * when the "add row" button is clicked, copy the row template and insert it into the search rows <div>
	 */
	setAddRowAction : function()
	{
		var self = this;
		
		$$('ul#buttons li.addSearchRow input').addEvent('click', function() {
			searchRow = $$('div.hidden ul.advancedSearch').clone();
			searchRow.injectInside($('searchRows'));
			self.setDeleteRowAction(searchRow.getElement('li.delete img'));
			self.checkRowsPresent();
		});
	},
	
	/**
	 * when the "delete row" button is clicked, remove <ul> with current row
	 */
	setDeleteRowAction : function(img)
	{
		var self = this;
		
		img.addEvent('click', function() {
			// remove parent <ul>
			this.getParent().getParent().remove();
			self.checkRowsPresent();
		});
	}
});

/**
 * Photographer detail page functions
 * Select widget, show/hide info, set/empty commment code etc.
 */
var PhotoGrapherDetails = new Class({
	
	initialize : function() {
		
		var self = this;
		
		this.commentValueDefault = $$('textarea.comment').getProperty('value');
		
		this.commentTexts($$('textarea.comment'));
		this.showHideExtraInfo();
		this.showHideDescription();
		this.widgetSelect();
		
		if ($defined($('showHideExtraInfoButtons'))) {
			// add click event to all contained buttons
			$('showHideExtraInfoButtons').getChildren().addEvent('click', function() {
				self.showHideExtraInfo();
			});
		};
	},

	/**
	 * Empty or reset the default comments text
	 */
	commentTexts : function(elements)
	{
		var self = this;
		
		elements.addEvent('click', function() {
			if (this.getProperty('value') == self.commentValueDefault) {
				this.setProperty('value', '');
			}
		});
		elements.addEvent('blur', function() {
			if (this.getProperty('value') == '') {
				this.setProperty('value', self.commentValueDefault);
			}
		});
	},
	
	/**
	 * if show or hide description button is clicked - toggle display of description intro and full tags
	 */
	showHideDescription : function()
	{
		$$('.highlightedShowDescription').addEvent('click', function(event) {
			event = new Event(event).stop();
			if ($$('.descriptionIntro').getStyle('display') == 'none') {
				$$('.descriptionIntro').setStyle('display', 'block');
				$$('.descriptionFull').setStyle('display', 'none');
			} else {
				$$('.descriptionIntro').setStyle('display', 'none');
				$$('.descriptionFull').setStyle('display', 'block');
			}
			return false;
		});
	},
	
	/**
	 * show or hide the extra information fields for a photographer
	 */
	showHideExtraInfo : function()
	{
		if ($defined($('photographerExtraInfo'))) {
			$('photographerExtraInfo').toggleClass('hidden');
		}
		if ($defined($('showHideExtraInfoButtons'))) {
			// loop through all contained buttons
			$('showHideExtraInfoButtons').getChildren().toggleClass('hidden');
		}
	},
	
	/**
	 * If the "widget html code" input box is entered - select the entire value
	 */
	widgetSelect : function()
	{
		if ($defined($('photographerWidgetCode'))) {
			$('photographerWidgetCode').addEvent('click', function() {
				this.select();
			});
		}
	}
});

/**
 * Edit photographer form
 * User can add or remove fields
 */
var PhotographerEditForm = new Class({
	
	options : {
		containers : [],
		classnameInputEdit: 'edit',
		classnameAnchorAdd: 'add',
		classnameAnchorDelete: 'delete',
		classnameAnchorThesaurus: 'thesaurus',
		classnameAnchorName: 'name',
		spanAddText: 'Add',
		spanDeleteText: 'Delete',
		spanDeleteThesaurus: 'Thesaurus',
		spanThesaurusText: 'Thesaurus',
		spanNameText: 'Names',
	},
	
	initialize : function(options) {
		// backup 'title' value to 'alt' value because Tips class empties 'title'
		$$('.editlinktip').each(function(span) {
			span.setProperty('alt', span.getProperty('title'));
		});
		
		this.setOptions(options);
		this.initializeAnchors();
	},

	initializeAnchors : function() {
		// fill 'title' value with backup ion 'alt' value because Tips class empties 'title'
		$$('.editlinktip').each(function(span) {
			span.setProperty('title', span.getProperty('alt'));
		});
		var JTooltips = new Tips($$('.editlinktip'), { maxTitleChars: 50, fixed: false});
		
		var self = this;
		
		$$('dd.multivalued').each(function(container) {
			if (container.hasClass('group') == false) {
				self.removeAnchors(container);
				self.setAnchorsDelete(container);
				self.setAnchorAdd(container);
			}
		});
		
		$$('div.group').each(function(groupContainer) {
			self.removeAnchorsGrouped(groupContainer);
			self.setAnchorsDeleteGrouped(groupContainer);
			self.setAnchorAddGrouped(groupContainer);
		});
		
		$$('dd.multivalued').each(function(container) {
			self.setAnchorPopups(container);
		});
		
		$$('input.isodate').each(function(input) {
			Calendar.setup({
				inputField	: input,
				ifFormat	: "%Y-%m-%d"
			})
		});
	},

	/**
	 * remove all existing anchors buttons in containers
	 */
	removeAnchors : function(container)
	{
		container.getElementsBySelector('a').each(function(anchor) {
			anchor.remove();
		});
	},
	
	/**
	 * remove all existing anchors buttons in grouped containers
	 */
	removeAnchorsGrouped : function(groupContainer)
	{
		groupContainer.getElementsBySelector('a').each(function(anchor) {
			anchor.remove();
		});
	},
	
	/**
	 * Add anchor for adding a new input field
	 */
	setAnchorAdd : function(container)
	{
		var self = this;
		
		anchor = new Element('a', {
			'class' : self.options.classnameAnchorAdd,
			'events' : {
				'click' : function() {
					// duplicate the last edit field for container / grouped containers
					var field = container.getElementsBySelector('.edit').getLast().clone(); // @TODO check if this can be chained into 1 line
					field.setProperty('value', '');
					field.injectInside(container);
					
					self.initializeAnchors();					
				}
			}
		});
		
		// add span tag with text for inside anchor
		span = new Element('span', {}); // @TODO check if this can be chained into 1 line
		span.setText(self.options.spanAddText);
				
		span.injectInside(anchor);
		anchor.injectInside(container);
	},
	
	/**
	 * Add anchor for adding a new grouped input field
	 */
	setAnchorAddGrouped : function(groupContainer)
	{
		var self = this;
		var groupClass = '';
		
		groupContainer.getProperty('class').split(' ').each(function(className) {
			if (className.indexOf('group_') !== -1) {
				groupClass = className;
			}
		});
		var groups = $$('div.'+groupClass);
		
		if (groups.getLast() != groupContainer) return;
		
		anchor = new Element('a', {
			'class' : self.options.classnameAnchorAdd,
			'events' : {
				'click' : function() {
					// duplicate the last edit field for container / grouped containers
					// @TODO check if this can be chained into 1 line
					group = groupContainer.clone();
					group.getElementsBySelector('.edit').setProperty('value', '');
					group.injectAfter(groups.getLast());
					
					// duplicate the last edit field
					self.initializeAnchors();
				}
			}
		});
		
		// add span tag with text for inside anchor
		// @TODO check if this can be chained into 1 line
		span = new Element('span', {});
		span.setText(self.options.spanAddText);
		
		span.injectInside(anchor);
		anchor.injectTop(groupContainer);
	},
	
	/**
	 * Add anchors for removing input fields
	 */
	setAnchorsDelete : function(container)
	{
		var self = this;
		var containers = []
		
		// check if there is more than 1 input field, when there is only 1 field - it can't be removed
		inputs = container.getElementsBySelector('.' + self.options.classnameInputEdit);
		
		if (inputs.length > 1) {
			// add anchor for each field
			inputs.each(function(input, offset) {
				anchor = new Element('a', {
					'class' : self.options.classnameAnchorDelete,
					'events' : {
						'click' : function() {
							// delete edit field from container
							curInputs = container.getElementsBySelector('.' + self.options.classnameInputEdit);
							curInputs[offset].remove();
							self.initializeAnchors();
						}
					}
				});
				
				// add span tag with text for inside anchor
				// @TODO check if this can be chained into 1 line
				span = new Element('span', {});
				span.setText(self.options.spanDeleteText);
						
				span.injectInside(anchor);
				anchor.injectAfter(input);
			})
		}
	},
	
	/**
	 * Add anchors for removing grouped input field
	 */
	setAnchorsDeleteGrouped : function(groupContainer)
	{
		var self = this;
		var groupClass = '';
		
		groupContainer.getProperty('class').split(' ').each(function(className) {
			if (className.indexOf('group_') !== -1) {
				groupClass = className;
			}
		});
		
		var groups = $$('div.'+groupClass);
		
		// only add delete anchor if there is more than one group
		if (groups.length <= 1) return;
		
		// add anchor for groupContainer
		anchor = new Element('a', {
			'class' : self.options.classnameAnchorDelete,
			'events' : {
				'click' : function() {
					// delete groupContainers
					groupContainer.remove();
					self.initializeAnchors();
				}
			}
		});
				
		// add span tag with text for inside anchor
		// @TODO check if this can be chained into 1 line
		span = new Element('span', {});
		span.setText(self.options.spanDeleteText);
						
		span.injectInside(anchor);
		anchor.injectTop(groupContainer);
	},
	
	/**
	 * Add anchor for opening thesaurus field
	 */
	setAnchorPopups : function(container)
	{
		var self = this;
		
		// check if there is more than 1 input field, when there is only 1 field - it can't be removed
		inputs = container.getElementsBySelector('.' + self.options.classnameInputEdit);
		
		inputs.each(function(input, offset) {
			
			if (input.getProperty('readonly')) {
				
				var alt = input.getProperty('alt');
				
				if (alt.indexOf('thesaurus') != -1) {
					parts = alt.split(':');
					var url = '/index.php?option=com_nfm_fotografen&view=thesaurus&tmpl=component&domein=' + parts[1];
					var currentText = self.options.spanThesaurusText;
				}
				
				if (alt.indexOf('name') != -1) {
					var url = '/index.php?option=com_nfm_fotografen&view=fotograafnamen&tmpl=component';
					var currentText = self.options.spanNameText;
				}
				
				anchor = new Element('a', {
					'class' : self.options.classnameAnchorThesaurus,
					'href': url,
					'events' : {
						'click' : function(ev) {
							new Event(ev).stop();
							
							currentField = this.getPrevious();
							
							SqueezeBox.fromElement(this, {
								handler : 'iframe',
								classWindow: 'thesaurus',
								classOverlay: 'thesaurus',
								size : {
									x : 450,
									y : 460
								},
								marginInner : {
									x : 0,
									y : 0
								}
							});
						}
					}
				});
				
				
				// add span tag with text for inside anchor
				span = new Element('span', {}); // @TODO check if this can be chained into 1 line
				span.setText(currentText);
						
				span.injectInside(anchor);
				anchor.injectAfter(input);
			}
		});
	}
	
});
