<!--
// pre Load, scriptaculous style!
if (window['loadFirebugConsole']) {
	window.loadFirebugConsole();
} else {
	if (!window['console']) {
		window.console = {};
		window.console.info = alert;
		window.console.log = alert;
		window.console.warn = alert;
		window.console.error = alert;
	}
}
// language construct quick-n-dirty 
function langsw(nltxt,entxt) {
	if (viidoo_language=='en') {
		return entxt;
	}
	return nltxt;
}

var ajaxObjects = new Array();

function asyncReq(url,el) {
	if ( isDefined(el) ) {
		reqobj = new Ajax.Updater( el, url ,{
			method: 'post'
			,asynchronous:true
			,evalScripts:true
		});
	}
	else {
		reqobj = new Ajax.Request( url, {
			method: 'post'
			,asynchronous:true
			,evalScripts:true
		});
	}
	
	return reqobj;
}

function syncReq(url,el) {
	if ( isDefined(el) ) {
		reqobj = new Ajax.Updater( el, url ,{
			method: 'post'
			,asynchronous:false
			,evalScripts:true
		});
	}
	else {
		reqobj = new Ajax.Request( url, {
			method: 'post'
			,asynchronous:false
			,evalScripts:true
		});
	}
	
	return reqobj;
}

function spinAsyncReq(url,el) {
	if ( isDefined(el) ) {
		fillSpinner(el);
		reqobj = new Ajax.Updater( el, url ,{
			method: 'post'
			,asynchronous:true
			,evalScripts:true
		});
	}
	else {
		reqobj = new Ajax.Request( url, {
			method: 'post'
			,asynchronous:true
			,evalScripts:true
		});
	}
	
	return reqobj;
}

// Prototype extensions

/*Ajax.Request.prototype.abort = function() {
    // prevent and state change callbacks from being issued
    this.transport.onreadystatechange = Prototype.emptyFunction;
    // abort the XHR
    this.transport.abort();
    // set status to failure
    this.aborted = true;
    // update the request counter
    if ( Ajax.activeRequestCount - 1 >= 0 )
    	Ajax.activeRequestCount--;
};*/

Ajax.Updater = Class.create(Ajax.Request, {
  initialize: function($super, container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    };
	
	this.url = url;
	this.aborted = false;
	
    options = Object.clone(options);
    var onComplete = options.onComplete;
    options.onComplete = (function(response, json) {
      if ( !this.aborted )
      	this.updateContent(response.responseText);
      if (Object.isFunction(onComplete)) onComplete(response, json);
    }).bind(this);

    $super(url, options);
  },
  
  abort: function() {
  	this.aborted = true;
  	//console.log(this.url+':: state: '+this.aborted);
  },
  
  updateContent: function(responseText) {
    var receiver = this.container[this.success() ? 'success' : 'failure'],
        options = this.options;

    if (!options.evalScripts) responseText = responseText.stripScripts();

    if (receiver = $(receiver)) {
      if (options.insertion) {
        if (Object.isString(options.insertion)) {
          var insertion = { }; insertion[options.insertion] = responseText;
          receiver.insert(insertion);
        }
        else options.insertion(receiver, responseText);
      }
      else receiver.update(responseText);
    }
  }
});

function abortAllRequests() {
	if ( ajaxObjects.size() < 1 )
		return;
	for (var iter in ajaxObjects )
		ajaxObjects[0].abort();
	
	ajaxObjects = new Array();
}

