/* / / / / / ENGINE  ROOM / / / / / / /
|	            XHTTP                 |
| (aka javascript response handlers)  |
|                                     |
| last edit:   20100218               |
| package:     beta 2     	          |
/ / / / / / / / / / / / / / / / / / /*/


var xhttp	= {
	errtarget	: false,

	redirect	: function(uri, int, mess) {
		if(mess) $(mess.target).update(mess.text);
		setTimeout("window.location='"+uri+"'",(int)? int:0);
	},
	
	error		: function(err, target){
		if(target) $(target).update(err);
		else if(typeof errtarget == "function") this.errtarget(err);
		else if(errtarget) $(errtarget).update(err);
	},
	
	send		: function( uri, vars, func ) {
		
		options = { parameters: { set: Object.toJSON(vars) }};
		if( func ) options.onSuccess = func;
		
		new Ajax.Request(uri, options );
	},
	
	construct	: function( vars, bind, update ) {

		set		= ( typeof vars == "number" )? { id:vars } : vars;
		options = { parameters: { set: Object.toJSON( set ) }};
		options.onSuccess = function( update, resp ){ 
			
			ajaxscope = (update)? this.up() : this;
			this[ update? "replace": "insert" ]( resp.responseText ); 
		
		}.bind( bind, update );
		
		new Ajax.Request( '/construct.mod', options );
	},
	
	checkscope	: function( condt ) {
		if( typeof ajaxscope == "undefined" )
			cont = $$( condt ).pop()
		
		else {
			cont = ajaxscope.select( condt ).pop();
			delete ajaxscope;
		}
		
		return cont;
	},
	
	gfx			: function(input, target, effect){
		effect = (effect)? effect : { name:'Highlight', options:{startcolor:'#fedb4e', endcolor:'#f9f7f7', restorecolor:'#f9f7f7', duration:1} };
		if(typeof input == "string") $(target).update(input);
		else {
			if(!input.attr.id) input.attr.id = target+"."+effect.name;
			el = elBirth(input.tpe, input.attr, input.cont);
			//el.addClassName('message');
			
			if(input.update) $(target).update(el); else $(target).appendChild(el);
			target = input.attr.id;
		}
		if(effect.name == "Highlight")			new Effect.Highlight(target, effect.options);
		else if (effect.name == "Opacity")		new Effect.Opacity(target, effect.options);
	},
	
	loadModule	: function( modstring ) {
	
		if( typeof window[ xhttp.camelize( modstring ) ]  == "undefined" ) {
			add_header_element ( "script", { src:"/script.mod?single=" + modstring, type:"text/javascript" });
			add_header_element ( "link", { href:"/style.mod?single=" + modstring, type:"text/css", rel:"stylesheet", media:"screen" });
		}
	},
	
	camelize	: function( string ) {
	
		string = "-" + string.replace(/\./, "-" );
		return string.camelize();
	},
	
	tooltip		: function() {
	
		$$( "*[tooltip]" ).each( function( el ){ 
			el.observe( "mouseover", xhttp.invokeTooltipOver.bind( el ) );
			el.observe( "mouseout", xhttp.invokeTooltipOut.bind( el ) );
			 
		});
	},
	
	invokeTooltipOver	: function( event) {
		
		if( event.target.select( '.tooltip' ).length == 0 ) {
			event.target.insert( new Element( 'div', { 'class': 'tooltip active' }).update( $(event.target).readAttribute('tooltip') ).setStyle({ position: 'relative' }));
		} 
	},
	
	invokeTooltipOut	: function( event) {

		if( event.target.select( '.tooltip' ).length != 0 ) {
			event.target.select( '.tooltip' )[ 0 ].remove();
		}
	}
	
}



////// FLOW SOFTENERS (not really pretty, but hey...)
br = "<br />";
tag = function(type, param, content) {
	obj = new Element(type, param);
	if(typeof content == "object") content.each( function(child){ obj.insert(child) }); else obj.update(content);
	return obj;
}

add_header_element = function ( tag, param ) {
	
	
		
		document.write( ( tag == "script" )?
			'<script src="' + param['src'] + '" type="' + param['type'] + '"><\/script>' :
			'<' + tag + ' href="' + param['href'] + '" type="' + param['type'] + '" \/>' 
		);
		
		/*document.getElementsByTagName('head')[0].appendChild(
			new Element( tag, param )
		);*/
		
	
}


////// FORM HANDLERS

