var ql;
var LANG = {
	access:{
		denied			: "Sorry, wrong password.",
		success			: "Please wait while the portal is being loaded.",
		countdown		: {
			day		: "day",
			days	: "days"
		}
	},
	msg:{
		namefield		: "Your name...",
		emailfield		: "Your email...",
		textarea		: "Your question...",
		sent_msg		: "Your question is sent.",
		sent_header		: "Thank you",
		type_choose		: "Type of question",
		type_content	: "Content",
		type_technical	: "Technical",
		b_send			: "Send",
		error_question	: "Please enter a question",
		error_type		: "Please enter the type",
		error_header	: "Error",
		sending_msg		: "Your question is being send.",
		sending_header	: "Processing"
	},
	login:{
		sending_msg		: "Your details are processed",
		sending_header	: "Success!",
		sending_error	: 'Sorry, the form can not be send,<br/>please fill in all marked fields'
	},
	poll:{
		thanks			: "Thanks for voting"
	},
	stream:{
		notfound		: "Stream not found."
	},
	language:{
		notfound		: "Language not found."
	},
	loginform:{
		first_name		: "Name",
		middle_name		: "Middle Name",
		last_name		: "Name",	
		company			: "Company",
		"function"		: "Function",		
		email			: "Email",	
		field1			: "Country",		
		field2			: "Field 2",	
		field3			: "Field 3",	
		field4			: "Field 4",	
		field5			: "Field 5",	
		password		: "Password",		
		submit			: "Register"		
	}
};
var client_url = document.location.toString();
client_url = client_url.substring(0,client_url.lastIndexOf('/')+1);
if($type(console)==false||$type(console.log)==false){var console={log:function(){}}}	

