/* 	CalendarField
*	Nice calendar navigation
*	
*	IMPORTANT
*
*	
*										*/
var CalendarField = function( ref, set )	{

	Object.extend( obj = $$( '.CalendarField' ).pop(), CalendarField.proto );
	Object.extend( obj, CalendarField[ "proto_" + ref.react ]);
	obj.ref = ref;
	
	obj.select( ".header" )[0].insert(
		new Element( "div", { "class":"arrow left" }).observe( 'click', obj.load.bind( obj ))
	).insert(
		new Element( "div", { "class":"month" }).observe( 'click', obj.load.bind( obj )).update( "..." )
	).insert(
		new Element( "div", { "class":"arrow right" }).observe( 'click', obj.load.bind( obj ))
	);
	
	obj.init();
	if( set ) obj.seed( set );
	
	return obj;
}


CalendarField.proto = {
	
	current		: 0,
	
	load		: function( el ) {
		
		this.current += ( el.currentTarget.hasClassName( "left" ) )? -1 : 1;
		this.select( ".month" )[0].update( "..." );
		
		xhttp.send( '/xhttp.mod', { mod: "calendar.field", action: "mini", vars: { current: this.current }}, this.pull_response.bind( this ));
	},
	
	seed		: function( set ) {
		this.set = set;
		this.count = set.first;
		
		this.select( ".month" )[0].update( set.month );
		this.select( "span.node" ).each( this.fillnode.bind( this ));
		this.checkday();
		
		if( this.multi ) this.multi.hide();
	},
	
	fillnode	: function( span, n) {
			
			span.className = ( ++this.count <= 0 || this.count > this.set.days ) ? 'node blur': 'node';
			span.update(
				( this.count > 0 )? (( this.count > this.set.days )? this.count - this.set.days : this.count ) : this.set.prevdays + this.count
			).stopObserving().n = this.count;
			
			if( this.set.nodes && this.set.numref[ n ] )
				span.observe( "mouseover", this.hover ).observe( "click", this.bubble ).addClassName( "active" ).ref = this.set.numref[ n ];
	},
	
	checkday	: function() {
		
		switch ( this.current ) { 
			case -1	: num = this.set.today + this.set.days - this.set.first; break;
			case 0	: num = this.set.today - this.set.first; break;
			case 1	: num = this.set.today - this.set.prevdays - this.set.first; break;
			default	: num = -1;
		}
		if( num > 0 && num < 42 ) this.select( "span.node" )[ num-1 ].addClassName( "today" );
	},
	
	goto		: function( id ) {
		window.location = "/agenda/dag?calid=" + id;
	},
	
	pull_response	: function( response ) {
		
		set = response.responseText.evalJSON();
		this.seed( set );
	},
	
	bubble		: function() {}

}

CalendarField.proto_info = {
	
	init		: function() {
	
		this.insert( { top: new Element( "div", { "class":"info" }).update(
			new Element( "h1" ).update( "Klik dag voor detailpagina" )
		) });
	},
	
	hover		: function() {
		obj = this.up(1);
		descr = this.innerHTML + "." + (( this.n < 0 )? obj.set.prevstr : ( this.n <= obj.set.days )? obj.set.curstr: obj.set.nextstr ); 
		
		info = obj.select( ".info" )[0].update(
			new Element( "h1" ).update( descr )
		).insert( ul = new Element( "ul" ));
		
		this.ref.each( function( id ){
			ul.insert( "<li class=''><strong>" + obj.set.nodes[ id ].name + "</strong>" + obj.set.nodes[ id ].hour + ", " + obj.set.locations[ obj.set.nodes[ id ].location ] + "</li>" );
		});
	},
	
	bubble		: function() {
		
		this.up(1).select( ".info" )[0].update( "daar gaan we..." );
		obj.goto( this.ref[0] );
	}
}

CalendarField.proto_multi = {
	
	init		: function() {
	
		this.insert( this.multi = new Element( "ul", { "class": "multi" }).hide() );
	},
	
	hover		: function() {
		multi = this.up(1).multi.clonePosition( this, { setWidth:false, setHeight:false, offsetTop:-11 }).update().show();
		
		this.ref.each( function( id ){
			
			multi.insert( "<li class=''><a href='" + this.ref.uri + "?calid=" + id + "'>" + this.set.nodes[ id ].name + "</a> " + this.set.nodes[ id ].hour + "<br /><a href='" + this.set.nodes[ id ].uri + "' class='bio'>bio</a> " + this.set.locations[ this.set.nodes[ id ].location ] + "</li>" );
		}.bind( this.up(1) ));
	}
}














