var signupCurrentBookForm = null;
var signupCaptchaRequired = true;
var signupHighlightElement = null;
var signupEffectDefaults = { duration: 0.3 };
var signupShowRewindModal = false;

document.observe("dom:loaded",function(){
	
	/* previous/next/this week links */
	$$('a.linkNextWeek','a.linkPreviousWeek','a.linkThisWeek').each(function(elt){
		elt.observe('click',function(event){
			event.stop();
			if (!elt.hasClassName('inactive')) {
				if (elt.hasClassName('linkThisWeek')) {
					pageNumber = $('signupContainer').retrieve('page_thisweek');
				} else {
					pageNumber = $('signupContainer').retrieve('page','1');
					pageNumber = parseInt(pageNumber,10) + (elt.hasClassName('linkNextWeek') ? 1 : -1);
				}
				$('signupContainer').store('page',pageNumber);			
				signupTblRedraw(pageNumber);
			}
		});
	});
	
	/* settings links */
	$$('a.linkSettings').each(function(elt,index){
		elt.observe('click',function(event){
			event.stop();
			if (!$('signupSettingsContainer')) {
				$$('.signupControls .col3 a').each(function(elt){ elt.addClassName('inactive'); }); // make control links inactive
				$$('#signupTbl tr.slots td > a').each(function(link){ link.stopObserving('click').observe('click',function(event){ event.stop(); }); }); // disable all slot links
				$('signupTbl').setOpacity(.3);
				$('loader').appear(signupEffectDefaults);
				new Ajax.Request(location.pathname,{
					method: 'get',
					parameters: {
						action: 'settings'
					},
					onSuccess: function(response){
						$('loader').fade(signupEffectDefaults);
						$('signupTblContainer').insert((index == 0 ? { top: response.responseText } : { bottom: response.responseText }));
						Effect.BlindDown('signupSettingsContainer', { duration: signupEffectDefaults['duration'], queue: 'end' });
					}
				});
			}
		});
	});
	
	/* captcha form */
	if ($('signupCaptchaForm')) {
		$('signupCaptchaForm').observe('submit',function(event){
			event.stop();
			new Ajax.Updater($(signupCurrentBookForm).down('.error').identify(),location.pathname,{
				parameters: $H(event.element().serialize({hash:true})).merge({action:'book'}).merge($(signupCurrentBookForm).serialize({hash:true})),
				method: 'post',
				onCreate: function(){ event.element().disable(); },
				onSuccess: function () {
					Control.Modal.close();
					Recaptcha.reload();
					event.element().enable();
				},
				evalScripts: true
			});
		});
	}
	
	signupInitNavigation();
	
}); /* dom:loaded */

function signupObserveAttributesLink (link) {
	
	link.observe('click',function(event){
		event.stop();
		container = link.up('dd');
		new Ajax.Updater(container.identify(),location.pathname,{
			method: 'get',
			parameters: {
				action: 'attributesform',
				ts: link.up('td').down('a.slot').identify().replace(/[^0-9]/g,'')
			},
			onCreate: function(){
				link.update($('signupTblContainer').down('div.loader-small').clone());
				link.down('div.loader-small').appear(signupEffectDefaults);
			},
			onComplete: function(){ signupInitAttributesForm(container); }
		});
	});
}