gridform	= {

parse		: function(line) {
	tr = new Element('tr');
	if(!line.length) line[0] = [0];
	line.each(function(cell){
		td = new Element('td',{colspan:(cell[2])?cell[2]:grid.am});
		if(cell[0]) {
			attr = {'class':(typeof cell[3] == 'string')?cell[3]:((cell[3])?'req':'')};
			if(['input','button','submit','radio','checkbox','select','multiple'].include(cell[0])) {
				if(['button','submit','radio','checkbox'].include(cell[0]) ) { attr.type = cell[0]; cell[0]='input';
				} else if(cell[0]=='input') attr.type = 'text';
				attr.style='width:'+(cell[2]*grid.w+((cell[2]-1)*14))+'px;';
				attr.id = attr.name = cell[1];
				if(attr.type == "radio") attr.name = cell[4];
				if(attr.type == "radio" || attr.type == "checkbox") attr.style='width:12px;';
				else if(cell[4] == "multiple" && cell[0]=='select') attr.multiple = "multiple";
				else if(cell[4]) attr.value = cell[4];
			}
			
			el = new Element(cell[0],attr);
			if(cell[0]=='select') grid.select[cell[1]].each(function(opt){ el.appendChild(new Element('option',{value:opt[0]}).update(opt[1]?opt[1]:opt[0])) });

			if(['b','i','h2'].include(cell[0])) el.update(cell[1]);
		
			td.appendChild(el);
		} else td.update((cell[1])?cell[1]:'&nbsp;');
		tr.appendChild(td);
	});
	$(grid.form+".tbody").appendChild(tr);
},

confirm		: function(e) {
	error = false;
	$$('input.req').each(function(el) {
		if($(el).hasClassName('err')) $(el).removeClassName('err');
		if($(el).value ===''){
			error = el.id;
			$(el).addClassName('err');
		}
	});
					
	if(error){
		alert('please complete. (in red)');
	} else Query('mod',{trg:grid.query.trg ,mod:'form', wtype:'ajax', lod:grid.query.lod, setid:((grid.query.setid)?grid.query.setid:0) ,form:$(grid.form).serialize(true)});
}

}







function nospam(user) {
	locationstring = "mailto:" + user + "@" + init.ext;
	window.location = locationstring;
}


///// MODULE RELATED FUNCTIONS //////
mod 			= {};

///// MEDIA
mod.media		= {
	album		: function(vars) {
		Object.extend(obj = new Element("div", {id: vars.id+".album", "class":"album"}), mod.media._proto_.album);
		obj.insert(new Element("div",{id:vars.id+".status", "class":"status"}).update("klik..."));
		obj.insert(new Element("div",{"class":"ico"}));
		obj.insert(bar = new Element("div", {"class":"bar"}));
		bar.insert(new Element("div",{id:vars.id+".thumb0", "class":"thumb" }));
		bar.insert(new Element("div",{id:vars.id+".thumb1", "class":"thumb" }));
		obj.insert(control = new Element("div", {"class":"control"}));
		
		control.insert(new Element("div", {id:vars.id+".arright", "class":"arright"}).observe("click", function(e){ this.ancestors()[1].flip(2); }));	
		control.insert(new Element("div", {id:vars.id+".arrleft", "class":"arrleft"}).observe("click", function(e){ this.ancestors()[1].flip(-2); }));
		control.insert(new Element("ul", {id:vars.id+".num", "class":"num"}));
		
		obj.getstring = "&unt=1&lay=1&sze="+vars.sze;
		obj.insert(new Element("div", {"class":"name"}).update(vars.name).observe("click", obj.flip));

		obj.vars	= vars;
		return obj;
	},
	_proto_		: {
		album	: {
			seed	: function(values, obj) {
				if(!obj) obj = this;
				obj.values	= values;
				
				(obj.am = (obj.vars.am<values.length)? obj.vars.am:values.length).times(function(n) {
					$(obj.vars.id+".num").insert(li = new Element("li",{id:obj.vars.id+".n"+n}))
					li.observe("click", obj.show);
				});
				$(obj.vars.id+".thumb0").observe("click", obj.show);
				$(obj.vars.id+".thumb1").observe("click", obj.show);
				
				if(obj.vars.active) {
					obj.n = obj.cur = (obj.vars.random)? (Math.random()*(values.length-2)).round():0;
					tm = setTimeout(function(obj){ obj.show(); }, 1000, obj);  
				} else obj.flip(0);
				
			},
			flip	: function(add, override) {
				obj	= (this.className == "album")? this : this.ancestors()[ (this.ancestors()[1].vars)? 1:((this.ancestors()[2].vars)?2:0)];
				if(!add || typeof add != "number") obj.cur = 0;
				else obj.cur = (obj.cur+add<obj.values.length-1)? ((obj.cur+add>=0)? obj.cur+add : 0) : obj.values.length-2;
				
				$(obj.vars.id+".thumb0").update( new Element("img", {"src":"/engine.room/gfx/img.php?id="+obj.values[obj.cur]['ID']+obj.getstring}) );
				$(obj.vars.id+".thumb0").n = obj.cur;
				$(obj.vars.id+".thumb1").update(new Element("img", {"src":"/engine.room/gfx/img.php?id="+obj.values[obj.cur+1]['ID']+obj.getstring}) );
				$(obj.vars.id+".thumb1").n = obj.cur+1;
				
				span = (obj.cur+obj.am <= obj.values.length)? obj.cur : obj.values.length-obj.am;
				(obj.am).times(function(n) { li = $(obj.vars.id+".n"+n);
					li.update(n+span+1); li.n = span+n;
					if(span+n == obj.active) li.className = "active";
					else if(span+n == obj.cur || span+n == obj.cur+1) li.className = "demi";
					else li.className = "";
				});
				return album;
			},
			show	: function(e) {
				obj	= (this.className == "album")? this : this.ancestors()[ (this.ancestors()[1].vars)? 1:((this.ancestors()[2].vars)?2:0)];
				img		= $(obj.vars.trg).childElements()[0];
				img.src	= "/engine.room/gfx/img.php?sze="+obj.vars.trgsze+"&id="+obj.values[this.n].ID;
				img.observe("load", obj.loaded);
				obj.cur = obj.active = img.n	= this.n; img.refid	= obj.vars.id;
				$(obj.vars.id+".status").update("efkes...");
				obj.flip(1);
			},
			loaded	: function(e) {
				$(this.refid+".status").update((this.n+1)+" van "+$(this.refid+".album").values.length);
			}
		}
	}
} 