/*calendar = {
			cur		: 0,
			multi	: 0,
			load	: function(n) {
				$('refcal.month').update("dum dum...");
				calendar.cur += n;
				if(this.multi) $('float').hide();
				xhttp.send("/inc/ajx/mod.php", {wtype:'ajax', mod:'group', vars:{ 'n':calendar.cur, 'multi':this.multi }});
			},
			parse	: function(count) {
				$R(1, 42).each(function(n) { count++;
					$('refcal.'+n).className = (count<=0 || count > calendar.totalm) ? 'blur':'';
					$('refcal.'+n).stopObserving();
					if(calendar.dates['refcal.'+n]) {
						$('refcal.'+n).addClassName('active');
						$('refcal.'+n).observe('mouseover',calendar.blub);
					}
  					input = (count>0)? ((count > calendar.totalm)? count - calendar.totalm : count) : calendar.tprev + count;
  					$('refcal.'+n).update(input);
				});
			},
			blub 	: function() {
				
				if(calendar.multi) {
					vars = calendar.dates[this.id]; name='';
					$('float').clonePosition(this, {setWidth:0,setHeight:0,offsetLeft:0,offsetTop:0});
					$('float').update();
					vars.each(function(o){ $('float').appendChild(new Element('a',{href:"/artists/bio?id="+o.ID,"style":(o.otype==2)?"color:#aaa;":""}).update(o.name+"<br />")); });
					//$('float').update(name);
					$('float').show();
				} else {
					vars = calendar.dates[this.id][0];
					$('hint').clonePosition(this, {setWidth:0,setHeight:0,offsetLeft:6,offsetTop:21});
					$('hint.cont').update(vars.name);
					$('hint').show();
					this.observe('click', calendar.doinfo);
					this.observe('mouseout',calendar.unblub);
				}
			},
			refer	: function() {
					$('hint').clonePosition(this, {setWidth:0,setHeight:0,offsetLeft:6,offsetTop:21});
					$('hint.cont').update("klik voor volledig overzicht");
					$('hint').show();
					this.observe('click', function(){ window.location = "/agenda/cal.alles";});
					this.observe('mouseout',calendar.unblub);
			},
			unblub	: function() { $('hint').hide(); },
			closest	: function(now) {
				$('refcal.'+now).addClassName('now');
				for(n = now; n<42; n++) {
					if(calendar.dates['refcal.'+n]) { calendar.doinfo('refcal.'+n); break; }
				}
			},
			doinfo	: function(e) {
				vars = calendar.dates[(typeof e == 'string')? $(e).id : e.target.id][0];
				$('refcal.info.title').update();
				$('refcal.info.title').appendChild( new Element('a', {href:'/artiesten/bio?id='+vars.ID}).update(vars.name));
				$('refcal.info.date').update(vars.date);
				$('refcal.info.content').update(vars.content);
				$('refcal.info.content').appendChild(new Element('a', {href:'/artiesten/bio?id='+vars.ID}).update(' ...meer'));
				if(vars.alt) $('refcal.info.content').innerHTML += "<br />"+vars.alt;
			},
			goto	: function() {
				window.location = "/artists/bio?id="+calendar.dates[this.id][0].ID;
			}
		}
*/


var TextForm = function( action, vars, modid )	{
	
	
	Object.extend( obj = xhttp.checkscope( '.TextForm' ), TextForm.proto );
	Object.extend( obj, TextForm[ "proto_" + action ]);
	
	obj.modid		= modid;
	obj.form		= obj.down( "form" );
	obj.form.action	= "/xhttp.mod";
	
	return obj.init( vars );
	
}

