window.addEvent('domready', function() {

	// Login scherm boven in de pagina
	if($('login'))
	{
		$('login').setStyle('height','auto');
		var mySlide = new Fx.Slide('login').hide();
	
		if($('toggleLogin')) {
			$('toggleLogin').addEvent('click', function(e) {
				e.stop();
				mySlide.toggle();
			});	
		}
		$('closeLogin').addEvent('click', function(e) {
			e.stop();
			mySlide.slideOut();
		});

		// Controle op lege velden
		if($('fancyLoginButton')) {
			$('fancyLoginButton').addEvent('click', function(e) {
				e.stop();
				var blnErrors = false;

				if($('email').value == '') {
					blnErrors = true;
					$('email').setStyles({
						background: 'url(/images/input_error.gif)',
						color: '#333333'
					});
				} else {
					blnErrors = false;
					$('email').setStyles({
						background: 'url(/images/spacer.gif)',
						color: '#ffffff'
					});
				}

				if($('password').value == '') {
					blnErrors = true;
					$('password').setStyles({
						background: 'url(/images/input_error.gif)',
						color: '#333333'
					});
				} else {
					blnErrors = false;
					$('password').setStyles({
						background: 'url(/images/spacer.gif)',
						color: '#ffffff'
					});
				}

				if(blnErrors == false) {
					document.loginForm.submit();
				}
			});
		}
	}

	var AllArticlePhotos = $$('ul#winkel_content li p a img, div#content div.visual img');
	AllArticlePhotos.each(function(SingleArticlePhoto) {
		SingleArticlePhoto.addEvent('contextmenu', function(e) {
			e.stop();
		});
	});

	if($('work_list')) {
		$$('table tbody > tr:odd').addClass('odd');
	}

	if($('work_list')) {
		var textAreasForNice = $$('textarea');
		if(textAreasForNice.length > 0) {
			nicEditors.allTextAreas();
		}
	}

	SqueezeBox.assign($$('a.boxed'), {
		parse: 'rel'
	});


	if($('submenu')) {

		$$('.submenu').each(function(subMenuItems) {
			subMenuItems.setStyle('display','none');
			subMenuItems.getParent('li').getFirst('a').getFirst('span').set('text','+');
		});

		$$('#submenu li a.active, .submenu li a.active').each(function(activeSubMenuItems) {
			activeSubMenuItems.getElement('span').set('text','-');
			if(activeSubMenuItems.getParent('li').getChildren('ul').length != 0) {
				activeSubMenuItems.getParent('li').getChildren('ul')[0].setStyle('display','block');
			}
		});

	}

	$$('#work_list tbody a.delete').addEvent('click', function(e) {
		e.stop();
		if(confirm('Weet u zeker dat u dit item wil verwijderen?')) {
			window.location.href = this.get('href');
		}
	});

	if($('image')) {
		SqueezeBox.assign($('image'), {
			url: '/ajax/images.php'
		});
	}

	$$('a.goback').each(function(backButton) {
		backButton.addEvent('click', function(e) {
			e.stop();
			history.back(-1);
		});
	});

	if($('nested')) {
		NestedTree = new Nested('nested', {
			onStart: startUpdateOrder,
			onComplete: updateOrder
		});
	}

	if($('demo-list')) {
		var up = new FancyUpload2($('demo-status'), $('demo-list'), { // options object
			// we console.log infos, remove that in production!!
			verbose: true,

			// url is read from the form, so you just have to change one place
			url: $('form-demo').action,

			// path to the SWF file
			path: '/js/Swiff.Uploader.swf',

			// remove that line to select all files, or edit it, add more items
			typeFilter: {
				'Images (*.jpg, *.jpeg, *.gif, *.png)': '*.jpg; *.jpeg; *.gif; *.png; *.pdf'
			},

			// this is our browse button, *target* is overlayed with the Flash movie
			target: 'demo-browse',

			// graceful degradation, onLoad is only called if all went well with Flash
			onLoad: function() {
				$('demo-status').removeClass('hide'); // we show the actual UI
				$('demo-fallback').destroy(); // ... and hide the plain form

				// We relay the interactions with the overlayed flash to the link
				this.target.addEvents({
					click: function() {
						return false;
					},
					mouseenter: function() {
						this.addClass('hover');
					},
					mouseleave: function() {
						this.removeClass('hover');
						this.blur();
					},
					mousedown: function() {
						this.focus();
					}
				});

				// Interactions for the 2 other buttons

				$('demo-clear').addEvent('click', function() {
					up.remove(); // remove all files
					return false;
				});

				$('demo-upload').addEvent('click', function() {
					up.start(); // start upload
					return false;
				});
			},

			// Edit the following lines, it is your custom event handling
			/**
			 * Is called when files were not added, "files" is an array of invalid File classes.
			 * 
			 * This example creates a list of error elements directly in the file list, which
			 * hide on click.
			 */ 
			onSelectFail: function(files) {
				files.each(function(file) {
					new Element('li', {
						'class': 'validation-error',
						html: file.validationErrorMessage || file.validationError,
						title: MooTools.lang.get('FancyUpload', 'removeTitle'),
						events: {
							click: function() {
								this.destroy();
							}
						}
					}).inject(this.list, 'top');
				}, this);
			},

			/**
			 * This one was directly in FancyUpload2 before, the event makes it
			 * easier for you, to add your own response handling (you probably want
			 * to send something else than JSON or different items).
			 */
			onFileSuccess: function(file, response) {
				var json = new Hash(JSON.decode(response, true) || {});

				if (json.get('status') == '1') {
					file.element.addClass('file-success');
					file.info.set('html', '<strong>Bestand is geupload:</strong> ' + json.get('width') + ' x ' + json.get('height') + 'px, <em>' + json.get('mime') + '</em>)');
				} else {
					file.element.addClass('file-failed');
					file.info.set('html', '<strong>Er is iets fout gegaan:</strong> ' + (json.get('error') ? (json.get('error') + ' #' + json.get('code')) : response));
				}
			},

			/**
			 * onFail is called when the Flash movie got bashed by some browser plugin
			 * like Adblock or Flashblock.
			 */
			onFail: function(error) {
				switch (error) {
					case 'hidden': // works after enabling the movie and clicking refresh
						alert('To enable the embedded uploader, unblock it in your browser and refresh (see Adblock).');
						break;
					case 'blocked': // This no *full* fail, it works after the user clicks the button
						alert('To enable the embedded uploader, enable the blocked Flash movie (see Flashblock).');
						break;
					case 'empty': // Oh oh, wrong path
						alert('A required file was not found, please be patient and we fix this.');
						break;
					case 'flash': // no flash 9+ :(
						alert('To enable the embedded uploader, install the latest Adobe Flash plugin.')
				}
			}
		});
	}

});

function startUpdateOrder(el) {
	var neighbour = $(el).getPrevious();
	var inject = 'after';
	if (!neighbour) {
		neighbour = el.getNext();
		inject = 'before';
		if (!neighbour) {
			neighbour = el.getParent().getParent();
			inject = 'inside';
		}
	}
	this.currNeighbour = neighbour.getProperty('id');
	this.currInject = inject;
}

function updateOrder(el) {
	var neighbour = $(el).getPrevious();
	var inject = 'after';
	if (!neighbour) {
		neighbour = el.getNext();
		inject = 'before';
		if (!neighbour) {
			neighbour = el.getParent().getParent();
			inject = 'inside';
		}
	}

	if (neighbour) {
		if (this.currInject != inject || this.currNeighbour != neighbour.getProperty('id')) {
			this.lockClass = 'temp';
			new Request({
				url: '/ajax/sort_categories.php',
				method: 'post',
				data: {
					el: el.getProperty('id'),
					neighbour: neighbour.getProperty('id'),
					inject: inject
				},
				onComplete: function() {
					this.lockClass = 'unlocked';
				}.bind(this), 
				onFailure: function() {
					this.lockClass = 'unlocked';
				}.bind(this)
			}).send();
		}
	}
}