function full_escape(string) {
	//return encodeURIComponent(url);	// forgets to encode a lot of chars. Useless
	var s = escape(string);	// this is javascript's most complete one, however forgets to encode star, slash, @ and +
	s = s.replace(/\*/g,"%2A");
	s = s.replace(/\//g,"%2F");
	s = s.replace(/\@/g,"%40");
	s = s.replace(/\+/g,"%2B");
	return s;
}

function allResults(url,el) {
	var scrollTo = $('advanced');
	if ( isDefined(scrollTo) ) 
		Effect.ScrollTo('advanced', { duration: 1.0 });
	
	fillSpinner('videoresult');
	asyncReq(url,el);
}

function abortProcess() {
	if ( isDefined(runningProcess) )
		runningProcess.abort();
	
	clearTimeout(timerId);
}

function pageUpdate(url,el) {
	updateAllowed = false;
	//console.log('page-update');
	hideDiv2('searchresults');
	var scrollTo = $('resultcontainer');
	if ( isDefined(scrollTo) ) 
		Effect.ScrollTo('resultcontainer', { duration: 1.0 });
	
	fillSpinner('searchspinner');
	abortProcess();
	runningProcess = asyncReq(url,el);
}

function fillSpinner(el,extrastr) {
	if ( isDefined(el) ) {
		$(el).update('<img src="'+base_url+'img/spinner.gif" border="0" style="text-align: center; no-repeat;">'+(isDefined(extrastr)?'<span style="position:relative;left:5px;top:-4px;">'+extrastr+'</span>':''));
	}
}

// pos 1..13
function fillSpinnerBar(el,pos) {
	if (isDefined(el)) {
		if (!isDefined(pos) || pos<1) 
			pos=1;
		else if (pos>13)
			pos=13;
		// 237x11
		//$(el).update('<img src="'+base_url+'img/progbar/progress'+pos.toString()+'.gif" width="237" height="11" border="0" style="text-align: center; no-repeat;padding:2px 0 2px 2px;">');
		var div='<div style="padding:2px;">';

		div+=	'<div style="float:left;position:relative;padding:0px;width:237px;height:11px;border-right:1px solid #ccc;overflow:hidden;">';
		div+=	'<img src="'+base_url+'img/progbar/progressfull.gif" width="237" height="11" border="0" style="position:absolute;left:0;top:0;z-index:0;" />'; 
		div+=	'<img src="'+base_url+'img/progbar/progressgrey.png" width="237" height="11" border="0" style="position:absolute;left:'+(15*(pos-1)).toString()+'px;top:0;z-index:2;" />';
		div+=	'</div>';
		div+=	'<a href="javascript:stopSearch()" style="padding-left:5px;position:relative;top:-2px;"><img src="'+base_url+'img/icon_stop_16.png" alt="Stop" /></a>';
		div+=	'</div>';
		$(el).update(div);
	}
}

function removeSpinner(el,url) {
	if ( isDefined(el) ) {
		if ( url )
			asyncReq(url,el);
		else 
			$(el).update(''); 
	}	
}

function cleanElement(el) {
	$(el).innerHTML = '';
}

function hideResults(el,button,dohide) {
	toggleDiv(el,dohide);
	if (dohide) {
		$(button+'up').setStyle( { visibility: "hidden" });
		$(button+'dn').setStyle( { visibility: "visible" });
	}
	else {
		$(button+'up').setStyle( { visibility: "visible" });
		$(button+'dn').setStyle( { visibility: "hidden" });
	}
	//$(button).setStyle({ background: "url("+base_url+"/img/icon_viewoptions_dn.png)" });
}

function toggleDiv(el,dohide) {
	var elRef = $(el);
	if ( !isDefined(elRef) ) 
		return;
	if ( !isDefined(dohide) ) { 
		if ( $(el).getStyle('display') == 'block' ) 
			dohide = true;
		else 
			dohide = false;
	}
	if ( is_ie ) {
		if (dohide)
			$(el).setStyle({display: "none"});	// dit werkt voor IE...TODO: showresults als hij al leeg is....
		else
			$(el).setStyle({display: "block"});
	}
	else {
		if (!( $(el).getStyle('display') == 'none' 
				&& dohide )) 
			Effect.toggle(el, 'blind', {duration: 0.3});
	}	
}

function getElementLocation(sequence,changer) {
	return getVideoLocation(sequence,changer);
}

function getVideoLocation(sequence,changer) {
	if ( !sequence || !changer )
		return false;
	//alert('sequence='+sequence);
	//alert('changer='+changer);
	var loc;
	var locatie = sequence.split("&");
	for(var i=0;i<locatie.length;++i) {
		loc = locatie[i].split('=');
		if ( loc[1] == changer ) {
			return i;
		}
	}
	return false;
}

function getElementOnLocation(sequence,position) {
	return getVideoOnLocation(sequence,position);
}

function getVideoOnLocation(sequence,position) {
	var locatie = sequence.split('&');
	var video = locatie[position];
	if ( !video )
		return false;
	locatie = video.split('=');
	return locatie[1];
}
 	
function isDefined(obj){
	return (obj != undefined);
}

/*shows a red fadebox.
 *@param the message for the box
 *@param green(1) or, default, red box (0) 
 *@el the target element where the warning should be displayed
 */  

function showFadeBox(msg, color, el) {
    var tarEl = $(el);
    var col = '#BB0000';
    if(color == 1)
        col = '#009900';
    if ( isDefined(tarEl) ) {
        tarEl.update('');
        tarEl.style.display = '';
        var fadebox = '<fieldset id="errordiv" style="border: 1px solid ' + col + '; margin: 20px 0pt;';
        fadebox += 'padding: 6px 10px 10px 6px; background-color: #DDD;"><div style="padding: 4px 0pt;';
        fadebox += 'color: '+col+'; font-weight: normal;"><p>' + msg + '</p></div></fieldset>';
        tarEl.update(fadebox);
        setTimeout("new Effect.Fade($('" + el + "'),{ duration:1.0});",1750);
    }
}

function removeImage(imgid, event, id, location) {
	confirmed = false;
	modalboxsurejs("confirmed=true",langsw('Wilt u deze foto definitief verwijderen?','Remove this photo?'));
	var obj = {
		exec: function(ev) {
			if (!confirmed)
				return;
			
			url = base_url+'image/removeimage/'+imgid;
			new Ajax.Request( url, {
					method: 'post',
					onSuccess: function (transport) {
						var response = transport.responseText;
						if (response != "ok") {
							modalboxalert(langsw("Waarschuwing","Warning"), response);
						}
						else if ( id != 'redirect' )
							new Effect.Shrink(document.getElementById(id));
						else
							window.location.href = base_url+location;
					}
			});
			document.stopObserving("lightview:hidden", obj.execx);
		}
	};
	obj.execx = obj.exec.bindAsEventListener(obj);
	document.observe("lightview:hidden", obj.execx);
	Event.stop(event); // stop event propagation
	return false; // cancel click
}

function removeVideoFromChannel(channel,video,args) {
	confirmed = false;
	modalboxsurejs("confirmed=true",langsw('Wilt u deze video verwijderen?','Remove this video?'));
	var obj = {
		exec: function(ev) {
			if (!confirmed)
				return;
			new Effect.Shrink(document.getElementById(video));
			url = base_url+'channelx/removeVideo/'+channel+'/'+video;
			asyncReq(url);
			// Videocounter updaten
			document.getElementById('videocount').innerHTML = document.getElementById('videocount').innerHTML-1;
			//url = base_url+'channelx/videoCount/'+channel;
			//asyncReq(url,'videocount');
			document.stopObserving("lightview:hidden", obj.execx);
		}
	};
	obj.execx = obj.exec.bindAsEventListener(obj);
	document.observe("lightview:hidden", obj.execx);
	return false; // cancel click
}

/*function removeChannel(chid, button) {
	confirmed = false;
	modalboxsurejs("confirmed=true", 'Wilt u dit kanaal echt verwijderen?');
	var obj = {
		exec: function(ev) {
				if(!confirmed) {
					document.stopObserving("lightview:hidden", obj.execx);
					return false;
				}
				else {
					if(button)
						return true;
					else {
						new Ajax.Request(base_url+"channelx/removechannel/"+chid, {
							method: 'post',
							onSuccess: function(transport) {
								var response = transport.responseText;
								if (response != "removed")
									modalboxalert("Error", response);
								else
									new Effect.Shrink(document.getElementById(chid));
							}
						});
					}
					document.stopObserving("lightview:hidden", obj.execx);
				}
			}
	};
	obj.execx = obj.exec.bindAsEventListener(obj);
	document.observe("lightview:hidden", obj.execx);
	return false; // cancel
}*/

function reactivateChannel(chid) {
	window.location.href = base_url+"channelx/reactivatechannel/"+chid;
}

function removeChannel(chid, button, addNew) {
	confirmed = false;
	new Ajax.Request(base_url+"channelx/isremovable/"+chid, {
		method:'post',
		onSuccess: function(verify) {
			var check = verify.responseText;
			if(check == "yes")
				modalboxsurejs("confirmed=true", langsw('Wilt u dit kanaal echt verwijderen?','Do you really want to delete this channel'));
			else
				modalboxalert("Error", "A channel with admins can't be deleted.");
		}
	});
	var obj = {
		exec: function(ev) {
				if(!confirmed) {
					document.stopObserving("lightview:hidden", obj.execx);
					return;
				}
				else {
					new Ajax.Request(base_url+"channelx/removechannel/"+chid, {
						method: 'post',
						onSuccess: function(transport) {
							var response = transport.responseText;
							if (response != "removed")
								modalboxalert("Error", response);
							else {
								if(button) {
									window.location.href = base_url+'channelx/channelDeleted/'+chid;
								}
								else {
									new Effect.Shrink(document.getElementById('cover'+chid));
									//setTimeout("removeElement(document.getElementById('cover"+chid+"'))", 1000);
									if(addNew)
										setTimeout("new Ajax.Request(base_url+\"channelx/showUserChannels/"+chid+"\", {method: 'post', onSuccess: function(suctransport) {document.getElementById('rbox6innerdiv').innerHTML += suctransport.responseText;}})", 1000);
								}
							}
						}
					});
					document.stopObserving("lightview:hidden", obj.execx);
				}
			}
	};
	obj.execx = obj.exec.bindAsEventListener(obj);
	document.observe("lightview:hidden", obj.execx);
	return false; // cancel click
}

//haalt een favoriete video weg
//verbergt de video uit de lijst
//doe json request
//als er geen videos meer zijn wordt de div emptyfavs ingevuld
function removeFavorite(uid,video) { 
	new Effect.Shrink(document.getElementById(video));
	url = base_url+'users/removeFavorite/'+uid+'/'+video+'/video';
	json_Request(false, url, '', 'message', 'emptyfavs');
	var emptyfavs = $('emptyfavs');
	if(isDefined(emptyfavs)) {
	   	if(emptyfavs.innerHTML !="") {
      		$('channelvideos').innerHTML = "";
     	}
  	}
}

//vraag in een popup om bevestiging
//methode haalt comment weg gegeven type, id en het postid
//scrollt naar de div commentreport om aan te geven of het verwijderen succesvol is of niet
function removeComment(type, id, pid) { 
	del = false;
	modalboxsurejs("del=true",'Wilt u dit comment definitief verwijderen?');
	var obj = {
		exec: function(ev) {
		
		if(!del) {
			return;
		}
		
		url = base_url+'comments/remove/'+type+'/'+id+'/'+pid;
		json_Request(false, url, '', 'message', 'commentreport', 'commentreport');
		document.stopObserving("lightview:hidden", obj.execx);
		var hiderow = 'row' + pid;
		$(hiderow).hide();
		var test = $$('tr:[id^=row]');
		var nocomments = true;
		for (i = 0; i < test.length; i++)
		{
			if(test[i].style.display != 'none')
			{
				nocomments = false;
			}
		}
		if(nocomments && $('commentreport').innerHTML != "Nog geen reacties gegeven")
		{
			syncReq(base_url+'comments/get/'+type+'/'+id,'commentsholder');
		}
		new Effect.ScrollTo($('commentreport'), { duration: 1.0 });
		}
	};
	obj.execx = obj.exec.bindAsEventListener(obj);
	document.observe("lightview:hidden", obj.execx);
	return false; // cancel click
}

function reloadHeader(channel) {
	var header = $('channel_head');
	if ( isDefined(header) ) {
		var url = base_url+'channel/header/'+channel;
		asyncReq(url,'channel_head');					
	} 
}

function openDiv(divName) {
	Effect.Appear(divName);
}

function closeDiv(divName) {
	Effect.SwitchOff(divName);
}

function hideDiv(divName) {
	$(divName).style.visibility = 'hidden';
}
function hideDiv2(divName) {
	$(divName).style.display = "none";
}

function showDiv(divName) {
	$(divName).style.visibility = 'visible';
}

function showDiv2(divName) {
	$(divName).style.display = "block";
}

function closeDriver(source) {
	var driverBlock = $(source+'_videoblock');
	if ( isDefined(driverBlock) ) 
		Element.hide(driverBlock);
}

function addVideoToChannel(channel,resultvideo, customsort) {
	// Delay for spinner, else doesn't show			
	fillSpinner('dropzone_spinner');
	var firstorlast = 'last';
	//even quick 'n dirty
	var channeladd = $('channeladdoption');
	if(isDefined(channeladd)) {
		if(channeladd.value == 'first') {
			firstorlast = 'first';
		} 
	}
	url = base_url+'channelx/addvideotozone/'+channel+'/'+resultvideo+'/'+firstorlast+'/1';
	syncReq(url,'dropzone_videos');
	$('droppables').highlight();
	// Delay for spinner, else doesn't show			
	setTimeout("removeSpinner('dropzone_spinner')",1000);
}

//function called from within an iframe, adds the video being played to the channel and scrolls to the top
function addVideoToChannelInView(vid) {
	addVideoToChannel(channel,vid);
	Lightview.hide();
	Effect.ScrollTo('channel_search_dropzone', { duration: 0.5 });
}

//opens up a lightview with a form to edit a channelvideo
function editChannelVideo(channel, vid, descr) {
	var stitle='Modify Video';
	var scapt= '';
	var form = ''
	var url = base_url + 'channel/modifyvideo/'+channel+'/'+vid;
	new Ajax.Request(url, {
		method: 'post', 
		asynchronous: false,
		parameters: 'channel=' + channel + '&vid=' + vid,
		onSuccess: function(transport) {
			eval("var response = " + transport.responseText);
			if (response.result == 'success') {
				form = response.message;
			}
			if( !isDefined($('__mbBody'))) {
				var __mbBody = document.createElement('div');
				__mbBody.id = '__mbBody';
				document.body.insertBefore(__mbBody, document.body.childNodes[0]);
			} 
			
			var __mbBody = $('__mbBody');
			
			__mbBody.setStyle({
				backgroundColor: '#FFFFFF',
				display: 'none'
			});
			var desc = false;
			var extrajs = '';
			
			if(descr) {
				desc = descr;
				extrajs += 'spinAsyncReq(\''+base_url+'channel/getchanneltags/'+channel+'\',$(\'userchannels_tags\')); ';
			}
			extrajs += 'Lightview.hide();';
			but='';
			but+='<input type="button" value="Modify"';
			but += ' onClick="fillSpinner(\'formspinner\'); simple_submit(false, \''+base_url+'channel/modifyvideo/'+channel+'/'+vid+'\',\'$(\\\'modifyvideo\\\').serialize(true)\','+vid+',\''+desc+'\'); '+extrajs+' ">';
			but+='<input type="button" value="'+langsw('Annuleren','Cancel')+'"';
			but+=' onClick="Lightview.hide();"><div id="formspinner"></div>';
			__mbBody.update('<div style="padding: 10px 10px 10px 0px;">'+but+'</div>');
			Lightview.show({
			  href: '#__mbBody',		// this div should be out there somewhere
			  rel: 'inline',
			  title: stitle,
			  caption: form,
			  options: {
			    autosize: false,
			    topclose: false,
				width: 500,
				height: 40
			  }
			});
	
		}
	});
}

// generic lightview call to show an url with ajax
function LightviewPage(url,tit,capt, callmethod) { 
	if (isDefined(callmethod))
		cm=callmethod;	// ajax or iframe
	else
		cm='ajax';	// default
		
	Lightview.show({
		href: base_url+url,
		rel: 'ajax',
		title: tit,
		caption: capt,
		options: {
			autosize: true,
			//topclose: false,
			ajax: {
				method: 'get',
				evalScripts: true
				// onComplete: function(){ xxx }	// als de ajax geladen is, dus aan het begin
			}
		}
	});
}

function reloadChannelVideos() {
	fillSpinner('channel_content');
	url = base_url+'channelx/showChannelVideos/'+channel+'/0/'+backoffice;
	syncReq(url,'droppables');
	removeSpinner('channel_content');	
}

function nextVideoPage(url,el) {
	fillSpinner('channelvideos2');
	asyncReq(url,el);
}

/*function getChannelPage(url,el) {
	var scrollTo = $('pageheader');
	if ( isDefined(scrollTo) ) 
		Effect.ScrollTo('pageheader', { duration: 1.0 });
		
//	regex url pg:xxx for updating pagenumber	
//	currentPageLink = 
	
	fillSpinner('channel_list');
	asyncReq(url,el);
}*/

//simple ajax submit, if the vid/desc parameter is set the name of the added channelvideo/description will change
function simple_submit(async, url, parameters, vid,desc) {
	new Ajax.Request(url, {
		method: 'post', 
		asynchronous: async,
		parameters: eval(parameters),
		onSuccess: function(transport) {
			eval("var response = " + transport.responseText);
			if(vid) {
				//title always has to be updated, description only with list representation of videos
				$$('div#'+vid+' div[class=\'inlinetitle\']')[0].innerHTML = $('modVideoTitle').value;
				//list representation update
				if(desc == 'list') {
					$$('div#'+vid+' div[class=\'sv_title\']')[0].innerHTML = $('modVideoTitle').value;
					$$('div#'+vid+' div[class=\'sv_desc\']')[0].innerHTML = $('modVideoDescription').value;
				}
			}
		}
	});
}


// universal request page:
//	- put on a spinner somewhere
//	- (optional) jump to a page location
//	- do the Synchronous request
//
function getSyncPageWithSpinner(url,el,spinnerid,scrolltoid, extrajs) {
	var scrollTo;
	if (scrolltoid) {
		scrollTo = $(scrolltoid);
		if ( isDefined(scrollTo) ) 
			Effect.ScrollTo(scrolltoid, { duration: 1.0 });
	}
	if (spinnerid)
		fillSpinner(spinnerid);
	syncReq(url,el);
	eval(extrajs);
}

// universal request page:
//	- put on a spinner somewhere
//	- (optional) jump to a page location
//	- do the async request
//  replaces all specific copies. -rvw
//
function getAsyncPageWithSpinner(url,el,spinnerid,scrolltoid) {
	var scrollTo;
	if (scrolltoid) {
		scrollTo = $(scrolltoid);
		if ( isDefined(scrollTo) ) 
			Effect.ScrollTo(scrolltoid, { duration: 1.0 });
	}
	if (spinnerid)
		fillSpinner(spinnerid);
	asyncReq(url,el);
}

// universal json request function
// - make a new ajax.request with the following required parameters: asyncbool, url, parameters.
// - asyncbool determines if the request should be asynchronous or not.
// - if responseid is given, it will put the result of response.responseid in el, else the page will be reloaded 
// - if errordiv is given, and this div exists, response.message is inserted in that errordiv else the response.message will be alerted.
// 
function json_Request(asyncbool, url, parameters, responseid, el, errordiv) {
	new Ajax.Request(url, {
		method: 'post', asynchronous: eval(asyncbool),
		parameters: eval(parameters),
		onSuccess: function(transport) {
			eval("var response = " + transport.responseText);
			if (response.result == 'success') {
				if(responseid) {					
					$(el).update(eval("response." + responseid));
				}
				else
				{
					document.location.reload();
				}
			} else {
				var diverror;
				if (errordiv) {
					diverror = $(errordiv);
					if ( isDefined(diverror) ) {
						$(errordiv).innerHTML = response.message;
					}
				}
				else
				{
					alert(response.message);
				}
			}
		}
	});
}

//getJSONWithspinner uses a json_Request
// - empty the error message
// - it fills a spinner id
// - does the json call (see json_Request for an explanation)
// - the extrajs will be executed,
// - check if the errordiv was given. 
// - if there was no error, scroll to scrolltoid, else scroll to errordiv.

function getJSONWithSpinner(asyncbool, url,el,spinnerid,scrolltoid, parameters, responseid, extrajs, errordiv) {
	if(errordiv) {
		$(errordiv).innerHTML = "";
	}
	if (spinnerid) {
		fillSpinner(spinnerid);
	}
	
	json_Request(asyncbool, url, parameters, responseid, el, errordiv);
	
	if(extrajs) {
		eval(extrajs);
	}
	if(errordiv)
	{
		var scroll = errordiv;
		if($(errordiv).empty())
		{
			scroll = scrolltoid;
		}			
		var scrollTo;
		if (scroll) {
			scrollTo = $(scroll);
			if ( isDefined(scrollTo) ) {
				Effect.ScrollTo(scroll, { duration: 1.0 });
			}
		}
	}
	cleanElement(spinnerid);
}

function reloadComment(channel,video) {
	var comments = $('channel_videocomments');
	if ( isDefined(comments) ) {
		var url = base_url+'channel/comments/'+channel+'/'+video;
		asyncReq(url,'channel_videocomments');
	}
}

function showMessage(title,caption,options) {
	Lightview.show({
	  href: '#__mbBody',		// this div should be out there somewhere
	  rel: 'inline',
	  title: title,
	  caption: caption,
	  options: {
	    autosize: false,
	    topclose: false,
		width: 200,
		height: 20
	  }
	});
}

// showVideo2 is verwijderd - werd niet gebruikt
// showVideo is verwijderd - mag niet meer gebruikt worden

function showCachedVideo(cachedid,stitle,scapt) { 
	var width = 600;
	new Ajax.Request(base_url+"channel/getvideowidth/cache/"+cachedid+"/"+width, {
		method: 'post',
		onSuccess: function(transport) {
			var response = transport.responseText;
			if (response > width)
				width = parseInt(response);
			// Te lange beschrijving afkappen
			if ( scapt.length > 300 )
				scapt_short = scapt.substr(0,300)+'...';
			else
				scapt_short = scapt;
				
			Lightview.show({
			  href: base_url+'channel/videoplay/cache/'+cachedid+'/width:'+width,
			  rel: 'iframe',
			  title: stitle.substr(0,79),
			  caption: scapt_short,
			  options: {
				 autosize: false,
				 topclose: false,
				 width: width,
				 height: 429
			  }
			});
		},
		onFailure: function(){ }
	});
}

function showChannelVideo(vid,stitle,scapt) {
	var width = 600;
	new Ajax.Request(base_url+"channel/getvideowidth/channelvideo/"+vid+"/"+width, {
		method: 'post',
		onSuccess: function(transport) {
			var response = transport.responseText;
			if (response > width)
				width = parseInt(response);
			// Te lange beschrijving afkappen
			if ( scapt.length > 300 )
				scapt_short = scapt.substr(0,300)+'...';
			else
				scapt_short = scapt;
			
			Lightview.show({
			  href: base_url+'channel/videoplay/channelvideo/'+vid+'/width:'+width,
			  rel: 'iframe',
			  title: stitle.substr(0,79),
			  caption: scapt_short,
			  options: {
				 autosize: false,
				 topclose: false,
				 width: width,
				 height: 400
			  }
			});
		},
		onFailure: function(){ }
	});
}

//adds the right tags to the parameter text and returns the changed parameter text
function changeText(type, text) {
	switch (type) 
	{
		case 'smiley':
			text = ' ' + text + ' ';
			break;
		case 'bold':
			text = '[b]' + text + '[/b]';
			break;
		case 'italic':
			text = '[i]' + text + '[/i]';
			break;
		case 'underscore':
			text = '[u]' + text + '[/u]';
			break;
		case 'url':
			if(text == 'http:\/\/') {
				text = '';
			}
			text = '[url]' + text + '[/url]';
			break;
		case 'email':
			text = '[email]' + text + '[/email]';	
			break;
		case 'red':
			text = '[red]' + text + '[/red]';
			break;
		case 'blue':
			text = '[blue]' + text + '[/blue]';
			break;
		case 'green':
			text = '[green]' + text + '[/green]';
			break;
		case 'orange':
			text = '[orange]' + text + '[/orange]';
			break;
		case 'image':
			if(text == 'http:\/\/') {
				text = '';
			}
			text = '[img]' + text + '[/img]';
			break;
		case 'yellow':
			text = '[yellow]' + text + '[/yellow]';
			break;
		default:
			break;
	}
	
	return text;
}

//insert smileys/tags in a textarea with the id 'comment'
function insertText(type, str) {
	var textarea = $('comment');
	if(!str) {
		str = '';
	}
	//Internet Explorer
	if (document.selection) {
		textarea.focus();
		var cursor = document.selection.createRange();
		var text = (cursor.text == '') ? str : cursor.text;
		if(type == 'smiley' || type == 'url' || type == 'image') {
			text = str;
		}
		cursor.text = changeText(type,text);
	}
	//Mozilla
	else if (typeof(textarea.selectionStart) != "undefined") {
		var scrollTop = textarea.scrollTop;
		var begin = textarea.selectionStart;
        var end = textarea.selectionEnd;
		// substr 2nd arg=nrchars, substring 2nd arg=endpos
		var text = (type == 'smiley' || type == 'url' || type == 'image') ? str : textarea.value.substring(begin,end);
		text = changeText(type,text);
        textarea.value = textarea.value.substr(0, begin) + text + textarea.value.substr(end);
		var newEnd = begin + text.length;
		if(begin != end) {
			textarea.setSelectionRange(begin, newEnd);
		}
		else {
			textarea.setSelectionRange(begin+text.length, newEnd);
		}
        textarea.scrollTop = scrollTop;
	}
	//Safari en andere browsers die niets van cursor positie weten
	else {
		textarea.value += changeText(type,str);
	}

	textarea.focus();
	
	if (typeof textarea.cursorPos != 'undefined') {
		textarea.onselect();
	}
}

//toggles elements with id: type1, type2 etc...
//also requires the object thats being clicked on, so the image of that element can be changed
function showIcons(object,type, number,text1,text2) {
	for(i=1; i<=number; i++) {
		var divnumber = '' + type + i;
		Effect.toggle(divnumber, 'appear', { delay: 0.1, duration: 0.5});
	}
	if(object.src == base_url + 'img/icon_follow2.png') {
		object.src = base_url + 'img/flink.png';
		object.title = text2;
	} else {
		object.src = base_url + 'img/icon_follow2.png';
		object.title = text1;
	}
	//Effect.multiple(['smile1','smile2','smile3','smile4'], Effect.toggle);
}

//toggles element visible/invisible. 
//also requires the object thats being clicked on, so the image of that element can be changed (img without baseurl!! so like img/xxx)
function showIcons2(object,divobj,text1,text2, img1, img2) {
	Effect.toggle(divobj, 'appear', { delay: 0.1, duration: 0.7});
	if(object.src == base_url + img1) {
		object.src = base_url + img2;
		object.title = text2;
	} else {
		object.src = base_url + img1;
		object.title = text1;
	}
}


function modalboxconfirmjs(args) {
	if (args.title) 
		stitle=args.title;
	else
		stitle='Warning';
	scapt= args.caption ? args.caption:'Are you sure ?';
	
	if( !isDefined($('__mbBody'))) {
		var __mbBody = document.createElement('div');
		__mbBody.id = '__mbBody';
		document.body.insertBefore(__mbBody, document.body.childNodes[0]);
	} 
	
	var __mbBody = $('__mbBody');
	
	__mbBody.setStyle({
		backgroundColor: '#FFFFFF',
		display: 'none'
		//width: '100px',
		//height: '55px'
	});
	but='';
	if (args.button1) {
		but+='<input type="button" value="'+args.button1+'"';
		if (args.button1url)
			but+=" onClick='"+args.button1url+";Lightview.hide();'>";
		else
			but+=' onClick="Lightview.hide();">';
	}
	else
		but+='<input type="button" value=" OK " onClick="Lightview.hide();">';
	if (args.button2) {
		but+='<input type="button" value="'+args.button2+'"';
		if (args.button2url)
			but+=" onClick='"+args.button2url+"'>";
		else
			but+=' onClick="Lightview.hide();">';
	}
	__mbBody.update('<div style="height: 30px;">'+scapt+'</div><div style="padding: 0px 10px 0px 0px;">'+but+'</div>');

	Lightview.show({
	  href: '#__mbBody',		// this div should be out there somewhere
	  rel: 'inline',
	  title: stitle,
	  caption: '',
	  options: {
	    autosize: false,
	    topclose: false,
		width: 400,
		height: 100
	  }
	});
}

function modalboxlargeconfirmjs(args) {
	if (args.title) 
		stitle=args.title;
	else
		stitle='Warning';
	scapt= args.caption ? args.caption:'Are you sure ?';
	
	if( !isDefined($('__mbBody'))) {
		var __mbBody = document.createElement('div');
		__mbBody.id = '__mbBody';
		document.body.insertBefore(__mbBody, document.body.childNodes[0]);
	} 
	
	var __mbBody = $('__mbBody');
	
	__mbBody.setStyle({
		backgroundColor: '#FFFFFF',
		display: 'none'
		//width: '100px',
		//height: '55px'
	});
	but='';
	if (args.button1) {
		but+='<input type="button" value="'+args.button1+'"';
		if (args.button1url)
			but+=" onClick='"+args.button1url+";Lightview.hide();'>";
		else
			but+=' onClick="Lightview.hide();">';
	}
	else
		but+='<input type="button" value=" OK " onClick="Lightview.hide();">';
	if (args.button2) {
		but+='<input type="button" value="'+args.button2+'"';
		if (args.button2url)
			but+=" onClick='"+args.button2url+"'>";
		else
			but+=' onClick="Lightview.hide();">';
	}
	__mbBody.update('<div style="height: 30px;">'+scapt+'</div><div style="padding: 10px 10px 0px 0px;">'+but+'</div>');

	Lightview.show({
	  href: '#__mbBody',		// this div should be out there somewhere
	  rel: 'inline',
	  title: stitle,
	  caption: '',
	  options: {
	    autosize: true,
	    topclose: false,
		width: 400,
		height: 100
	  }
	});
}


function modalboxconfirm(args) {
	if (args.title) 
		stitle=args.title;
	else
		stitle='Warning';
	scapt= args.caption ? args.caption:'Are you sure ?';
	
	if( !isDefined($('__mbBody'))) {
		var __mbBody = document.createElement('div');
		__mbBody.id = '__mbBody';
		document.body.insertBefore(__mbBody, document.body.childNodes[0]);
	} 
	
	var __mbBody = $('__mbBody');
	
	__mbBody.setStyle({
		backgroundColor: '#FFFFFF',
		display: 'none'
		//width: '100px',
		//height: '55px'
	});
	but='';
	if (args.button1) {
		but+='<input type="button" value="'+args.button1+'"';
		if (args.button1url)
			but+=" onClick='location.href=\""+args.button1url+"\";'>";
		else
			but+=' onClick="Lightview.hide();">';
	}
	else
		but+='<input type="button" value=" OK " onClick="Lightview.hide();">';
	if (args.button2) {
		but+='<input type="button" value="'+args.button2+'"';
		if (args.button2url)
			but+=" onClick='location.href=\""+args.button2url+"\";'>";
		else
			but+=' onClick="Lightview.hide();">';
	}
	__mbBody.update('<div style="height: 30px;">'+scapt+'</div><div style="padding: 10px 10px 0px 0px;">'+but+'</div>');

	Lightview.show({
	  href: '#__mbBody',		// this div should be out there somewhere
	  rel: 'inline',
	  title: stitle,
	  caption: '',
	  options: {
	    autosize: false,
	    topclose: false,
		width: 400,
		height: 100
	  }
	});
}

function modalboxlargeconfirm(args) {
	if (args.title) 
		stitle=args.title;
	else
		stitle='Warning';
	scapt= args.caption ? args.caption:'Are you sure ?';
	
	if( !isDefined($('__mbBody'))) {
		var __mbBody = document.createElement('div');
		__mbBody.id = '__mbBody';
		document.body.insertBefore(__mbBody, document.body.childNodes[0]);
	} 
	
	var __mbBody = $('__mbBody');
	
	__mbBody.setStyle({
		backgroundColor: '#FFFFFF',
		display: 'none'
	});
	but='';
	if (args.button1) {
		but+='<input type="button" value="'+args.button1+'"';
		if (args.button1url)
			but+=" onClick='location.href=\""+args.button1url+"\";'>";
		else
			but+=' onClick="Lightview.hide();">';
	}
	else
		but+='<input type="button" value=" OK " onClick="Lightview.hide();">';
	if (args.button2) {
		but+='<input type="button" value="'+args.button2+'"';
		if (args.button2url)
			but+=" onClick='location.href=\""+args.button2url+"\";'>";
		else
			but+=' onClick="Lightview.hide();">';
	}
	__mbBody.update('<div>'+scapt+'</div><div style="padding: 10px 10px 10px 0px; text-align: center;">'+but+'</div>');

	Lightview.show({
	  href: '#__mbBody',		// this div should be out there somewhere
	  rel: 'inline',
	  title: stitle,
	  caption: '',
	  options: {
	    autosize: true,
	    topclose: false
	  }
	});
}

function modalboxprompt(args) {
	if (args.title) 
		stitle=args.title;
	else
		stitle='Invoer';
	scapt= args.caption ? args.caption:'Are you sure ?';
	
	if( !isDefined($('__mbBody'))) {
		var __mbBody = document.createElement('div');
		__mbBody.id = '__mbBody';
		document.body.insertBefore(__mbBody, document.body.childNodes[0]);
	} 
	
	var __mbBody = $('__mbBody');
	
	__mbBody.setStyle({
		backgroundColor: '#FFFFFF',
		display: 'none'
		//width: '100px',
		//height: '55px'
	});
	but='';
	if (args.button1) {
		but+='<input type="button" value="'+args.button1+'"';
		if (args.button1url)
			but += ' onClick="'+args.button1url+'; Lightview.hide();">';
		else
			but+=' onClick="Lightview.hide();">';
	}
	else
		but+='<input type="button" value=" OK " onClick="Lightview.hide();">';
	if (args.button2) {
		but+='<input type="button" value="'+args.button2+'"';
		if (args.button2url)
			but+=" onClick='"+args.button2url+"'>";
		else
			but+=' onClick="Lightview.hide();">';
	}
	__mbBody.update('<div style="height: 40px;">'+scapt+'<br><input id="inputfield" class="text" type="text" size="50" maxlength="100" value="'+args.inputvalue+'" name="inputfield"/></div><div style="padding: 10px 10px 10px 0px;">'+but+'</div>');
	Lightview.show({
	  href: '#__mbBody',		// this div should be out there somewhere
	  rel: 'inline',
	  title: stitle,
	  caption: '',
	  options: {
	    autosize: false,
	    topclose: false,
		width: 400,
		height: 75
	  }
	});
}

function modalboxshowprompt(js,inputvalue, text) {
	modalboxprompt({button1: ' OK ',button1url: js, caption: text, inputvalue: inputvalue, title: 'Invoer',button2: langsw('annuleren','cancel')});
}

function modalboxsure(url,scapt) {
	modalboxconfirm({button1: ' OK ',button1url: url, caption: scapt});
}

function modalboxsurejs(js,scapt) {
	modalboxconfirmjs({button1: ' OK ',button1url: js, caption: scapt, title: langsw('Waarschuwing','Warning'),button2: langsw('annuleren','cancel')});
}
function modalboxlargesurejs(js,scapt) {
	modalboxlargeconfirmjs({button1: ' OK ',button1url: js, caption: scapt, title: langsw('Waarschuwing','Warning') ,button2: langsw('annuleren','cancel')});
}

function modalboxinfo(header,text) {
	modalboxlargeconfirm({button1: ' OK ',title: header, caption: text});
}
function modalboxalert(header,text) {
	modalboxconfirm({button1: ' OK ',title: header, caption: text});
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
// extend inplaceeditor
Ajax.InPlaceEditor2 = Class.create(Ajax.InPlaceEditor, {
	createEditField: function($super) {
		$super();
		this._controls.editor.value = this._controls.editor.value.stripTags();
	},
	
	initialize: function($super, element, url, options) {
		if (!options.emptyText)        options.emptyText      = "klik om aan te passen..";
		if (!options.emptyClassName)   options.emptyClassName = "inplaceeditor-empty";
		// rvw
		if (!options.doCheckEmpty)	   options.doCheckEmpty   = false;	// force true/false
		// ferry
		if (!options.killHover)   options.killHover = false;
		// endferry
		// david
		if (!options.ignoreURL) options.ignoreURL = false;
		
		$super(element, url, options);
		this.checkEmpty();
	},
	
  enterHover: function($super, e) {
	if(!this.options.killHover) {
  		  $super(e);
    }
  },
  enterEditMode: function(e) {
    if (this._saving || this._editing) return;
    if(this.options.ignoreURL) {
      var ele = Event.element(e);
      if (ele.match('a')) return; 
    }
    this._editing = true;
    this.triggerCallback('onEnterEditMode');
    if (this.options.externalControl)
      this.options.externalControl.hide();
    this.element.hide();
    this.createForm();
    this.element.parentNode.insertBefore(this._form, this.element);
    if (!this.options.loadTextURL)
      this.postProcessEditField();
    if (e) Event.stop(e);
  },  
  leaveHover: function($super, e) {
	  if (!this.options.killHover)
		  $super(e);
  },

  checkEmpty: function() {
	  if (this.element.innerHTML.length == 0 && this.options.emptyText && this.options.doCheckEmpty) {
		  this.element.appendChild(
			  new Element("span", { className : this.options.emptyClassName }).update(this.options.emptyText)
        );
	  }
  },
  
  leaveEditMode: function($super, transport) {
	  this.checkEmpty();
	  return $super(transport);
  },

  getText: function($super) {
	  if (empty_span = this.element.select("." + this.options.emptyClassName).first()) {
		  empty_span.remove();
	  }
	  return $super();
  },
  
  loadExternalText: function() {
    this._form.addClassName(this.options.loadingClassName);
    this._controls.editor.disabled = true;
    var options = Object.extend({ method: 'post' }, this.options.ajaxOptions);
    Object.extend(options, {
      parameters: '',
      onComplete: Prototype.emptyFunction,
      onSuccess: function(transport) {
        this._form.removeClassName(this.options.loadingClassName);
        var text = transport.responseText;
        if (this.options.stripLoadedTextTags)
          text = text.stripTags();
        this._controls.editor.value = text;
        this._controls.editor.disabled = false;
        this.postProcessEditField();
      }.bind(this),
      onFailure: this._boundFailureHandler
    });
    new Ajax.Request(this.options.loadTextURL, options);
  },
  
  //link.href weggehaald zodat in IE7 bij een submit/cancel niet naar die href wordt gescrolled
  createControl: function(mode, handler, extraClasses) {
    var control = this.options[mode + 'Control'];
    var text = this.options[mode + 'Text'];
    if ('button' == control) {
      var btn = document.createElement('input');
      btn.type = 'submit';
      btn.value = text;
      btn.className = 'editor_' + mode + '_button';
      if ('cancel' == mode)
        btn.onclick = this._boundCancelHandler;
      this._form.appendChild(btn);
      this._controls[mode] = btn;
    } else if ('link' == control) {
      var link = document.createElement('a');
      link.appendChild(document.createTextNode(text));
      link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
      link.className = 'editor_' + mode + '_link';
      if (extraClasses)
        link.className += ' ' + extraClasses;
      this._form.appendChild(link);
      this._controls[mode] = link;
    }
  },

  onComplete: function($super, transport) {
	  this.checkEmpty();
	  return $super(transport);
  },
  
  wrapUp: function(transport) {
    this.leaveEditMode();
    // Can't use triggerCallback due to backward compatibility: requires
    // binding + direct element
	//extra call op complete zorgt ervoor dat er twee keer een effect.highlight wordt aangeropen bij een cancel, wat ervoor zorgt
	//dat de kleur geel blijft
   // this._boundComplete(transport, this.element);
  }
  

});
// extend inplacecollectioneditor (to add submit-on-change)
// let op: deze implementatie gaat ervan uit dat er unieke key=>value paren worden gebruikt (symmetrisch)
Ajax.InPlaceCollectionEditor2 = Class.create(Ajax.InPlaceCollectionEditor, {
	initialize: function($super, element, url, options) {
		// ferry
		if (!options.killHover)   options.killHover = false;
		// endferry
		$super(element, url, options);
	},
	
	enterHover: function($super, e) {
	  if (!this.options.killHover)
		  $super(e);
	},
	
	leaveHover: function($super, e) {
	  if (!this.options.killHover)
		  $super(e);
	},
	
	createEditField: function($super) {
		$super();
		Event.observe(this._controls.editor,'change',this._boundSubmitHandler);
	},
	buildOptionList: function() {
    this._form.removeClassName(this.options.loadingClassName);
    this._collection = this._collection.map(function(entry) {
      return 2 === entry.length ? entry : [entry, entry].flatten();
    });
    var marker = ('value' in this.options) ? this.options.value : this._text;
	 // added
	 marker = marker.trim();
	 // end added
    var textFound = this._collection.any(function(entry) {
      //return entry[0] == marker;
		// changed
		return (entry[0] == marker || entry[1] == marker);
		//end changed
    }.bind(this));
    this._controls.editor.update('');
    var option;
    this._collection.each(function(entry, index) {
      option = document.createElement('option');
      option.value = entry[0];
      //option.selected = textFound ? entry[0] == marker : 0 == index;
		// changed
		option.selected = textFound ? (entry[0] == marker || entry[1] == marker) : 0 == index;
		//end changed
      option.appendChild(document.createTextNode(entry[1]));
      this._controls.editor.appendChild(option);
    }.bind(this));
    this._controls.editor.disabled = false;
    Field.scrollFreeActivate(this._controls.editor);
  }
});


function removeFriendFromFriendlist(id,name) {
	confirmed = false;
	modalboxsurejs("confirmed=true",'Are you sure you want to delete this friend : ' + name + ' ?');
	var obj = {
		exec: function(ev) {
			if (!confirmed)
				return;
			new Effect.Shrink($('friend_item'+id),{ duration:1.0});
			url = base_url+'friends/del/'+id;
			asyncReq(url);
			// Friend counter updated
			$('friend_item'+id).innerHTML = "";
			document.stopObserving("lightview:hidden", obj.execx);
		}
	};
	obj.execx = obj.exec.bindAsEventListener(obj);
	document.observe("lightview:hidden", obj.execx);
	return false; // cancel click
}

//---------------------------------------------------------------------------------
//	eInputLabelRemove - remove an input element label when it receives focus
//  @author: rvw 
//---------------------------------------------------------------------------------		
function eInputLabelOnFocus(e,o,color){
	o=$(o);	// expand
	if(o.labelpushed){
		return;	
	}
	o.labelpushed=true;	
	o.defvalue=o.value;
	o.value="";
	if ( isDefined(color) ) 
		o.setStyle( { color:color } );
	else
		o.setStyle( { color:"#000000" } );
}
function eInputLabelOnBlur(e,o){
	o=$(o);	// expand
	if(o.labelpushed){
		o.value=o.defvalue;
		o.labelpushed=false;
		o.setStyle( { color:"#A3451D" } );
	}
}


//---------------------------------------------------------------------------------
//	getWindowHeight - browser indep method to obtain viewport height
//  @author: rvw and http://www.alistapart.com/articles/footers
//---------------------------------------------------------------------------------
function getWindowHeight() {
	var windowHeight=0;
	if (typeof(window.innerHeight)=='number') {
		windowHeight=window.innerHeight;
	}
	else {
		if (document.documentElement&&
			document.documentElement.clientHeight) {
			windowHeight=
				document.documentElement.clientHeight;
		}
		else {
			if (document.body&&document.body.clientHeight) {
				windowHeight=document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}
//---------------------------------------------------------------------------------
//	setPageFooter - position the footer object so it follows the viewport bottom
//  @author: rvw and http://www.alistapart.com/articles/footers 
//---------------------------------------------------------------------------------
function setPageFooter() {
	var windowHeight=getWindowHeight();
	if (windowHeight>0) {
		var contentHeight=0;
		if (isDefined($('pageheader')) )
			contentHeight=$('pageheader').offsetHeight;
		else
			return;	// no pageheader? do nothing! 
		if (isDefined($('wrap')) ) {
			contentHeight+=$('wrap').offsetHeight;
		}
		var footerElement=$('pagefooter');
		if (isDefined(footerElement)) {
			var footerHeight=footerElement.offsetHeight;
			if (windowHeight-(contentHeight+footerHeight)>=0) {
				footerElement.style.position='relative';
				footerElement.style.top=(windowHeight-
				(contentHeight+footerHeight))+'px';
			}
			else {
				footerElement.style.position='static';
			}
		}
	}
}

//-------------------------------------------------------------------------------
// set load and resize events to reset PageFooter
// ------------------------------------------------------------------------------
Event.observe(window, 'load', function() {
  setPageFooter();
});
Event.observe(window, 'resize', function() {
  setPageFooter();
});

//-------------------------------------------------------------------------------
// END of preload.js
// ------------------------------------------------------------------------------
-->