// GENERAL PROTOS
TextForm.proto = {
	
	foo			: function() {
	
		return "Bar.";
	},
	
	init		: function( vars ) {
			
		this.vars = vars;
				
		if( vars.validate )
			for ( id in vars.validate ) 
				this.down( '#'+ id ).observe( vars.validate[ id ].event, this[ "validate_" + vars.validate[ id ].action ].bind( this )).vars = vars.validate[ id ];
		
		if( vars.actions )
			for ( id in vars.actions ) 
				this.down( '[name="'+ id +'"]' ).observe( "click", this[ vars.actions[ id ]].bind( this ));
			
		
		return this;
	},
	
	push			: function() {

		this.form.request( {
			parameters: { set: Object.toJSON({ mod: "text.form", action:"push" })},
			evalJSON: 'force',
			onComplete: this.confirmed.bind(this)
		} );
	},
	
	submit			: function( e ) {
		
		el = e.element();	
		el.value = "connecting...";
		
		if( el.vars && typeof el.vars.succ == "string" ) {

			var succ	= el.vars.succ;
			var fb	= '';
			var tw	= '';
			
			
			if( el.vars.social ) {
				if( el.vars.social.twitter ) {
					tw = " <a class='social twitter' title='post to twitter' href='http://twitter.com/home/?status=" + el.vars.social_message + "' target='_blank'>Post to twitter</a>";
				}
				
				if ( el.vars.social.facebook ) {
					fb = " <a class='social facebook' title='post to facebook' href='http://facebook.com/share.php?u=" + el.vars.social_message + "' target='_blank'>Post to facebook</a>";
				}
			}
			
			succ = succ + tw +fb;
		
			el.up(0).update( succ );
		}
		
		this.form.request( {
			parameters: { set: Object.toJSON({ mod: "text.form", action:"query", id:this.modid })},
			evalJSON: 'force',
			onComplete: this.confirmed.bind( this )
		} );
			
		this.form.disable();
	},
	
	confirmed	: function( response ) {
		
		var set = response.responseJSON;
		///// IF "update", point to element and update 
		if( set.update ) {
			this.form.update( set.update )
		}
		
		
		///// IF func, eval function
		if( set.func ) {
			this[ set.func ]();
		}

	},
	
	redirect	: function() {
		
		window.location = this.vars.redirect;
	}

}

// ACTION SPECIFIC OVERWRITES
TextForm.proto_sequence = {

	init			: function( validate ) {
	
		for ( val in validate ) 
			$( val ).observe( validate[ val ].event, this[ "validate_" + validate[ val ].action ].bind( this,  validate[ val ], val )).vars = validate[ val ];
		
		//xhttp.loadModule( "text.note" );
		
		return this;
	},
	
	validate_connect: function( act, el ) {
	
		$( el ).up(2).hide();
		this.select( '.' + act.connect )[0].removeClassName('hide');
	},
	
	validate_redirect	: function( act, el ) {
		
		window.location = act.redirect;

	},
	
	validate_req	: function( elem, act, e ) {
	
		el = e.element();
		el.pass = true;
		
		this.form.getElements().each( function( node ) {
	
			if( $( node.parentNode ).hasClassName("req") && (!node.getValue() || ( el.vars && $( node.parentNode ).hasClassName( "err" )))) {
				
				el.pass = false;
				$( node.parentNode ).addClassName( "err" );
			} else
				$( node.parentNode ).removeClassName( "err" );
			
		});
		
		if( el.pass ) this.submit( e );
		else this.note( "stick", ( el.vars.err )? el.vars.err : "Error.", el );
	}
	
}


TextForm.proto_simple = {
	
		
	login			: function( e ) {
		
		this.form.request({
			parameters: { set: Object.toJSON({ "mod": "text.form", "action": "login" })},
			evalJSON: 'force',
			onComplete: this.confirmed.bind(this)
		});
		
	},
	
	
	logout 			: function ( e ) {
	
		this.form.request({
			parameters: { set: Object.toJSON({ "mod": "text.form", "action": "logout" })},
			evalJSON: 'force',
			onComplete: this.confirmed.bind(this)
		});
	}, 
	
		
	connect			: function ( e ) {
	
		xhttp.construct( Number( this.vars.connect ), this.wrap(), 1 );
				
	},
	
	forgot_pass		: function ( e ) {
	

		this.form.request({
			parameters: { set: Object.toJSON({ "mod": "text.form", "action": "forgot_pass","modid": this.vars.sendin.modid })},
			evalJSON: 'force',
			onComplete: this.confirmed.bind(this)
		});
	
	}
	
	

}