function signupInitTbl () {

	/* slot popup close links */
	initCloseLink = function(link){
		link.observe('click',function(event){
			event.stop();
			link.up('dl.popup').removeClassName('active').fade(signupEffectDefaults);
		});
	}
	$$('#signupTbl dl.popup dt a').each(initCloseLink);
		
	/* slot links */
	$$('#signupTbl tr.slots td > a.slot').each(function(link){
		link.observe('click',function(event){
			event.stop();
			clearPopups = function () {
				$$('#signupTbl tr.slots td dl.popup.active').each(function(popup){
					if (!popup.descendantOf(link.up('td'))) { popup.removeClassName('active').fade(signupEffectDefaults); }
				});
			}
			clearPopups();
			if (event.element().up('td').down('dl.popup')) {
				event.element().up('td').down('dl.popup').addClassName('active').appear({
					duration: signupEffectDefaults['duration'],
					afterFinish: function() {
						if (link.up('td').down('form')) { link.up('td').down('form').focusFirstElement(); }
					}
				});
			} else if (!link.hasClassName('exclusive')) {
				clearPopups();
				link.insert($('signupTblContainer').down('div.loader-small').clone());
				link.down('div.loader-small').appear(signupEffectDefaults);
				new Ajax.Updater(link.up('td').identify(),location.pathname,{
					method: 'get',
					parameters: {
						action: (link.hasClassName('unavailable') ? 'attributesform' : 'bookform'),
						fullpopup: true,
						ts: link.identify().replace(/[^0-9]/g,''),
						exclusivable: (link.hasClassName('exclusivable') ? '1' : '') /* only relevant to bookform action */
					},
					onComplete: function(){
						link.down('div.loader-small').fade({
							duration: signupEffectDefaults['duration'],
							afterFinish: function(){
								link.down('div.loader-small').remove();
							}
						});
						link.up('td').down('dl.popup').addClassName('active').appear({
							duration: signupEffectDefaults['duration'],
							afterFinish: function() {
								link.up('td').down('form').focusFirstElement();
							}
						});
						$$('#signupTbl dl.popup.active dt a').each(initCloseLink);
						if (link.hasClassName('unavailable')) {
							signupInitAttributesForm(link.up('td'));
						} else {
							signupInitBookForm(link.up('td'));
						}
					},
					insertion: 'bottom',
					evalScripts: true
				});
			} else {
				link.highlight({ duration: 1, startcolor: '#ffdddd', keepBackgroundImage: true });
			}
		});		
	});
	
	/* book links */
	$$('a.book').each(function(link){
		link.observe('click',function(event){
			event.stop();
			container = link.up('dd');
			new Ajax.Updater(container.identify(),location.pathname,{
				method: 'get',
				parameters: {action: 'bookform'},
				onCreate: function(){
					link.update($('signupTblContainer').down('div.loader-small').clone());
					link.down('div.loader-small').appear(signupEffectDefaults);
				},
				onComplete: function(){ signupInitBookForm(container); }
			});
		});
	});
	
	/* attributes links */
	$$('a.attributes').each(signupObserveAttributesLink);
	
	/* remove links */
	$$('a.remove').each(function(link){
		link.observe('click',function(event){
			event.stop();
			new Ajax.Request(link.readAttribute('href'),{
				method: 'get',
				onCreate: function(){
					link.setOpacity(0.5);
					signupHighlightElement = link.up('td').down('a.slot').identify();
				},
				onSuccess: function(){ signupTblRedraw(); }
			});
		});
	});
	
	/* highlight updated cell, then reset the var */
	if ($(signupHighlightElement)) {
		$(signupHighlightElement).highlight({ duration: 3, startcolor: '#ffffdd', keepBackgroundImage: true });
	}
	signupHighlightElement = null;
	
	signupInitNavigation();
	
	if (signupShowRewindModal) {
		signupInitRewindModal();
	}
}

function signupInitNavigation () {
	
	/* previous/next week links */
	$$('a.linkNextWeek').each(function(elt){
		if ($('signupContainer').retrieve('page_next_valid','1') == '1') { elt.removeClassName('inactive'); } else { elt.addClassName('inactive'); }
	});
	$$('a.linkPreviousWeek').each(function(elt){
		if ($('signupContainer').retrieve('page_previous_valid','1') == '1') { elt.removeClassName('inactive'); } else { elt.addClassName('inactive'); }
	});
	
	/* this week links */
	$$('a.linkThisWeek').each(function(elt){
		if ($('signupContainer').retrieve('page_thisweek') != $('signupContainer').retrieve('page')) { elt.removeClassName('inactive'); } else { elt.addClassName('inactive'); }
	});
}

function signupTblRedraw (pageNumber) {
	
	if (pageNumber == null) { pageNumber = $('signupContainer').retrieve('page','1'); }

	$('signupTbl').setOpacity(.3);
	$('loader').appear(signupEffectDefaults);
	new Ajax.Updater('signupTblContainer',location.pathname,{
		method: 'get',
		parameters: {
			action: 'draw',
			page: (pageNumber == null ? '' : pageNumber)
		},
		evalScripts: true
	});
}