ToolTip = function( mod, vars, list )	{

	Object.extend( obj = $$( mod ).pop(), ToolTip.proto );
	
	obj.vars		= vars;
	obj.list		= list;
	obj.elements	= obj.select( vars.elements );
	
	return obj.tooltip();
}



ToolTip.proto =	{

	tooltip			: function() {
	
		this.elements.each( function( el, i ) {

			switch( this.vars.trigger ) {
			
				case 'hover':
					el.observe( 'mouseover', this.trigger.bind( this, el, i, 'mouseover' ));
					el.observe( 'mouseout', this.trigger.bind( this, el, i, 'mouseout' ));
					break;
				
				default:
					el.observe( this.vars.trigger, this.trigger.bind( this, el, i, this.vars.trigger ));
					break;
			}
		}, this );
	},
	

	trigger			: function( el, i, mouseaction ) {
	
		if( !this.list[ i ].content ) {
			xhttp.send( '/xhttp.mod', {
				mod: this.vars.mod,
				action: "tooltip",
				vars: { el: this.list[ i ], what: this.vars.action }
			}, this.pull_response.bind( this, el, i, mouseaction ));
		} else {
			this.select( '.tooltip' ).each( function( elem ) { 
				elem.hide(); 
				
			});
			
			if( el.select( '.tooltip' ).length == 0 ) {
				el.insert( new Element( 'div', { 'class': 'tooltip active' }).update( this.list[ i ].content )).setStyle({ position: 'relative' }).show()
			}
			
			if ( el.select( '.tooltip' ).length > 0 ) {
				el.select( '.tooltip' )[ 0 ].show();
			}		
			
			if( mouseaction == 'mouseout' ) {
				el.select( '.tooltip' )[ 0 ].hide();
			}
		}
		
	},
	
	remove			: function( el, i ) {
	
		if( el.select( '.tooltip' ).length > 0 ) {
			el.select( '.tooltip' )[ 0 ].hide();	
		}
	},
	
	
	pull_response	: function( el, i, mouseaction, response ) {
	
		this.list[ i ].content = response.responseText;
		
		this.select( '.tooltip' ).each( function( elem ) { 
			elem.hide(); 
		});
		
		if( el.select( '.tooltip' ).length == 0 ) {
			el.insert( new Element( 'div', { 'class': 'tooltip active' }).update( this.list[ i ].content )).setStyle({ position: 'relative' }).show()
		}
		
		if ( el.select( '.tooltip' ).length > 0 ) {
			el.select( '.tooltip' )[ 0 ].show();
		}		
		
		if( mouseaction == 'mouseout' ) {
			el.select( '.tooltip' )[ 0 ].hide();
		}

	}
	
	
}


Growl = function( vars )	{

	var style 	= 'growl' + (( vars.style ) ? ' ' + vars.style : '' );		
		
	if( $$( '.growl' )[ 0 ] )
		newbie	= $$( '.growl' ).pop().update( vars.content );	
	else {
		document.body.insert( newbie = new Element( 'div', { id: 'growl', 'class': style }).update( vars.content ).setStyle({ opacity: 0 }));
		new Effect.Appear( newbie, { duration: vars.duration, from: 0.0, to: 1.0, delay: 0 });
	}
	new Effect.Appear( newbie, { duration: vars.duration, from: 1.0, to: 0.0, delay: vars.delay, afterFinish: function() { newbie.remove() }});
}