TextForm.proto_label = {

	init			: function( validate ) {
		
		for ( val in validate ) 
			$( val ).observe( validate[ val ].event, this[ "validate_" + validate[ val ].action ].bind( this )).vars = validate[ val ];
		
		//xhttp.loadModule( "text.note" );
		
		return this;
	},
	
	note			: function( type, cont, target ) {
		
		if( !cont && this[ "note_"+ type ] ){
			this[ "note_"+ type ].remove()
			return this[ "note_"+ type ] = false;
		}
		
		if( !this[ "note_"+ type ] )
			if( type == "stick" ) this.insert( this[ "note_"+ type ] = new TextNote( type, { target:target }, true ));
			else target.up(0).insert( this[ "note_"+ type ] = new TextNote( type, { target:target }, true ));
		
		this[ "note_"+ type ].set( cont, target );
	},
	
	validate_reg	: function( e ) {

		el = e.element();
		regexp = new RegExp( el.vars.cond );
		
		if( !regexp.test( el.getValue() )) {
			
			$( el.parentNode ).addClassName( "err" );
			this.note( "stick", ( el.vars.err )? el.vars.err : "Error.", el );
			
		} else {
			this.note( "stick", false );
			$( el.parentNode ).removeClassName( "err" );
		}
	},
	
	validate_print	: function( e ) {
	
		window.print();
		
	},
	
	validate_clone	: function( e ) {
	
		el = e.element();

		if( $( el.vars.cond ).getValue() != el.getValue() || !el.getValue() ) {
			$( el.parentNode ).addClassName( "err" );
			this.note( "stick", ( el.vars.err )? el.vars.err : "Error.", el );
			
		} else {
			$( el.parentNode ).removeClassName( "err" );
			this.note( "stick", false );
		}
	},
	
	validate_calc	: function( e ) {
	
		el = e.element();
		var amount	= eval( Number( el.value ) + el.vars.cond + Number( el.vars.val ));
		
		$( el.vars.holder ).value = amount;
	
	},
	
	validate_cancel	: function( e ) {
	
		this.hide();
		this.previous(0).hide();
	
	},
	
	validate_req	: function( e ) {
		
		el = e.element();
		el.pass = true;
		
		this.form.getElements().each( function( node ) {
	
			if( $( node.parentNode ).hasClassName("req") && (!node.getValue() || ( el.vars && $( node.parentNode ).hasClassName( "err" )))) {
				
				el.pass = false;
				$( node.parentNode ).addClassName( "err" );
			} else
				$( node.parentNode ).removeClassName( "err" );
			
		});
		
		if( el.pass ) this.submit( e );
		else this.note( "stick", ( el.vars.err )? el.vars.err : "Error.", el );
	}

}



// add textnote to form (should be seperated from this module)!!
var TextNote = function( action, vars, blank )	{
	
	Object.extend(
		obj = (blank)? new Element( "div", { "class":"TextNote " + action }) : $$( '.TextNote' ).pop(), 
		TextNote[ "proto_" + action ]
	);
	
	obj.vars = vars;
	return obj.init( );	

}



// ACTION SPECIFIC PROTO'S
TextNote.proto_stick = {
	init		: function() {
		
		return this;
	},
	
	set			: function( string, trg ) {
		
		this.update( string );
		if( trg ) this.clonePosition( trg, { setWidth:false, setHeight:false, offsetTop: trg.getHeight() + 2 });
	}

}


//add_header_element ( "script", {...} )  

TextNews = function( obj )	{
	
	this.obj = (typeof obj == "object" )? obj : (
		(obj == "first")? $$('.TextNews')[0] : $$('.TextNews').pop()
	);
	
	this.children = this.obj.select('li');
	this.children.each( function( el ) {
		el.observe( "click", function( e ){ this.toggleClassName( "active" ); } );
	} );

}

TextNews.prototype =	{
	expand		: function( cond ) {
		
		if( cond == "first" ) this.children[0].addClassName( "active" );
		else if( !cond ) this.children.invoke( "addClassName", "active");
		else for( n=0; n<cond; n++ ) chlidren[ n ].addClassName( "active" );
	}
}