function signupInitBookForm (container) {

	bookForm = container.down('form');
	if (!bookForm) { return; }
	
	bookForm.insert({
	  top: new Element('input', { type: 'hidden', value: bookForm.up('td').down('a').identify().replace(/[^0-9]/g,''), name: 'ts' })
	}).focusFirstElement();
	
	bookForm.observe('submit',function(event){
		event.stop();
		if (signupCaptchaRequired && $('signupCaptchaForm')) {
			Control.Modal.open($('recaptcha'),{ overlayOpacity: 0.8, fade: true, fadeDuration: signupEffectDefaults['duration'], closeOnClick: false, position: 'center_once' });
			signupCurrentBookForm = bookForm.identify();
		} else {
			new Ajax.Updater(bookForm.down('.error').identify(),location.pathname,{
				parameters: $H(bookForm.serialize({hash:true})).merge({action:'book'}),
				method: 'post',
				onCreate: function(){ bookForm.disable(); },
				onSuccess: function(){ bookForm.enable(); },
				evalScripts: true
			});
		}
	});
	
	/* attributes link, if applicable */
	if (attributesLink = container.down('a.attributes')) {
		signupObserveAttributesLink(attributesLink);
	}
}

function signupInitAttributesForm (container) {

	attributesForm = container.down('form');
	if (!attributesForm) { return; }
	
	attributesForm.insert({
	  top: new Element('input', { type: 'hidden', value: attributesForm.up('td').down('a').identify().replace(/[^0-9]/g,''), name: 'ts' })
	});
	
	attributesForm.observe('submit',function(event){
		event.stop();
		new Ajax.Request(location.pathname,{
			parameters: $H(attributesForm.serialize({hash:true})).merge({action:'attributes'}),
			method: 'post',
			onCreate: function(){ attributesForm.disable(); },
			onSuccess: function(){ attributesForm.enable(); }
		});
		
	});
	
	attributesForm.select('a.remove').each(function(link){
		link.observe('click',function(event){
			event.stop();
			new Ajax.Request(location.pathname,{
				parameters: $H(attributesForm.serialize({hash:true})).merge({ action: 'attributes', remove: '1' }),
				method: 'post',
				onCreate: function(){ attributesForm.disable(); },
				onSuccess: function(){ attributesForm.enable(); }
			});
		});
	});
}

function signupInitRewindModal () {
	
	if (!$('rewindmodal')) { return; }
	
	Control.Modal.open($('rewindmodal'),{ overlayOpacity: 0.8, fade: true, fadeDuration: signupEffectDefaults['duration'], closeOnClick: false, afterClose: function(){ $('rewindmodal').remove(); }, position: 'center_once' });
	
	$$('#rewindmodal a.yes','#rewindmodal a.no').each(function(link){
		link.observe('click',function(event){
			event.stop();
			new Ajax.Request(location.pathname,{
				method: 'post',
				parameters: {
					action: 'rewind',
					subscribe: (link.hasClassName('yes') ? '1' : '')
				}
			});
			Control.Modal.close();
			signupShowRewindModal = false;
		});
	});
}

function signupInitSettingsForm () {
	
	$$('#signupFormSettings p.signupSettingsMessage').each(function(paragraph){
		if (paragraph.up('form').down('.signupSettingsNotify').checked != true) {
			paragraph.setStyle({display:'none'});
		}
	});
	
	$$('#signupFormSettings input.signupSettingsNotify').each(function(inp){
		inp.observe('click',function(event){
			if (inp.checked) {
				Effect.BlindDown(inp.up('form').down('p.signupSettingsMessage'), { duration: signupEffectDefaults['duration'] });
			} else {
				Effect.BlindUp(inp.up('form').down('p.signupSettingsMessage'), { duration: signupEffectDefaults['duration'] });
			}
		});
	});
	
	$$('#signupFormSettings textarea').each(function(elt){
		elt.observe('focus',function(event){
			Effect.Appear(elt.up('p').down('.signupSettingsMessageHelp'),signupEffectDefaults);
		}).observe('blur',function(event){
			Effect.Fade(elt.up('p').down('.signupSettingsMessageHelp'),signupEffectDefaults);
		});
	});
	
	$('signupFormSettings').observe('submit',function(event){
		event.stop();
		new Ajax.Request(location.pathname, {
			method: 'post',
			parameters: $H($('signupFormSettings').serialize({hash:true})).merge({action:'savesettings'}),
			onSuccess: function(){
				event.element().disable();
				new Ajax.Updater('signupTblContainer',location.pathname,{
					method: 'get',
					parameters: {
						action: 'draw',
						page: $('signupContainer').retrieve('page','1')
					},
					evalScripts: true
				});
				$$('a.linkSettings').each(function(elt){ elt.removeClassName('inactive'); });
			}
		});
	});
}
