window.addEvent('domready', function(){

	// the whole activity list item becomes clickable
	$$('.checkinbox').addEvent('click', function(){
		var id = $$(this).get('id');
		var link = new URI('/'+id);
		link.go();
	});
	
	// the chevron lightens up when hovering the activity list items
	$$('.checkinbox').addEvents({
				'mouseover':function(){
					$$(this).addClass('chevronfade');
				},
				'mouseout':function(){
					$$(this).removeClass('chevronfade');
				}
	});			
	
	// if there's a webcheckin button make it pop
	$$('[action=checkin]').addEvent('click', function(e){
		e.stop();
		var pop = new Popbox({'url':this.get('href')});
	});

	// if there's a webcheckin button make it pop
	$$('[action=rsvp]').addEvent('click', function(e){
		e.stop();
		new Rsvp(this);
	});

	// if there's a webcheckin button make it pop
	$$('[action=unrsvp]').addEvent('click', function(e){
		e.stop();
		new Rsvp(this);
	});

	// if there's a login link make it pop
	$$('[action=login]').addEvent('click', function(e){
		e.stop();
		var pop = new Popbox({'url':'/popup/login'});
	});

	// if there's a signon button make it pop
	$$('a.signon').each(function(item){
		item.addEvent('click', function(e){
			e.stop();
			var windowName = 'userConsole';
			var popUp = window.open(this.get('href'), windowName, 'width=980, height=580, left=24, top=24, scrollbars, resizable');
			if (popUp == null || typeof(popUp)=='undefined') {
				var link = new URI(this.get('href'));
				link.go();
			}
		});
	});

	// fill blur input elements
	$$('.blur').each(function(item){
		if(item.get('title') != '' && item.get('value') == '') {
			item.value = item.get('title');
		} else {
			item.removeClass('blur');
		}
	});

	// unblur the input elements 
	$$('.blur').addEvent('focus', function(item){
		if(this.hasClass('blur')) {
			this.removeClass('blur');
			this.value = '';
		}
	});

	// maxlength on textarea's
	$$('textarea[max]').addEvent('keypress', function(e){
		if(this.value.length >= this.get('max')) {
			this.value = this.value.substr(0,this.get('max'));
		}
	});

	// form tips
    $$('.tip').each(function(el){
        var content = el.get('html');
        el.empty();
        new Element('div',{ html: content, 'class': 'content'}).inject(el);
        new Element('div',{ 'class':'pointer'}).inject(el);
    })

    $$('form input, form textarea').addEvents({
       'focus': function(){ if(this.getParent('tr')) this.getParent('tr').getElements('.tip').setStyle('display','block'); },
       'blur': function(){  if(this.getParent('tr')) this.getParent('tr').getElements('.tip').setStyle('display','none'); }
    });

	// error message
    if($('message')){
        $('message').setStyle('top',-40).tween('top',0);
        (function(){ $('message').tween('top',-40)}).delay(5000);
    }

    $$('#content .rightbar .blocks div.block:nth-child(2n+1)').setStyles({ 'margin-right': '20px' });
	$$('#content #widebar div.block:nth-child(3)').setStyles({ 'margin-top': '0' });
	
	// mouseover photo preview
	$$('.hasphoto').each(function(item){
		var id = item.get('id');
		if (id != '') {
			var type = item.get('rel');
			var assets = $('assets').get('href');
			var position = item.getPosition();
			item.addEvents({
				'mouseover': function(){
					
					var src    = assets+'/images/'+type+'/l/'+id+'.jpg';
					var images = [];
					images.include(src);

					var loader = new Asset.images(images, {
						onProgress: function(counter,index) {
						  //progressBar.set((counter + 1) * (100 / images.length));
						},
						onComplete: function() {
							images.each(function(src,pos) {
							
								var image = new Element('img', {
									'class': 'popoverPhoto',
									'src': src,
									'alt': 'preview',
									'title': 'Photo preview'
								});
								
								image.inject(document.body);

								var docsize = document.body.getSize();
								var half = docsize.x / 2;
								var top  = position.y + 48;
								var left = (position.x < half) ? position.x + 60 : position.x - image.getSize().x;

								image.setStyles({
									'border': '5px solid #ffffff',
									'background': '#000',
									'position': 'absolute',
									//'width': 300,
									//'height': 120,
									'top': top,
									'left': left,
									'z-index': 500,
									'-moz-box-shadow': '1px -1px 30px rgba(0,0,0,0.25)',
									'-webkit-box-shadow': '1px -1px 30px rgba(0,0,0,0.25)',
									'box-shadow': '1px -1px 30px rgba(0,0,0,0.25)'
								});
								image.setStyle('opacity',0).tween('opacity',1);

						  });
						}
					});

				},
				'mouseout': function(){
					$$('.popoverPhoto').destroy();
				}
			});
		}
	});
});

var Reply = new Class({
	Implements: Events,
    initialize: function(){

		var button = $('respond');

		if(!button) return;

		// add event listener
		button.addEvent('click', function(e){

			e.stop();

			var message = $('replymessage').value;
			var url		= button.getParent('form').get('action');

			if(message=='') {
				alert('Je kan geen lege reactie achterlaten.');
				return;
			}

			var notify = ($('notify') && $('notify').checked) ? true : false;

			var jsonRequest = new Request.JSON({ url: url, onSuccess: function(result){

				button.disabled = true;
				button.fade(0.5);

				(function(){
					button.disabled = false;
					button.fade(1);
				}).delay(60*1000);

				$('replymessage').value = "";

				this.fireEvent('complete',result);

			}.bind(this),onFailure: function(result){

				if(result.status == 480) alert('Je reageert te snel');
				if(result.status == 490) alert('Je kan geen lege reactie achterlaten.');

			}.bind(this)}).post({ 'message': message, 'notify': notify, 'ajax': true });

		}.bind(this));
   }
});

var Rsvp = new Class({
	Implements: Events,
    initialize: function(button){

		var action = button.get('action');
		var alt	   = button.get('alt');
		var text   = button.get('text');

		var altclass = button.get('altclass');
		var orgclass = button.get('class');

		button.setStyle('opacity',0.5);

		var vars  = {};
		vars.ajax = true;

		if(action == "rsvp"){
			vars.status = 'attending';
		} else {
			vars.status = 'declined';
		}

		var execute = new Execute(button.get('href'),vars);

		execute.addEvent('complete', function(result){

			button.set('text',alt);
			button.set('alt',text);

			button.set('class',altclass);
			button.set('altclass',orgclass);

			if(action == "rsvp"){
				button.set('action','unrsvp');
			} else {
				button.set('action','rsvp');
			}
			button.setStyle('opacity',1);

			this.fireEvent('complete',result);
		
		}.bind(this));

   }
});

var Execute = new Class({
	Implements: Events,
    initialize: function(url,vars){
      	var jsonRequest = new Request.JSON({url:url,onSuccess: function(result){
			this.fireEvent('complete',result);
			return;
		}.bind(this),onFailure: function(result){
			if(result.status == 401) var pop = new Popbox({'url':'/popup/login'});
			this.fireEvent('error',result);
		}.bind(this)}).post(vars);
    }
});