var Qlive = new Class({
	portal		:{refresh:null,load_timer:null,online:{},offline:{},timer:null},
	poll		:{holder:null,id:null,voted:[]},
	lastSelectedStream:'',
	message		:{},
	countdown	:{
		timer:null,
		time:0,
		what:''
	},
	popup		:{
		timer:null,
		delay:4000,
		holder:null,
		parent:'h_wrapper'
	},
	initialize:function() {
		this.elMainElement = $('h_qlive2') || $(document.body);
		
		window.alert=function(txt,title) {
			if($type(title)===false) title = "Alert";
			ql.popupmsg(txt,title,true);
		}
		this.comm				= new Request.JSON({
			'url':'./settings/',
			'method':'get',
			'link':'cancel',
			'noCache':true,
			'onSuccess':this.receive.bind(this),
			'onFailure':function(e){
				//console.log("FAILURE",e.status,e);
			}.bind(this),
			'onComplete':function(){
				//console.log("COMPLETE");
				$clear(this.portal.load_timer);
				this.portal.load_timer = this.load.delay(this.portal.refresh,this);
			}.bind(this)
		});
		this.get_static = new Request.JSON({
			'url':'./settings/portal.asp',
			'method':'post',
			'noCache':true,
			'onSuccess':this.set_static.bind(this)
		}).send();

	},
	set_static:function(stat) {
		this.static_settings = stat;
		
		this.GET = $get();

		this.resetVars();

		if(this.GET.register != '' & !this.registered ) {
			var external = $get( "","?"+unescape(this.GET.register));
			external['external']=true;
			this.post(external);
			this.registered = true;
		}
		this.load();
	},
	load:function(){
		
		if(this.GET.logout) {	
			this.outbox.logout=true;
		}

		if($type(this.outbox)!='object')	this.comm.get();
		else {
			//console.log('Send',this.outbox);
			this.comm.send({'data':this.outbox,'url':'./settings/?post=1','method':'post'});
			this.outbox={'log':true};
		}
	},
	post:function(data) {
		var data = new Hash(data);
		if(data.getLength()>0 && $type(this.outbox)!='object' ) this.outbox={};
		this.outbox=data.combine(this.outbox).getClean();
	},
	postnow:function(data) {
		this.post(data);
		this.check_timer(0);
	},
	receive:function(resp) {
		//console.log(resp);
		//console.log('Receive',resp, ' TIME:',new Date().getMinutes()+':'+new Date().getSeconds() );
		if($type(resp)==false) {
			//console.log(this);
			return;
		}
		if($type(resp)=='array') {
			this.personal = resp[0];
			resp = resp[1];
			
			if(this.personal.session) 	this.session = this.personal.session;
			if(this.personal.voted) 	this.poll.voted = this.personal.voted;
			if(this.personal.access)	{
				if(this.personal.access=="denied") 			alert(LANG.access.denied);
				else if(this.personal.access=="success") 	alert(LANG.access.success);				
			}
			
			
		}
		//console.log(resp);
		this.check_timer(resp.portal.refresh);
		this.check_portal(resp.portal);
		if(this.portal.timer == null || resp.portal.delay==0)	var timer = 1;
		else													var timer = resp.portal.delay*1000;
		this.portal.timer = this.set_portal.delay(timer,this,resp);
	},
	resetVars:function() {
		this.first				= true;
		this.player_holder		= null;
		this.player_holder_swf	= null;
		this.slide				= {elements:[],holder:new Element('img')};
		this.player				= {'type':null,'url':null};
		this.meta				= {};
		this.poll.holder		= null;
		this.poll.id			= null;
		this.outbox				= {'log':true,'first':true};
		this.h_pollresults 		= Element('div',{'id':'h_pollresults'});
		this.registered			= false;
		
		this.set_language(this.current_language);
		
		$clear(this.countdowntimer);
		
	},
	set_language:function(lang) {
		
		var ls = [];
		if(this.static_settings && this.static_settings.language) ls = new Hash(this.static_settings.language).getKeys();
		this.current_language = '';
		
		if( $type(lang)!==false && ls.contains(lang.toLowerCase()) ) {
			this.message.state='CHANGED';
			this.current_language = lang.toLowerCase();
		} else if($type(this.static_settings) !== false && $type(this.GET.language)!==false && ls.contains(this.GET.language)   ) {
			this.current_language = this.GET.language;
		} else if( $type(this.static_settings) !== false && $type(this.portal) !== false && ls.contains(this.portal.def_language) ) {
			this.current_language = this.portal.def_language;
		}
		if(this.current_language !== '') {
			ls.each(function(item){
				this.elMainElement.removeClass("LANG_"+item);
			},this);
			LANG=this.static_settings.language[this.current_language];
			this.elMainElement.addClass("LANG_"+this.current_language);
			
			//this.check_messagesender();
		}
	},
	setSession:function(resp) {
		if(!this.session)return;
		for(key in this.session){
			$$('.SESSION_'+key).each(function(e){ e.set('html',trim(this.session[key]));},this);
		}
	},
	set_portal:function(resp) {
		this.check_settings(resp.portal);
		
		if(resp.slide) {
			this.add_slides(resp.slide.all);
			this.set_slide(resp.slide);
		}
		
		this.set_poll(resp.poll);
		
		this.check_player(resp.player);
		
		this.set_tickers();
		
		this.check_meta(resp.meta);
		this.check_showhide(resp.showhide);
		
		this.check_messagesender();
		this.check_countdown();
	},
	check_timer:function(time) {
		if(time<1) 	time = 1;
		time = time * 1000;
		if(time != this.portal.refresh) {
			this.portal.refresh = time;
			//$clear(this.portal.load_timer);
			//this.portal.load_timer = this.load.periodical(this.portal.refresh,this);
		}
	},
	check_portal:function(portal) {
		/*
			for design, add ?page=splash, ?page=live, ?page=end or ?page=login to overrule time and date.
		*/
		
		if($type(this.comm.getHeader("Date"))!==false)	this.servertime = new Date(this.comm.getHeader("Date"));
		else											this.servertime = new Date();
		
		var redir = client_url;
		this.portal.def_language = portal.def_language;
		//console.log(portal.online);
		if(portal.online) {
			
			var pOn = new Date(portal.online.time.replace(/-/g, "/"));
			var pOf = new Date(portal.offline.time.replace(/-/g, "/"));
			
			
			

			if(this.portal.online.time != pOn ) {
				this.portal.online.time = pOn;
			}
			if(this.portal.offline.time != pOf ) {
				this.portal.offline.time = pOf;
			}
			var t_sPage = '';
			if( $type(this.GET.page)!==false ) {
				switch(this.GET.page) {
					case 'splash':	t_sPage=portal.online.page;	break;
					case 'live':	t_sPage=portal.live.page;	break;
					case 'end':		t_sPage=portal.offline.page;	break;					
					case 'login':	t_sPage=portal.access.page;	break;					
				}
			} else {
				if(pOn > this.servertime) 		t_sPage=portal.online.page;
				else if(pOf < this.servertime)	t_sPage=portal.offline.page;
				else							t_sPage=portal.live.page;
			}
		} else {
			t_sPage=portal.access.page;

		}
		redir+=t_sPage;
		
		if(redir != this.portal.content) {
			this.resetVars();
			this.portal.content = redir;

			var page = new Request.HTML({'url':redir,'async':false,'link':'chain',onSuccess:function(tree){
				this.elMainElement.empty().adopt(tree);
				window.fireEvent('qliveready');
				this.set_tabs();
				$(document.body).set('class',t_sPage.replace('.asp',''));
				this.check_loginform();
			}.bind(this)}).get();
		}
		this.setSession();

	},
	check_settings:function(portal) {
		if(portal.language != this.portal.language) {
			this.portal.language = portal.language;
		}
		if(portal.name != this.portal.name) {
			this.portal.name = portal.name;
			document.title=portal.name;
		}
		
		
	},
	check_loginform:function() {
		if(this.portal.def_language && this.static_settings && this.current_language) {
			var loginW = new LoginWindow('Qlogin',this.static_settings.loginform);		
			window.fireEvent('loginwindowready');
		}
	},
	add_slides:function(slides) {
		var sl = [];
		
		var l = (this.portal.def_language==this.current_language? '' : this.current_language+'/');
		
		slides.each(function(item){
			sl.push(client_url+'slides/'+l+item);
		})
		this.slide.elements.each(function(item,x){
			if(sl.indexOf(item.get('src'))>=0) {
				sl.erase(item.get('src'));
			}
		});
		this.slide.elements.combine(Asset.images(sl));
	},
	set_slide:function(slide) {
		if(!$('Qslides')) return;
		if( !$('Qslides').hasChild(this.slide.holder) ) $('Qslides').adopt([this.slide.holder]);		
		
		var l = (this.portal.def_language==this.current_language? '' : this.current_language+'/');
		
		this.slide.active = client_url+'slides/'+l+slide.active;
		if(this.slide.holder.get('src')!=this.slide.active) this.slide.holder.set('src',this.slide.active);
	},
	set_poll:function(poll) {
		if(!$('Qpoll')) return;
		if(!poll) return;
		this.poll.holder = $('Qpoll');
		if($type(poll.poll_id)==false) this.poll.holder.empty();
		
		
		this.h_pollresults.empty();
		
		if(this.poll.id != poll.poll_id) {
			this.poll.id = poll.poll_id;
			this.poll.holder.empty();
			if(this.poll.id == 0) return;
			var polloptions = [];
			
			//this.poll.holder.adopt();//	<iframe "></iframe>
			poll.poll_options.each(function(item,x){
				polloptions.push(
					Element('a',{'href':'#','class':'poll_option'}).addEvent('click',function(e){
						e.target.getParent().getChildren().each(function(opt,i){
							opt.addClass( 		opt==e.target?'chosen':'notchosen' );
							opt.removeClass( 	opt!=e.target?'chosen':'notchosen' );
						},this);
						this.poll_vote(this.poll.id,item.polloption_id);
						return false;
					}.bind(this) ).adopt(Element('span',{'html':item.polloption_name}))
				)
			},this);
			
			
			var ph = Element('div',{'class':'poll_holder'}).inject(this.poll.holder);
			
			if(Browser.Engine.trident === true && Browser.Engine.version ==4) ph.adopt(Element('iframe',{'class':'ieiframehack'}));
			
			ph.adopt(Element('div',{'class':'poll_holder2'}).adopt([
					Element('div',{'class':'poll_name','html':poll.poll_name}),
					Element('div',{'class':'poll_description','html':poll.poll_description}),
					Element('div',{'class':'poll_options'}).adopt(polloptions)
				])
			);
			
			this.poll.poll_name = poll.poll_name;
		}
		if(this.poll.voted.contains(poll.poll_id)) {
			this.poll_thanks();
			if(poll.result)	this.h_pollresults.adopt( pollLayout.createGraph(poll.result,false) );
		}
	},
	poll_vote:function(poll_id,polloption_id) {
		this.postnow({
			polloption_id:polloption_id,
			poll_id:poll_id
		});
		this.poll.voted.push(poll_id);
		this.poll_thanks();		
	},
	poll_thanks:function() {
		this.poll.holder.empty();
		
		
		var ph = Element('div',{'class':'poll_holder thanks'}).inject(this.poll.holder);

		if(Browser.Engine.trident === true && Browser.Engine.version ==4) ph.adopt(Element('iframe',{'class':'ieiframehack'}));
		ph.adopt(Element('div',{'class':'poll_holder2'}).adopt([
			Element('div',{'html':this.poll.poll_name,'class':'poll_name'}),
			Element('div',{'html':LANG.poll.thanks,'class':'poll_thanks'}),
			this.h_pollresults
		]));	

	},
	check_player:function(player) {

		this.player = new Hash(player);
		if(!$('Qplayer')) return;
		this.player_holder = $('Qplayer');
		
		var tplayer = new Hash(player).erase('streamsources').erase('type');
		var tmp = new Hash(this.player).erase('streamsources').erase('type');

		if(this.player_holder.getChildren().length > 0	&& tplayer.toQueryString() == tmp.toQueryString()) return;
		
		this.pWidth = this.player_holder.getSize().x;
		this.pHeight = this.player_holder.getSize().y;
		//this.player = new Hash(player);
		this.set_player();
	},
	set_player:function(pOpts,pType){
		
//		var base_streamsource = (pOpts && pOpts.base_streamsource?pOpts.base_streamsource:this.player.base_streamsource);
		if(pOpts && pOpts.base_streamsource) this.lastSelectedStream = pOpts.base_streamsource;
		
		var base_streamsource = ( (this.lastSelectedStream == '') ? this.player.base_streamsource : this.lastSelectedStream );
		
		this.lastSelectedStream = base_streamsource;
		
		if(!this.player_holder) return;
		
		this.pWidth = '100%';
		this.pHeight = '100%';
	
		//console.log(this.player);
		
		//if(pType) this.player.type = pType;
		//console.log("base_streamsource",base_streamsource.substr(0,6)=='mms://');
		//console.log(this.player);
		this.player.type = 'flash';
		if((base_streamsource.substr(0,6)=='mms://') || base_streamsource.substr(0,7)=='http://') this.player.type = 'wmv';
		this.player_holder.empty();
		if(this.player.type == 'flash') {
			var pf = new Hash({"stream_id":base_streamsource}).combine(this.player.flashvars);//.getClean();
			var pp = new Hash({"menu":"true","allowscriptaccess":"always"}).combine(this.player.params);//.getClean();
			//var pa = new Hash({}).combine(this.player.attributes);//.getClean();
			//this.player_holder_swf = swfobject.embedSWF(this.player.player, this.player_holder.get('id'), 512, 288, "9.0.0", "../_core/_flash/expressInstall.swf",pf,pp,pa);
			var so = new SWFObject(this.player.player, this.player_holder.get('id')+'_object', this.pWidth, this.pHeight, "9", "#000");
			so.useExpressInstall('../_core/_flash/expressinstall.swf');
			pf.each(function(value,key){so.addVariable(key,value)},this);
			pp.each(function(value,key){so.addParam(key,value)},this);
			//pa.each(function(value,key){so.addAttribute(key,value)},this);

			//The live player can send a small log via the livelogger script on bugtrack.quadiatv.com .
			//In order to track which user sends which log, an email address is added to the flashvars.
			//Author: Felix van Geuns - 2010-07-16
			if(this.session["email"])
			{
				so.addVariable('user_email',this.session["email"]);
			}
			
			so.write(this.player_holder.get('id'));
		} else if(this.player.type == 'wmv') {
			this.player_holder.set('html',
				//'<OBJECT ID="'+this.player_holder.get('id')+'_object'+'" CLASSID="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95" STANDBY="Loading Windows Media Player components..." TYPE="application/x-oleobject"	WIDTH="'+this.pWidth+'" HEIGHT="'+this.pHeight+'"><PARAM NAME="FileName" VALUE="'+base_streamsource+'"><PARAM name="ShowControls" VALUE="true"><PARAM name="ShowStatusBar" value="false"><PARAM name="ShowDisplay" VALUE="false"><PARAM name="autostart" VALUE="true"><PARAM name="uiMode" VALUE="none"><PARAM name="stretchToFit" value="true"><param name="scale" value="ToFit"><param name="transparentatStart" value="true"><embed type="application/x-mplayer2" name="MediaPlayer" src="'+base_streamsource+'" ShowControls="1" showtracker="0" showdisplay="0" showstatusbar="1" controller="false" kioskmode="false" autostart="1" autoplay="true" scale="ToFit" width="'+this.pWidth+'" height="'+this.pHeight+'" ></embed></OBJECT>'
				//'<OBJECT ID="'+this.player_holder.get('id')+'_object'+'" name="'+this.player_holder.get('id')+'_object'+'" CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" STANDBY="Loading Windows Media Player components..." TYPE="application/x-oleobject"	WIDTH="'+this.pWidth+'" HEIGHT="'+this.pHeight+'"><PARAM NAME="FileName" VALUE="'+base_streamsource+'"><PARAM name="ShowControls" VALUE="true"><PARAM name="ShowStatusBar" value="true"><PARAM name="ShowDisplay" VALUE="false"><PARAM name="autostart" VALUE="true"><PARAM name="uiMode" VALUE="none"><PARAM name="stretchToFit" value="true"><param name="scale" value="ToFit"><param name="transparentatStart" value="true"><embed type="application/x-mplayer2" name="MediaPlayer" src="'+base_streamsource+'" ShowControls="1" showdisplay="0" showstatusbar="1" controller="true" kioskmode="false" autostart="1" autoplay="true" scale="ToFit" width="'+this.pWidth+'" height="'+this.pHeight+'" ></embed></OBJECT>'

				'<object classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6" width="'+this.pWidth+'" height="'+this.pHeight+'" id="'+this.player_holder.get('id')+'_object'+'" name="'+this.player_holder.get('id')+'_object'+'">'+
				'<param name="URL" ref value="'+base_streamsource+'">'+
				'<param name="rate" value="1">'+
				'<param name="autoStart" value="-1">'+
				'<param name="uiMode" value="none">'+
				/*'<param name="balance" value="0">'+
				'<param name="currentPosition" value="0">'+
				'<param name="defaultFrame" value>'+
				'<param name="playCount" value="1">'+
				'<param name="currentMarker" value="0">'+
				'<param name="invokeURLs" value="-1">'+
				'<param name="baseURL" value>'+
				'<param name="volume" value="51">'+
				'<param name="mute" value="0">'+
				'<param name="stretchToFit" value="-1">'+
				'<param name="windowlessVideo" value="-1">'+
				'<param name="enabled" value="-1">'+
				'<param name="enableContextMenu" value="-1">'+
				'<param name="fullScreen" value="0">'+
				'<param name="SAMIStyle" value>'+
				'<param name="SAMILang" value>'+
				'<param name="SAMIFilename" value>'+
				'<param name="captioningID" value>'+
				'<param name="enableErrorDialogs" value="0">'+
				'<param name="_cx" value="4498">'+
				'<param name="_cy" value="3625">'+
				*/	'<embed type="application/x-mplayer2" '+
						'src="'+base_streamsource+'" '+
						'ShowControls="0" '+
						'showtracker="0" '+
						'showdisplay="0" '+
						'showstatusbar="1" '+
						'controller="false" '+
						'kioskmode="false" '+
						'autostart="1" '+
						'autoplay="true" '+
						'scale="ToFit" '+
						'width="'+this.pWidth+'" '+
						'height="'+this.pHeight+'" >'+
					'</embed>'+
				'</object>'

			);			
		}
		
	},
	check_meta:function(meta) {
		for(var i in meta) {
			if(!(el = $(i))) continue;
			//if(!(el = this.getFlashMovie(i))) continue;
			
			//if(el.get && el.get("flashvars") != '' ) alert(el.get("flashvars"));
			if($type(this.meta[i])==false || this.meta[i] != meta[i]) {
				var pos = 0;
				var tag = i.split(",");
				if(tag[1]) pos = tag[1]-1;
				tag = tag[0];
				if($$(tag)[pos]) el = $$(tag)[pos];
				this.meta[i] = meta[i];
				if(el.set) el.set('html',meta[i]);
				
			}
		}
	},
	check_showhide:function(showhide) {
		for(var i in showhide) {
			if($(i)) $(i).setStyle('display',(showhide[i]?"block":"none") );
		}
	},
	check_messagesender:function() {
		
		if(!$('Qmessage')) {	
			this.message.state = null;
			return;
		}
		this.message.holder = $('Qmessage');

		this.message.standardTxt = LANG.msg.textarea;
		
		
		if(!this.message.form) this.message.form = Element('div',{'class':'msg_form'});

		if(!this.message.holder.hasChild(this.message.form)) this.message.holder.adopt(this.message.form);
		
		if(this.message.state == 'sending') {
			this.popupmsg(LANG.msg.sent_msg,LANG.msg.sent_header);	
			this.message.state == 'sent'
		}

		if(this.message.state != 'form' || $type(this.message.el.msg)==false || !$('Qmessage').hasChild(this.message.el.msg) ) {

			this.message.el = {
				'name' : Element('input',{'value':LANG.msg.namefield,'id':'MSG_name'}).addEvents({
					'focus':function(e){	if(e.target.value==LANG.msg.namefield)e.target.value='';	}.bind(this),
					'blur':	function(e){	if(e.target.value=='') e.target.value=LANG.msg.namefield;}.bind(this)
				}),
				'email' : Element('input',{'value':LANG.msg.emailfield,'id':'MSG_email'}).addEvents({
					'focus':function(e){	if(e.target.value==LANG.msg.emailfield)e.target.value='';	}.bind(this),
					'blur':	function(e){	if(e.target.value=='') e.target.value=LANG.msg.emailfield;}.bind(this)
				}),
				'msg' : Element('textarea',{'html':this.message.standardTxt,'id':'MSG_msg'}).addEvents({
					'focus':function(e){	if(e.target.value==this.message.standardTxt)e.target.value='';	}.bind(this),
					'blur':	function(e){	if(e.target.value=='') e.target.value=this.message.standardTxt;}.bind(this)
				}),
				'type':	Element('select',{'id':'MSG_type'}).adopt([
					Element('option',{'html':LANG.msg.type_choose,'value':''}),
					Element('option',{'html':LANG.msg.type_content,'value':'content'}),
					Element('option',{'html':LANG.msg.type_technical,'value':'technical'})
				]),
				'send' : Element('input',{'type':'button','id':'MSG_submit','class':'button','value':LANG.msg.b_send}).addEvent('click', this.send_message.bind(this))
			};
			this.message.form.empty().adopt([this.message.el.name,this.message.el.email,this.message.el.msg, this.message.el.type, this.message.el.send]);
			this.message.form.set('class','msg_form form');
			this.message.state = 'form';
		}
	},
	send_message:function(){
		if( this.message.el.msg.value == ''  || this.message.el.msg.value == this.message.el.msg.defaultValue )	{	this.popupmsg(LANG.msg.error_question,LANG.msg.error_header);	return; }		
		if( this.message.el.type.value == '' )	{	this.popupmsg(LANG.msg.error_type,LANG.msg.error_header);		return; }
		
		var msg_value = this.message.el.msg.value;
		msg_value = msg_value.replace(/"/g,'&quot;');
		msg_value = msg_value.replace(/\n/g,'<br/>');
		var t_aPost = {}
		if(this.message.el.name.value != '')	t_aPost['msg_name'] = this.message.el.name.value;
		if(this.message.el.email.value != '')	t_aPost['msg_email'] = this.message.el.email.value;
		
		t_aPost['msg_value']	= msg_value;
		t_aPost['msg_type']		= this.message.el.type.value;

		this.post(t_aPost);
		this.message.form.set('class','msg_form sending');
		this.message.state = 'sending';
		this.add_popupmsg(LANG.msg.sending_msg,LANG.msg.sending_header);	

	},
	remove_popupmsg:function(){
		$clear(this.popup.timer);
		var exists = ($type(this.popup.holder) !== false);
		if(exists) this.popup.holder.destroy();
		return exists;
	},
	add_popupmsg:function(msg,title,closebutton){
		var exists = this.remove_popupmsg();
		var parent='';
		if(!(parent = $(this.popup.parent))) {
			parent = this.elMainElement;
		}
		
		this.popup.holder = Element('div',{'id':'popup'}).adopt(
			Element('div',{'class':'pu_position'}).adopt(
				Element('div',{'class':'pu_container'}).adopt(
					Element('div',{'class':'pu_container2'}).adopt(
						Element('div',{'class':'pu_content'}).adopt([
							Element('div',{'class':'pu_header','html':title}).adopt(Element('div',{'class':'b_close','html':'X'}).addEvent('click',function(){this.remove_popupmsg();}.bind(this))),
							Element('div',{'class':'pu_txt','html':msg}),
						])
					)
				)
			)
		).setStyle('opacity',0);
		
		parent.adopt(this.popup.holder);
		this.popup.holder.fade(exists?'show':1);
	},
	popupmsg:function(msg,title,closebutton){ 
		this.add_popupmsg(msg,title,closebutton);
		this.popup.timer = this.remove_popupmsg.delay(this.popup.delay,this);
	},
	check_countdown:function() {
		if(!$('Qcountdown')) return;
		//console.log("PORTA:",this.portal);
		if( ! (this.portal.online.time)&&(this.portal.offline.time) ) return;
		
		var countdown=0;
		//this.servertime = new Date(this.comm.getHeader("Date"));
		
		if(this.servertime < this.portal.online.time) {
			this.countdown.what = "start";
			this.countdown.time = (this.portal.online.time.getTime() - this.servertime.getTime())/1000;
		} else if(this.servertime > this.portal.online.time && this.servertime < this.portal.offline.time) {
			this.countdown.what = "end";
			this.countdown.time = (this.portal.offline.time.getTime() - this.servertime.getTime())/1000;
		} else {
			this.countdown.what = "finished";
			this.countdown.time = (this.servertime.getTime()-this.portal.offline.time.getTime())/1000;
		}
		
		$clear(this.countdown.timer);
		this.update_countdown();
		this.countdown.timer = this.update_countdown.periodical(1000,this);
		
	},
	update_countdown:function() {
		if(!$('Qcountdown')) {
			$clear(this.countdown.timer);
			return;
		}
		$('Qcountdown').set('html',sec_to_time(this.countdown.time));
		if(this.countdown.what=='finished')	this.countdown.time++;	
		else								this.countdown.time--;	
	},
	set_tabs:function() {
		//console.log("TAB",$$('.Qtabs'));
		var Qtabs = $$('.Qtabs');
		if( Qtabs.length <= 0 ) return;
		
		Qtabs.each(function(Qtab,y){
			var tabs = Qtab.getChildren(".tab_head");
			var cont = Qtab.getChildren(".tab_content");
			
			var tabs_holder = Element('div',{'class':'Qtabs_h_head'});
			var tabs_content = Element('div',{'class':'content'});
			var tabs_hider = Element('div',{'style':'display:none;'});
			
			
			tabs.each(function(item,x){
				item.addEvent('click',function(e){
					tabs.each(function(item){item.removeClass('selected')})
					item.addClass('selected');
			
					cont.each(function(item,x){item.inject(tabs_hider);});
					tabs_content.adopt(cont[x]);
	
					return false;
				});	
				if(item.hasClass('selected')) item.fireEvent('click');
			});
			
			tabs_holder.adopt(tabs);
			Qtab.empty().adopt([
				tabs_holder,
				Element('div',{'class':'Qtabs_h_content'}).adopt(tabs_content),
				tabs_hider
			]);
		});		
	},
	set_tickers:function() {
		var Qticks = $$('.Qticker');
		if( Qticks.length <= 0 ) return;
		
		Qticks.each(function(Qtick,y){
			var size = Qtick.getSize();
			
			var TickId = Qtick.get('id');
			var so = new SWFObject("../_core/_flash/qlive2ticker_as3.swf", TickId, size.x, size.y, "9", Qtick.getStyle('background-color'));
			
			var settings = JSON.decode(trim(Qtick.get('html')));
			var pf = new Hash(settings)
				.each(function(value,key){so.addVariable(key,value)},this);
			
			var pp = new Hash({
				"wmode":"opaque",
				"allowScriptAccess":"always",
				"name":TickId
			}).each(function(value,key){so.addParam(key,value)},this);
				
			Qtick.set('id',TickId+'1');
			
			Element('div',{'html':so.getSWFHTML()}).inject(Qtick,'after');
			
			Qtick.dispose();
						
		});

	}
});



var LoginWindow = new Class({
	mask:{
		email:/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
	},
	initialize:function(holder,field_info) {
		if(!(this.holder = $(holder)) || this.holder.getChildren().length>0) return false;
		
		this.holder.addEvent('submit',function(){
			this.login();
			return false;
		 }.bind(this));
		 
		//if(this.holder.get('tag')!='form') alert("Qlogin is not a form!!!");
		
		this.field_info = field_info;
		this.createFields();
		this.addActions();
	},
	createFields:function() {
		for(i in this.field_info) {
			if(this.field_info[i].show===false)continue;
			
			if($type(LANG.loginform[i])=="string")	LANG.loginform[i]={value: LANG.loginform[i]};
			
			this.field_info[i]['container'] = Element('div',{'class':'h_field '+i});
			
			var id = "field_"+i;
			
			if(this.field_info[i].label && this.field_info[i].label == true) {
				this.field_info[i].value = '';
				this.field_info[i]['elLabel'] = Element('label',{'for':id,'html':LANG.loginform[i].value,'id':"label_"+i});
			} else {
				this.field_info[i].value = LANG.loginform[i].value;
			}
			
			switch(this.field_info[i].type) {
				case 'text':
				case 'password':
					this.field_info[i]['el'] = Element("input",{'type':'text','id':id,'name':i,'value':this.field_info[i].value});
				break;
				case 'select':
					this.field_info[i]['el'] = Element("select",{'id':id,'name':i,'value':this.field_info[i].value});
					for(j in this.field_info[i].values) {
						this.field_info[i]['el'].adopt(Element('option',{'value':j, 'html':this.field_info[i].values[j] }));
					}
				break;
				case 'submit':
					this.field_info[i]['el'] = Element("input",{'type':'submit','class':'button','id':id,'name':i,'value':this.field_info[i].value});
				break;
				case 'radio':
					this.field_info[i]['el'] = Element('div',{'class':'h_field_radio','id':id});
					if(LANG.loginform[i].values) {
						LANG.loginform[i].values.each(function(radiovalue,r){ this.field_info[i]['el'].adopt([
							Element('label',{'for':i+'_radio'+r,'html':radiovalue }),
							Element('input',{'type':'radio','class':'radio','name':i,'value':radiovalue,'id':i+'_radio'+r})
						]) },this);
					}
				break;
				case 'checkbox':
					this.field_info[i]['el'] = Element('input',{'type':'checkbox','class':'checkbox','id':id,'name':i,'value':LANG.loginform[i].value.stripTags()})
				break;
				case "multiselect":
					this.field_info[i]['el'] = Element('div',{'class':'h_field_multiselect','id':id});
					if(LANG.loginform[i].values) {
						var count = 0;
						$H(LANG.loginform[i].values).each(function(radiovalue,r){ this.field_info[i]['el'].adopt(Element('div').adopt([
							Element('label',{'for':i+'_multiselect'+count,'html':radiovalue }),
							Element('input',{'type':'checkbox','class':'radio','name':i+'[]','value':r,'id':i+'_multiselect'+count})
						]));
						count++;
						},this);
					}
				break;
			}
			
			
			if(this.field_info[i]['elLabel']) {
				this.field_info[i]['container'].adopt([
					this.field_info[i]['elLabel'],
					this.field_info[i]['el']
				]);
			} else {
				this.field_info[i]['container'].adopt(this.field_info[i]['el']);
			}
			this.holder.adopt(this.field_info[i]['container']);
		}
		this.holder.adopt(Element('div',{'class':'h_field footer'}));
	},	
	addActions:function(){
		for(i in this.field_info) {
			if($type(this.field_info[i]['el'])===false)continue;
			this.field_info[i]['el'].addEvent('keyup',function(e){this.check_value(e.target.get('name'));}.bind(this));
			this.field_info[i]['el'].addEvent('blur',function(e){this.check_value(e.target.get('name'));}.bind(this));
			
			//console.log("addactions",i,this.field_info[i].type);
			switch(this.field_info[i].type) {
				case 'text':
					this.field_info[i]['el'].addEvents({
						'focus':function(e){	if(this.el.value==this.value) this.el.value=''; }.bind(this.field_info[i]),
						'blur':function(e){		if(this.el.value=='') this.el.value = this.value; }.bind(this.field_info[i])
					});
				break;
				case 'submit':
					
					this.field_info[i]['el'].addEvent('click',function(e){ this.login(); }.bind(this));
				break;
				case 'password':
					this.field_info[i]['el'].addEvent('focus',function(e){	
						if(this.el.value==this.value) {
							this['el3'] = this['el'];
							this['el'] = this['el2'];
							this['el2']= this['el3'];
							
							this['el2'].setStyle('display','none');
							this['el'].setStyle('display','block').set('value','').focus();
						}
					}.bind(this.field_info[i]));
					
					this.field_info[i]['el2'] = Element('input',{'type':'password'}).setStyle('display','none').inject(this.field_info[i]['el'],'after').addEvent('blur',function(e){
						this['el2'].value=this['el'].value;
						if(this.el.value=='') {
							this['el3'] = this['el'];
							this['el'] = this['el2'];
							this['el2']= this['el3'];

							this['el2'].setStyle('display','none');
							this['el'].setStyle('display','block').set('value',this.value);
						}
						
					}.bind(this.field_info[i]));
					
				break;
				
			}
		}	
	},
	login:function(){//Qaccess();
		if(this.check_all_values()) {
			alert(LANG.login.sending_msg,LANG.login.sending_header);
			Qaccess();
		} else {
			alert(LANG.login.sending_error);		
		}
	},
	check_value:function(name) {
		//console.log("CHECK",name,this.field_info[name], this.field_info[name].el.type)
		if(this.field_info[name].notempty===true) {
			switch(this.field_info[name].type) {
				case 'checkbox':
					if(!(this.field_info[name].el.checked)) return this.flagError(name);
				break;
				case 'radio':
					
					var isEmpty = true;
					this.field_info[name].el.getElements('input').each(function(raditem){
						if(raditem.checked) isEmpty=false;
					})
					if(isEmpty)	return this.flagError(name);
				break;
				default:
					if( (this.field_info[name].el.value==='' || this.field_info[name].el.value===this.field_info[name].value) )	return this.flagError(name);
				break
			}
		}
		
		
		if($type(this.field_info[name].mask)!==false && !(this.mask[this.field_info[name].mask].test(this.field_info[name].el.value))  )					return this.flagError(name);
		
		this.clearError(name);
		return true;
	},
	check_all_values:function() {
		errors=false;
		for(i in this.field_info) {
			if(this.field_info[i]['el']) this.field_info[i].valid = this.check_value(i);
			if(this.field_info[i].valid===false) errors=true;
		}
		return (!errors)
	},
	flagError:function(id) {
		//this.field_info[id].el.addClass('error');
		this.field_info[id].container.addClass('error');
		return false;
	},
	clearError:function(id) {
		this.field_info[id].container.removeClass('error');
	}
});






var Qaccess = function() {
	var out = new Hash();
	var fields = ['first_name','middle_name','last_name','company','function','email','username','password','field1','field2','field3','field4','field5'];
	
	for(x=0;x<$("Qlogin").elements.length;x++){
		//console.log(x, $("Qlogin").elements[x]  );
		if(!( el= $($("Qlogin").elements[x]) )) continue;
		elname = el.name;
		elarray = (elname.contains("[]"));
		if(elarray) elname = elname.replace("[]","");
		
		if(!(fields.contains(elname))) continue;
		switch(el.type) {
			case "text":
				if(elarray)	{
					if($type(out[elname])==false) out[elname] = '';
					out[elname] += "|"+el.value;
				} else		out[elname] = el.value;
			break;
			case "checkbox":
			case "radio":
				//console.log(elname,el.type);
				if(el.checked) {
					if(elarray)	{
						if($type(out[elname])==false) out[elname] = '';
						out[elname] += "|"+el.value;
					} else		out[elname] = el.value;
				}
			break;
		}
	}
	//console.log(out.getClean());
	if(out.getLength()>0) {
		ql.postnow(out.getClean());
	}
}
var Qlogout = function() {
	ql.postnow({'logout':true})
}
var Quser = function(what) {
	switch(what) {
		case 'first_name':case 'middle_name':case 'last_name':case 'company':case 'function':case 'email':case 'username':case 'password':case 'field1':case 'field2':case 'field3':case 'field4':case 'field5':
			if(ql.session[what]) return (ql.session[what]);
		break;
	}
}
var QSwitchStream = function(stream) {
	if($type(ql.player.streamsources[stream])!==false) {
		ql.set_player({'base_streamsource':ql.player.streamsources[stream]});
	} else	alert(LANG.stream.notfound);
	return false;
}
var QSwitchLanguage = function(lang) {
	ql.set_language(lang);
}

var QgetTickerText = function(tickerid) {
	var output = "";
	if($type(ql.meta[tickerid]) == "string")	output = ql.meta[tickerid];
	else										output = "LEEG";
	return output;
}

function $get(key,url){  
    if(arguments.length < 2) url =location.href;  
    if(arguments.length > 0 && key != ""){  
        if(key == "#"){  
            var regex = new RegExp("[#]([^$]*)");  
        } else if(key == "?"){  
            var regex = new RegExp("[?]([^#$]*)");  
        } else {  
            var regex = new RegExp("[?&]"+key+"=([^&#]*)");  
        }  
        var results = regex.exec(url);  
        return (results == null )? "" : results[1];  
    } else {  
        url = url.split("?");
        var results = {};  
            if(url.length > 1){  
                url = url[1].split("#");  
                if(url.length > 1) results["hash"] = url[1];  
                url[0].split("&").each(function(item,index){  
                    item = item.split("=");  
                    results[item[0]] = item[1];  
                });  
            }  
        return results;  
    }  
}  

function sec_to_time(time){
	time = Math.round(time);
	var neg = false;
	if(time<0) {
		time = -1*time;
		neg = true;
	}
	
	
	word_day = '<i class="LANG_en">day</i><i class="LANG_nl">dag</i>';
	word_days = '<i class="LANG_en">days</i><i class="LANG_nl">dagen</i>';
	if(LANG.access.countdown) {
		if(LANG.access.countdown.day) word_day = LANG.access.countdown.day;
		if(LANG.access.countdown.days) word_days = LANG.access.countdown.days;
	}
	
	days		= Math.floor(time/(24*60*60));
	days		= (days != 0 ? days+' '+(days==1?word_day:word_days)+' ' : '');
	remaintime 	= time%(24*60*60);
	hrs			= cal_pad(Math.floor(remaintime/(60*60)));
	remaintime 	= remaintime%(60*60);
	min			= cal_pad(Math.floor(remaintime/60));
	sec			= cal_pad(remaintime%60);
	output = (neg?'-':'')+days+hrs+":"+min+":"+sec;
	return output;
}
function cal_pad(value) {
	value = '0'+value;
	value = value.substr(value.length-2,2);
	return value;
}
var pollLayout={
	createTable:function(res) {
		var output=[['Option','Votes','Percentage']];
		for(var i in res) {
			output.push([i,res[i].no,res[i].perc]);
		}
		return makeTable(output,{'class':'pollresults'});
	},
	createGraph:function(res,horizontal) {
		var graph=Element('div',{'class':'h_graph'});
		var count=1;
		for(var i in res) {
			graph.adopt([
				Element('div',{'class':'h_column'}).adopt([
					Element('div',{'class':'h_columnbar column'+(count++)+'','style':(horizontal?'height':'width')+':'+res[i].perc+'%'}),
					Element('div',{'class':'h_columntitle','html':i}),
					Element('div',{'class':'h_columnvalue','html':res[i].perc+'%'})
				])
			]);
		};
		return graph;
	}
};
function trim(str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}

function openHelp() {
 window.open('./help.asp','help','width=550,height=480,scrollbars=yes,resizable=no,toolbar=no,directories=no,status=no,menubar=no');
 return false;
}

function openEval() {
 window.open('./evaluate.asp','Evaluatie','width=655,height=630,scrollbars=yes,resizable=no,toolbar=no,directories=no,status=no,menubar=no');
 return false;
}




window.addEvent('domready',function(){
	ql = new Qlive();	
});



