var koalaPlaylist = {
	playlist_entries: null,
	
	players: null,
	players_div: null,
	
	current_video: null,
	
	active_player: null,
	
	state: -1,
	
	'addVideo': function(videoId, pos) {
		koalaPlaylist.playlist_entries[videoId] = videoId;
	},
	
	'getNextVideo': function() {
		var next_video = null;
		var last_video = null;
		var first_video = null;
		var current_video = koalaPlaylist.current_video;
		
		$each(koalaPlaylist.playlist_entries,function (videoId) {
			if (typeof(videoId) !== 'function') {
				if (first_video === null) {
					first_video = videoId;
				}
				if (next_video === null) {
					if (last_video === current_video || current_video == null) {
						next_video = videoId;
					}
					last_video = videoId;
				}
			}
		});
		
		if (next_video === null) {
			next_video = first_video;
		}
		
		return next_video;
	},
	
	'getRandomVideo': function() {
		var first_video = null;
		var current_video = koalaPlaylist.current_video;
		
		var video_count = 0;
		
		koalaPlaylist.playlist_entries.each(function (videoId) {
			if (typeof(videoId) !== 'function') {
				if (first_video === null) first_video = videoId;
				if (videoId !== current_video) video_count++;
			}
		});
		
		if (video_count === 0) {
			return first_video;
		}
		
		video_count--;
		
		var next_video = null;
		
		video_count = Math.floor((Math.random()*video_count));
		
		koalaPlaylist.playlist_entries.each(function (videoId) {
			if (typeof(videoId) !== 'function') {
				if (videoId !== current_video) {
					if (video_count === 0) {
						next_video = videoId;
					}
					video_count--;
				}
			}
		});
		
		return next_video;
	},
	
	'removeVideo': function(video_id) {
		delete koalaPlaylist.playlist_entries[video_id];
	},
	
	'removeCurrent': function() {
		if (koalaPlaylist.current_video !== null) {
			koalaPlaylist.removeVideo(koalaPlaylist.current_video);
			koalaPlaylist.current_video = null;
		}
	},
	
	'loadPlayers': function() {
		if (koalaPlaylist.state != -1) return ;
		koalaPlaylist.state = 0;
		
		var playlist = new Element('div',{'id':'koala-playlist'});
		
		koalaPlaylist.players_div[1] = new Element('div',{'id':'koala_playlist_player1','class':'koala_playlistplayer'});
		koalaPlaylist.players_div[2] = new Element('div',{'id':'koala_playlist_player2','class':'koala_playlistplayer'});
		
		koalaPlaylist.players_div[1].inject(playlist);
		koalaPlaylist.players_div[2].inject(playlist);
		
		playlist.inject($('body'));
		
		var playlist_buttons = new Element('div',{'id':'koala-playlistbuttons'});
		
		var next_button = new Element('img',{
			'class': 'koala-action-image',
			'src': 'img/player_fwd.png',
			'title': koala.t['playlist-next'],
			'id':'koala-playlist-button-next',
			'alt':'[next]',
			'events': {
				'click': function () {
					koalaPlaylist.next();
				}
			}
		});
		
		var stop_button = new Element('img',{
			'class': 'koala-action-image',
			'title': koala.t['playlist-stop'],
			'id':'koala-playlist-button-stop',
			'src': 'img/player_stop.png',
			'alt':'[stop]',
			'events': {
				'click': function () {
					koalaPlaylist.stop();
				}
			}
		});

		var random_button = new Element('img',{
			'class': 'koala-action-image',
			'title': koala.t['playlist-random'],
			'id':'koala-playlist-button-random',
			'src': 'img/player_random.png',
			'alt':'[random]',
			'events': {
				'click': function () {
					koalaPlaylist.random();
				}
			}
		});
		
		var remove_button = new Element('img',{
			'class': 'koala-action-image',
			'title': koala.t['playlist-remove'],
			'id':'koala-playlist-button-remove',
			'src': 'img/player_removevideo.png',
			'alt':'[remove]',
			'events': {
				'click': function () {
					koalaPlaylist.removeCurrent();
					koalaPlaylist.next();
				}
			}
		});
		
		random_button.inject(playlist_buttons);
		stop_button.inject(playlist_buttons);
		next_button.inject(playlist_buttons);
		remove_button.inject(playlist_buttons);
		
		playlist_buttons.inject($('body'));
		
		var playersReady = 0;
		
		var onPlayerPlay = function(playerId) {
			koalaPlaylist.current_player = playerId;
			var player_to_hide = playerId === 1 ? 2 : 1;
			koalaPlaylist.players_div[playerId].set('tween', {duration: 6000});
			koalaPlaylist.players_div[player_to_hide].set('tween', {duration: 6000});
			koalaPlaylist.players[player_to_hide].stop();
			koalaPlaylist.players_div[playerId].tween('opacity',0,1);
			koalaPlaylist.players_div[player_to_hide].tween('opacity',1,0);
		}

		var onPlayerReady = function(playerId) {
			playersReady++;
			if (playersReady == 2) {
				koalaPlaylist.state = 1;
				koalaPlaylist.next();
			}
		}
		
		var player_class = koala.debug ? YtMooDebugPlayer : YtMooPlayer;
		koalaPlaylist.players[1] = new player_class('koala_playlist_player1',{
			'width':'300px',
			'height':'180px',
			'onReady':function(){
				onPlayerReady(1);
			},
			'onPlay':function(){
				onPlayerPlay(1);
			},
			'onEnded':function(){
				if (koalaPlaylist.current_player === 1) koalaPlaylist.random();
			},
			'onNotAllowed':function(){
				koalaPlaylist.removeCurrent();
				koalaPlaylist.next();
			}
		});
		
		koalaPlaylist.players[2] = new player_class('koala_playlist_player2',{
			'width':'300px',
			'height':'180px',
			'onReady':function(){
				onPlayerReady(2);
			},
			'onPlay':function(){
				onPlayerPlay(2);
			},
			'onEnded':function(){
				if (koalaPlaylist.current_player === 2) koalaPlaylist.random();
			},
			'onNotAllowed':function(){
				koalaPlaylist.removeCurrent();
				koalaPlaylist.next();
			}
		});		
		
	},
	
	'stop': function() {
		if (koalaPlaylist.state != 1) return ;
		
		koalaPlaylist.players[1].stop();
		koalaPlaylist.players[2].stop();
		koalaPlaylist.players_div[2].fade('out');
		koalaPlaylist.players_div[1].fade('out');
		koalaPlaylist.active_player = null;
	},
	
	'isInitialized': function () {
		return koalaPlaylist.state == -1 ? false : true
	},
	
	'playNow': function (videoId) {
		if (koalaPlaylist.state == -1) {
			koalaPlaylist.loadPlayers();
			return ;
		}
		
		if (koalaPlaylist.state != 1) return ;
		
		if (videoId !== null) {
			koalaPlaylist.current_video = videoId; 
			if (koalaPlaylist.active_player === 1) {
				koalaPlaylist.active_player = 2;
				koalaPlaylist.players[2].playVideo(videoId);
			} else if (koalaPlaylist.active_player === 2) {
				koalaPlaylist.active_player = 1;
				koalaPlaylist.players[1].playVideo(videoId);
			} else {
				koalaPlaylist.active_player = 1;
				koalaPlaylist.players[1].playVideo(videoId);
			}
		} else {
			koalaPlaylist.stop();
		}
	},
	
	'random' : function() {
		koalaPlaylist.playNow(koalaPlaylist.getRandomVideo());
	},
	
	'next': function() {
		koalaPlaylist.playNow(koalaPlaylist.getNextVideo());
	},
	
	'init': function() {
		koalaPlaylist.playlist_entries = new Hash();
		koalaPlaylist.players_div = {};
		koalaPlaylist.players = {};
	}
}

var koala = {
		
	disabled_keywords : null,
	disabled_sites : null,
	filter_sites : null,
	filter_keywords : null,
	
	keywords: null,
	
	debug: false,
	
	keywords_total_usage: 0,
	keywords_total_min: 0,
	keywords_total_max: 0,
	
	query_cache: null,
	
	t : {
	},
	
	searchengines: {
		'yahoo':'query_yahoo.php',
		'windowslive':'query_windowslive.php',
		'google':'query_google.php'
	},
	
	searchengine: 'google',
	
	translations: {
		'':{
			'search-button':'Find',
			'refine-header':'Refine:',
			'filter-words-header':'Filter Words:',
			'block-words-header':'Block Words:',
			'filter-sites-header':'Filter Sites:',
			'block-sites-header':'Block Sites:',
			'reset-search-header':'Reset search',
			'sub-header':'DracoBlue\'s Experimental Search Engine',
			'refine-explanation':'Use the mouse to refine your search.',
			'filter-word-explanation':'<strong>Left-Click</strong> filters for a word.',
			'block-word-explanation':'<strong>Right-Click</strong> blocks a word.',
			'block-word-explanation-shift':'<strong>Shift</strong>+<strong>Left-Click</strong> blocks a word.',
            'filter-site-button':'Search only on this site',
            'block-site-button':'Block results from this site',
            'play-video-site-button':'Play this video',
            'playlist-video-site-button':'Add video to playlist',
            'inline-filter-text':'Links-Click to search also for this word, Right-Click to block the word.',
            'quick-remove-keyword-button':'Remove this keyword',
            'quick-add-keyword-button':'Filter for this keyword',
            'youtube-title-does-not-allow-to-play-external':'Playback disabled',
            'youtube-body-does-not-allow-to-play-external':'Due to rules for this video on Youtube, it can not be played on external sites (like koala).',
            'open-in-new-window':'Open in new window/tab',
            'notify-title-search-reseted':'Search reseted',
            'notify-body-search-reseted':'All search filters and terms have been reseted.',
            'notify-title-language-switched':'Language switched',
            'notify-body-language-switched':'The interface language is English now.',
            'notify-title-no-results':'No results!',
            'notify-body-no-results':'Sorry, wasn\'t able to find anything by using Google.',
            'notify-title-no-more-results':'No new results!',
            'notify-body-no-more-results':'Sorry, wasn\'t able to find anything else by using Google.',
            'notify-title-autosearch-more':'Searching ...',
            'notify-body-autosearch-more':'Searching for more results for %searchterm%.',
            'notify-title-added-to-playlist':'Added!',
            'notify-body-added-to-playlist':'Added the video to your playlist.',
            'search-more':'Find more!',
            'filter-did-you-mean':'Did you mean: <strong>%searchterm%</strong>?',
            'filter-did-you-mean-no-button':'No',
            'filter-did-you-mean-yes-button':'Yes',
            'playlist-remove':'Remove: Delete this video from the playlist.',
            'playlist-stop':'Stop: Interrupt playback.',
            'playlist-next':'Next: Start next video.',
            'playlist-random':'Random: Play a random video from the playlist.'
		},
		'de':{
			'search-button':'Finden',
			'refine-header':'Verfeinern:',
			'filter-words-header':'Erlaubte Wörter:',
			'block-words-header':'Verbotene Wörter:',
			'filter-sites-header':'Erlaubte Seiten:',
			'block-sites-header':'Verbotene Seiten:',
			'reset-search-header':'Suche zurücksetzen',
			'sub-header':'DracoBlues experimentelle Suchmaschine',
			'refine-explanation':'Benutze die Maus um Deine Suche zu verfeinern.',
			'filter-word-explanation':'<strong>Links-Klick</strong> erlaubt das Wort.',
			'block-word-explanation':'<strong>Rechts-Klick</strong> verbietet das Wort.',
			'block-word-explanation-shift':'<strong>Shift</strong>+<strong>Links-Klick</strong> verbietet das Wort.',
            'filter-site-button':'Nur auf dieser Seite suchen',
            'block-site-button':'Alle Ergebnisse dieser Seite ausschließen',
            'play-video-site-button':'Dieses Video abspielen',
            'playlist-video-site-button':'Video zur Wiedergabeliste hinzufügen',
            'inline-filter-text':'Links-Klick um auch nach dem Wort zu suchen, Rechts-Klick um das Wort zu verbieten.',
            'quick-remove-keyword-button':'Dieses Wort verbieten.',
            'quick-add-keyword-button':'Auch nach diesem Wort suchen.',
            'youtube-title-does-not-allow-to-play-external':'Abspielen deaktiviert',
            'youtube-body-does-not-allow-to-play-external':'Der Youtube-Benutzer hat deaktiviert, dass man dieses Video auf externen Seiten (wie koala) anschauen kann.',
            'open-in-new-window':'In neuem Fenster/Tab öffnen',
            'notify-title-search-reseted':'Suche zurückgesetzt',
            'notify-body-search-reseted':'Alle Suchfilter und der Suchbegriff wurden zurückgesetzt.',
            'notify-title-language-switched':'Sprache geändert',
            'notify-body-language-switched':'Die Sprache wurde auf Deutsch umgestellt.',
            'notify-title-no-results':'Kein Ergebnis!',
            'notify-body-no-results':'Leider gab es auf Google dafür kein Ergebnis.',
            'notify-title-no-more-results':'Keine neuen Ergebnis!',
            'notify-body-no-more-results':'Leider gab es keine weiteren Ergebnisse auf Google.',
            'notify-title-autosearch-more':'Suche ...',
            'notify-body-autosearch-more':'Suche mehr Ergebnisse für %searchterm%.',
            'notify-title-added-to-playlist':'Hinzugefügt!',
            'notify-body-added-to-playlist':'Das Video wurde zu deiner Wiedergabeliste hinzugefügt.',
            'search-more':'Weiter suchen!',
            'filter-did-you-mean':'Meintest Du: <strong>%searchterm%</strong>?',
            'filter-did-you-mean-no-button':'Nein',
            'filter-did-you-mean-yes-button':'Ja',
            'playlist-remove':'Löschen: Dieses Video aus der Wiedergabeliste entfernen.',
            'playlist-stop':'Stop: Wiedergabe anhalten.',
            'playlist-next':'Weiter: Nächstes Video abspielen.',
            'playlist-random':'Zufällig: Ein zufälliges Video aus der Wiedergabeliste abspielen.'
		},
		'uk':true,
		'us':true
	},
	
	language: '',
	
	switchLanguage : function (new_lang, refresh) {
		$('koala-flag-'+koala.language).tween('opacity','1.0','0.15');
		koala.language = new_lang;
		$('koala-flag-'+koala.language).fade('in');
		
		koala.t = koala.translations[koala.language];
		
		var t = koala.t; 
		
		$('koala-search-button').set('value', t['search-button']);
		$('sub-header').set('text', t['sub-header']);
		if ($defined($('koala-refine-header'))) {
			$('koala-refine-header').set('text',t['refine-header']);
		}
		if ($defined($('koala-block-words-header'))) {
			$('koala-block-words-header').set('text',t['block-words-header']);
		}
		if ($defined($('koala-filter-words-header'))) {
			$('koala-filter-words-header').set('text',t['filter-words-header']);
		}
		if ($defined($('koala-block-sites-header'))) {
			$('koala-block-sites-header').set('text',t['block-sites-header']);
		}
		
		if ($defined($('koala-search-reset-button'))) {
			$('koala-search-reset-button').set('title',t['reset-search-header']);
		}
		
		if ($defined($('koala-refine-hint'))) {
			$('koala-refine-hint').set('html', t['refine-explanation']+'<br/>'+t['filter-word-explanation']+'<br/>'+(koala.helper_canRightClick() ? t['block-word-explanation'] : t['block-word-explanation-shift']));
		}
		
		if ($defined($('koala-playlist-button-remove'))) {
			$('koala-playlist-button-remove').set('title',t['playlist-remove']);
			$('koala-playlist-button-next').set('title',t['playlist-next']);
			$('koala-playlist-button-stop').set('title',t['playlist-stop']);
			$('koala-playlist-button-random').set('title',t['playlist-random']);
		}
		
		if (refresh === undefined || refresh) koala.refresh(true);
	},
	
	notify_roar : null,
	
	notify: function(text, title, type_of_notify) {
		if (koala.notify_roar === null) {
			koala.notify_roar  = new Roar({
				position: 'lowerRight',
				slideDown: false,
				margin: {
					x: '25',
					y: '25'
				},
				duration: 5000
			});
		}
	 
		koala.notify_roar.alert(title, text);
	},
	
	helper_canRightClick: function() {
		return (navigator.userAgent.indexOf('Opera') > -1) ? false : true;
		
	},
	
	trackSearch: function() {
		try {
			pageTracker._trackPageview('search/'+(koala.language === '' ? 'world' : koala.language));
		} catch(err) {
		}
	},
	
	spellcheck: null,
	
	current_anchor: '',
	
	checkAnchor: function () {
		if (this.current_anchor === document.location.hash) {
		} else {
			this.current_anchor = document.location.hash;
			
			if (this.current_anchor.substr(0,3) === '#q/' && this.current_anchor.length>3) {
				koala.queryDirect(this.current_anchor.substr(3));
			}
		}
	},
	
	saved_settings: null,
	
	clearFilters : function () {
		koala.disabled_keywords = new Hash();
		koala.disabled_sites = new Hash();
		koala.filter_sites = new Hash();
		koala.keywords = new Hash();
		koala.filter_keywords = new Hash();
	},
	
	init : function () {
		$('body').set('morph', {
			transition: Fx.Transitions.Expo.easeOut
		});
		
		koala.disabled_keywords = new Hash();
		koala.disabled_sites = new Hash();
		koala.filter_sites = new Hash();
		koala.keywords = new Hash();
		koala.filter_keywords = new Hash();
		
		koala.query_cache = new Hash();
		
		koala.saved_settings = new Hash.Cookie('koalaSettings');
		
		koala.saved_settings.load();
		
		koala.t['us'] = koala.t[''];
		koala.t['uk'] = koala.t[''];
		
		$('koala-search-button').addEvent('click', function () {
			koala.refresh();
		});
		
		$('koala-input-text').addEvent('keyup', function (e) {
            if (e.code == 13) {
    			koala.refresh();
            }
		});
		
		var flags = new Element('div',{'id':'koala-flags-div'});
		
		var a_flag = new Element('img', {
			'src':'img/flag/uk.png',
			'id':'koala-flag-',
			'title':'Switch to English',
			'events':{
				'click':function () {
					koala.switchLanguage('', ($('koala-input-text').get('value')!='' ? true : false));
					koala.saved_settings.hash.set('language','');
					koala.saved_settings.save();
					koala.notify(koala.t['notify-body-language-switched'],koala.t['notify-title-language-switched']);
				}
			}
		});
		a_flag.setStyle('opacity','0.15');
		a_flag.inject(flags);
		
		var a_flag = new Element('img', {
			'src':'img/flag/de.png',
			'id':'koala-flag-de',
			'title':'In Deutsch suchen',
			'events':{
				'click':function () {
					koala.switchLanguage('de', ($('koala-input-text').get('value')!='' ? true : false));
					koala.saved_settings.hash.set('language','de');
					koala.saved_settings.save();
					koala.notify(koala.t['notify-body-language-switched'],koala.t['notify-title-language-switched']);
				}
			}
		});
		a_flag.setStyle('opacity','0.15');
		a_flag.inject(flags);
		
		flags.inject($('koala-input-div'));
		
		if (koala.saved_settings.hash.has('language')) {
			koala.switchLanguage(koala.saved_settings.hash.get('language'), false);
		} else {
			var language = navigator["language"] || navigator["userLanguage"] || "";
			if (language !== '' && $defined(koala.translations[language])) {
				koala.switchLanguage(language, false);
			} else {
				koala.switchLanguage('', false);
			}
		}
		
		var refine_explanation = new Element('div', {
			'class':'koala-hint',
			'id': 'koala-refine-hint',
			'style': 'display:none',
			'html': koala.t['refine-explanation']+'<br/>'+koala.t['filter-word-explanation']+'<br/>'+(koala.helper_canRightClick() ? koala.t['block-word-explanation'] : koala.t['block-word-explanation-shift'])
		});
		
		refine_explanation.inject($('koala-filter-div'),'before');
		
		if (document.location.hash.substr(0,3) === '#q/' && document.location.hash.length>3) {
			if (navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('Chrome') == -1  && navigator.userAgent.indexOf('Safari') == -1) {
				$('koala-input-text').set('value',document.location.hash.substr(3).replace(/\+/g," "));
			} else {
				$('koala-input-text').set('value',koala.helper_urldecode(document.location.hash.substr(3)).replace(/\+/g," "));
			}
		} else {
			var input_has_been_initialized = false;
			$('koala-input-text').addEvent('click', function () {
				if (!input_has_been_initialized) {
					$('koala-input-text').set('value','');
					input_has_been_initialized = true;
				}
			});
		}
		
		koala.checkAnchor.bind().periodical(300);
	},
	
	youtube_player: null,
	
	youtube_player_videoId: null,
	
	playYoutubeVideo: function(videoId) {
		koala.youtube_player_videoId = videoId;
		$('koala_video_player').fade('hide');
		$('koala-video-player-controls').fade('hide');
		
		$('koala_video_player').setStyles({'display':'block','left':$('koala-header').getPosition().x.toInt()+150,'top':window.getScroll().y+100});
		$('koala-video-player-controls').setStyles({'display':'block','left':$('koala-header').getPosition().x.toInt()+150,'top':window.getScroll().y+100+387});
		
		if (koala.youtube_player === null ) {
			var player_class = koala.debug ? YtMooDebugPlayer : YtMooPlayer;
			koala.youtube_player = new player_class('koala_video_player',{
				videoId: videoId,
				'onReady':function(){
					koala.youtube_player.playVideo(videoId);
				},
				'onError':function(){
					$('koala_video_player').fade('out');
					$('koala-video-player-controls').fade('out');
					koala.notify(koala.t['youtube-body-does-not-allow-to-play-external'], koala.t['youtube-title-does-not-allow-to-play-external']);
				}
			});
			
			var pause_video = new Element('img', {
				'class': 'koala-action-image',
				'src': 'img/big_pause_video.png',
				'id': 'koala-player-pauseplay-button',
				'alt': '[pause video]',
				'events': {
					'click': function () {
						if ($('koala-player-pauseplay-button').get('alt')=='[pause video]') {
							koala.youtube_player.pause();
							$('koala-player-pauseplay-button').set('alt','[play video]');                 
							$('koala-player-pauseplay-button').set('src','img/big_play_video.png');                 
						} else {
							koala.youtube_player.play();
							$('koala-player-pauseplay-button').set('alt','[pause video]');                 
							$('koala-player-pauseplay-button').set('src','img/big_pause_video.png');                 
						}
					}
				}
			});
			
			pause_video.inject($('koala-video-player-controls'));
			
			var playlist_video = new Element('img', {
				'class': 'koala-action-image',
				'src': 'img/big_playlist_video.png',
				'id': 'koala-player-playlist-button',
				'alt': '[playlist video]',
				'events': {
					'click': function () {
						koala.notify(koala.t['notify-body-added-to-playlist'], koala.t['notify-title-added-to-playlist']);
				
						koalaPlaylist.addVideo(koala.youtube_player_videoId);
						if (!koalaPlaylist.isInitialized()) {
							koalaPlaylist.next();
						}
					}
				}
			});
			
			playlist_video.inject($('koala-video-player-controls'));

			var stop_video = new Element('img', {
				'class': 'koala-action-image',
				'src': 'img/big_stop_video.png',
				'alt': '[stop video]',
				'events': {
					'click': function () {
						koala.youtube_player.stop();
						$('koala_video_player').fade('out');
						$('koala-video-player-controls').fade('out');
					}
				}
			});
			stop_video.inject($('koala-video-player-controls'));
			
		}
		$('koala_video_player').fade('in');
		$('koala-video-player-controls').fade('in');
		koala.youtube_player.playVideo(videoId);
	},
	
	helper_htmlspecialchars: function(text) {
		var el = new Element('span', {'text':text});
		var ret = el.get('html');
		el.destroy();
		return ret;
	},
	
	helper_urlencode: function(text) {
		if (encodeURIComponent) {
		    return encodeURIComponent(text);
		}
		return escape(text);
	},

	helper_urldecode: function(text) {
		if (decodeURIComponent) {
		    return decodeURIComponent(text);
		}
		return unescape(text);
	},
	
	blockSite: function (site, refresh) {
		koala.disabled_sites[site] = site;
		if (refresh === undefined || refresh) koala.refresh();
	},
	
	unblockSite: function (site, refresh) {
		delete koala.disabled_sites[site];
		if (refresh === undefined || refresh) koala.refresh();
	},
	
	filterSite: function (site, refresh) {
		koala.filter_sites[site] = site;
		if (refresh === undefined || refresh) koala.refresh();
	},
	
	unfilterSite: function (site, refresh) {
		delete koala.filter_sites[site];
		if (refresh === undefined || refresh) koala.refresh();
	},
	
	filterKeyword: function (keyword, refresh) {
		koala.filter_keywords[keyword] = keyword;
		if (refresh === undefined || refresh) koala.refresh();
	},
	
	fk: function(that,e) {
		if (e.preventDefault) e.preventDefault();
		
		if (e.shiftKey) {
			koala.blockKeyword($(that).get('text'));
		} else {
			koala.filterKeyword($(that).get('text'));
		}
		
		return false;
	},
	
	bk: function(that,e) {
		if (e.preventDefault) e.preventDefault();
		
		if (e.shiftKey) {
			koala.filterKeyword($(that).get('text'));
		} else {
			koala.blockKeyword($(that).get('text'));
		}
		
		return false;
	},
	
	unfilterKeyword: function (keyword, refresh) {
		delete  koala.filter_keywords[keyword];
		if (refresh === undefined || refresh) koala.refresh();
	},
	
	blockKeyword: function (keyword, refresh) {
		koala.disabled_keywords[keyword] = keyword;
		if (refresh === undefined || refresh) koala.refresh();
	},
	
	unblockKeyword: function (keyword, refresh) {
		delete koala.disabled_keywords[keyword];
		if (refresh === undefined || refresh) koala.refresh();
	},
	
	refresh: function(force) {
		koala.queryUrls($('koala-input-text').get('value'), force);
	},
	
	repaint: function() {
		$('koala-cloud-div').setStyle('display','block');
		$('koala-cloud-div').set('html','');
		var refine_text = new Element('div', {'class':"koala-refine-filter-header",'id':'koala-refine-header',text:koala.t['refine-header']});
		refine_text.inject($('koala-cloud-div'));
		
		koala.keywords_total_usage = 0;
		koala.keywords_total_max = 0;
		koala.keywords_total_min = 0;
		
		var filter_has_keyword_buttons = {};
		
		var filter_keywords_onhoverenter = function(event, that) {
			if (!filter_has_keyword_buttons[that.get('text')]) {
				event = new Event(event);
				
				var add_button = new Element('img', {
					'alt':'[add]',
					'title':koala.t['quick-add-keyword-button'],
					'src':'img/add.png',
					'class':'koala-keywords-quick-buttons',
					'events': {
						'click': function (event) {
							event = new Event(event);
							event.stop();
							that.fireEvent('click',event);
						},
						'mouseenter': function (event) {
							this.tween('opacity',1);
						},
						'mouseleave': function (event) {
							this.tween('opacity',0.5);
						}
					}
				});
				add_button.tween('opacity',0.5);

				var remove_button = new Element('img', {
					'alt':'[remove]',
					'title':koala.t['quick-remove-keyword-button'],
					'src':'img/remove.png',
					'class':'koala-keywords-quick-buttons',
					'events': {
						'click': function (event) {
							event = new Event(event);
							event.stop();
							that.fireEvent('contextmenu',event);
						},
						'mouseenter': function (event) {
							this.tween('opacity',1);
						},
						'mouseleave': function (event) {
							this.tween('opacity',0.5);
						}
					}
				});
				remove_button.tween('opacity',0.5);
				
				filter_has_keyword_buttons[that.get('text')] = {
						'addButton': add_button,
						'removeButton': remove_button
				};
				
				add_button.inject(that);
				remove_button.inject(that);
			} else {
				filter_has_keyword_buttons[that.get('text')].addButton.setStyle('display','inline');
				filter_has_keyword_buttons[that.get('text')].removeButton.setStyle('display','inline');
			}
		};
		
		var filter_keywords_onhoverleave = function(event, that) {
			if (filter_has_keyword_buttons[that.get('text')]) {
				filter_has_keyword_buttons[that.get('text')].addButton.setStyle('display','none');
				filter_has_keyword_buttons[that.get('text')].removeButton.setStyle('display','none');
			}
		};		
		
		var keywords_array = [];
		$each(koala.keywords, function (data) {
			keywords_array.push(data.word);
		});
		keywords_array.sort();
		
		var worst_best_keyword_count = 0;
		var worst_best_keyword_name = null;
		var best_keywords = {};
		var best_keywords_length = 0;
		
		
		
		$each(keywords_array, function (word) {
			if (typeof(word) !== 'function') {
				var data = koala.keywords[word];
				koala.keywords_total_usage = koala.keywords_total_usage + data.count;
				koala.keywords_total_max = (koala.keywords_total_max > data.count) ? koala.keywords_total_max : data.count; 
				koala.keywords_total_min = (koala.keywords_total_min < data.count) ? koala.keywords_total_min : data.count;
				if (best_keywords_length<7 || worst_best_keyword_count<data.count) {
					if (best_keywords_length<7) {
						best_keywords_length++;
					} else {
						delete best_keywords[worst_best_keyword_name];
					}
					best_keywords[word] = data.count;
					worst_best_keyword_name = word;
					worst_best_keyword_count = data.count;
					
					$each(best_keywords, function (count, word) {
						if (count<worst_best_keyword_count) {
							worst_best_keyword_name = word;
							worst_best_keyword_count = count;
						}
					});
				}
			}
		});
		
		keywords_array = [];
		
		$each(best_keywords, function (count, word) {
			keywords_array.push(word);
		});
		
		var total_max_distance = koala.keywords_total_max-koala.keywords_total_min;
		$each(keywords_array, function (word) {
			if (typeof(word) !== 'function' && koala.keywords[word].count>1) {
				var data = koala.keywords[word];
				var keyword = new Element('span',{
					'class':'keyword',
					'style':'font-size:'+(((((data.count-koala.keywords_total_min)/total_max_distance)+0.5)*10).round()/10)+'em',
					'text': data.word,
                    'title': koala.t['inline-filter-text'],
					'events': {
						'contextmenu': function (e) {
							e.preventDefault();
							koala.blockKeyword(data.word);
						},
						'click': function (e) {
							e.preventDefault();
							if (e.shift) {
								koala.blockKeyword(data.word);
							} else {
								koala.filterKeyword(data.word);
							}
						},
						'mouseenter': function(e) {
							filter_keywords_onhoverenter(e,this);
						},
						'mouseleave': function(e) {
							filter_keywords_onhoverleave(e,this);
						}
					}
				});
				
				keyword.inject($('koala-cloud-div'));
			}
		});
		
		$('koala-filter-div').set('html','');
		
		if (koala.spellcheck !== null) {
			var spellcheck_suggestion_text = koala.spellcheck;
			var spellcheck_text = new Element('div', {
				'class':"koala-spellcheck",
				'id':'koala-spellcheck',
				text:spellcheck_suggestion_text
			});
			spellcheck_text.set('html',koala.t['filter-did-you-mean'].replace(/%searchterm%/g, spellcheck_text.get('text')));
			var yes_spellcheck = new Element('input',{
				'value': koala.t['filter-did-you-mean-yes-button'],
				'type': 'button',
				'id': 'koala-spellcheck-yes',
				'events': {
					'click': function (e) {
						new Event(e).stop();
						$('koala-input-text').set('value', spellcheck_suggestion_text);
						koala.refresh();
					}
				}
			});
			var no_spellcheck = new Element('input',{
				'value': koala.t['filter-did-you-mean-no-button'],
				'type': 'button',
				'id': 'koala-spellcheck-no',
				'events': {
					'click': function (e) {
						new Event(e).stop();
						$('koala-spellcheck').dispose();
					}
				}
			});
			
			yes_spellcheck.inject(spellcheck_text);			
			no_spellcheck.inject(spellcheck_text);			
			spellcheck_text.inject($('koala-filter-div'));
		}
		
		var item_count = 0;
		var filter_words = new Element('div', {'id':'koala-filter-words'});
		
		$each(koala.filter_keywords, function (word) {
			if (typeof(word) !== 'function') {
				item_count++;
				var keyword = new Element('span',{
					'class':'keyword',
					'style':'font-size:1em',
					'text': word,
					'events': {
						'contextmenu': function (e) {
							e.preventDefault();
							koala.unfilterKeyword(word, false);
							koala.blockKeyword(word);
						},
						'click': function (e) {
							e.preventDefault();
							if (e.shiftKey) {
								koala.unfilterKeyword(word, false);
								koala.blockKeyword(word);
							} else {
								koala.unfilterKeyword(word);
							}
						}
					}
				});
				
				keyword.inject(filter_words);
			}
		});
		
		if (item_count>0) {
			var refine_text = new Element('div', {'class':"koala-refine-filter-header",'id':'koala-filter-words-header',text:koala.t['filter-words-header']});
			refine_text.inject(filter_words,'top');
			
			filter_words.inject($('koala-filter-div'));
		}
		
		
		var item_count = 0;
		var blocked_words = new Element('div', {'id':'koala-blocked-words'});
		
		$each(koala.disabled_keywords, function (word) {
			if (typeof(word) !== 'function') {
				item_count++;
				var keyword = new Element('span',{
					'class':'keyword',
					'style':'font-size:1em',
					'text': word,
					'events': {
						'contextmenu': function (e) {
							e.preventDefault();
							koala.unblockKeyword(word, false);
							koala.filterKeyword(word);
						},
						'click': function (e) {
							e.preventDefault();
							if (e.shiftKey) {
								koala.unblockKeyword(word, false);
								koala.filterKeyword(word);
							} else {
								koala.unblockKeyword(word);
							}
						}
					}
				});
				
				keyword.inject(blocked_words);
			}
		});
		
		if (item_count>0) {
			var refine_text = new Element('div', {'class':"koala-refine-filter-header",'id':'koala-block-words-header','text':koala.t['block-words-header']});
			refine_text.inject(blocked_words,'top');
			
			blocked_words.inject($('koala-filter-div'));
		}
		
		var item_count = 0;
		var blocked_sites = new Element('div', {'id':'koala-blocked-sites'});
		
		$each(koala.disabled_sites, function (site) {
			if (typeof(site) !== 'function') {
				item_count++;
				var keyword = new Element('span',{
					'class':'keyword',
					'style':'font-size:1em',
					'text': site,
					'events': {
						'contextmenu': function (e) {
							e.preventDefault();
							koala.unblockSite(site,false);
							koala.filterSite(site);
						},
						'click': function (e) {
							e.preventDefault();
							if (e.shiftKey) {
								koala.unblockSite(site,false);
								koala.filterSite(site);
							} else {
								koala.unblockSite(site);
							}
						}
					}
				});
				
				keyword.inject(blocked_sites);
			}
		});
		
		if (item_count>0) {
			var refine_text = new Element('div', {'class':"koala-refine-filter-header",'id':'koala-block-sites-header',text:koala.t['block-sites-header']});
			refine_text.inject(blocked_sites,'top');
			
			blocked_sites.inject($('koala-filter-div'));
		}
		
		var item_count = 0;
		var filter_sites = new Element('div', {'id':'koala-filter-sites'});
		
		$each(koala.filter_sites, function (site) {
			if (typeof(site) !== 'function') {
				item_count++;
				var keyword = new Element('span',{
					'class':'keyword',
					'style':'font-size:1em',
					'text': site,
					'events': {
						'contextmenu': function (e) {
							e.preventDefault();
							koala.unfilterSite(site,false);
							koala.blockSite(site);
						},
						'click': function (e) {
							e.preventDefault();
							if (e.shiftKey) {
								koala.unfilterSite(site,false);
								koala.blockSite(site);
							} else {
								koala.unfilterSite(site);
							}
						}
					}
				});
				
				keyword.inject(filter_sites);
			}
		});
		
		if (item_count>0) {
			var refine_text = new Element('div', {'class':"koala-refine-filter-header",'id':'koala-filter-sites-header',text:koala.t['filter-sites-header']});
			refine_text.inject(filter_sites,'top');
			
			filter_sites.inject($('koala-filter-div'));
		}
		
		$('koala-refine-hint').setStyle('display','block');
		$('koala-refine-hint').fade('in');
	},
	
	queryUrls : function (terms, force) {
		var q = terms;
		
		$each(koala.disabled_sites, function (site_url) {
			q = q + " -site:" + site_url;
		});
		
		$each(koala.filter_sites, function (site_url) {
			q = q + " site:" + site_url;
		});
		
		$each(koala.disabled_keywords, function (keyword) {
			q = q + " -" + keyword;
		});
		
		$each(koala.filter_keywords, function (keyword) {
			q = q + " " + keyword;
		});

		document.location = $('base').get('href')+"#q/"+koala.helper_urlencode(q);

		if (force !== undefined && force) {
			koala.queryDirect(koala.helper_urlencode(q));
		}
	},
	
	parseSearchResult: function(data, page, query) {
		var terms_used = {};
		$each($('koala-input-text').get('value').split(" "), function (term) {
			terms_used[term] = term;
		});
		
		var links_div = null;
		
		if (page === 1) {
			links_div = $('koala-links-div');
		} else {
			if (!$('koala-links-div-'+page)) {
				var before_div = $('koala-links-div');
				if (page !== 2) {
					before_div = $('koala-links-div-'+(page-1));
				}
				links_div = (new Element('div',{'id':'koala-links-div-'+(page),'class':'koala-links-div'}));
				links_div.inject(before_div,'after');
			} else {
				links_div = $('koala-links-div-'+page);
			}
		}
		links_div.fade('in');
		links_div.set('html','');
		
		var link_list = new Element('ul');
		
		koala.keywords = new Hash();
		
		var result_count = 0;
		
		if (data.spellcheck) {
			koala.spellcheck = data.spellcheck;
		} else {
			koala.spellcheck = null;
		}
			
		
		$each(data.results, function (data) {
			result_count++;
			
			var link_element = new Element('li');
			
			var site_parts = data.site.split(".");
			var site = site_parts[site_parts.length-2] + '.' + site_parts[site_parts.length-1];
			
			var title = new Element('div', {
				'class': 'url item-title'
			});
			
			var title_a = new Element('a', {
				'href': data.url,
				'text': data.title
			});
			
			title_a.inject(title);
			
			var link_image_a = new Element('a',{
				'href': data.url
			});
			
			var play_video = null;
			var playlist_video = null;
			
			if (site === 'youtube.com' && (data.url.match(/\?v\=([^&]+)/) || data.url.match(/\&v\=([^&]+)/))) {
					var video_id = data.url.match(/\?v\=([^&]+)/);
					if (!video_id) {
						video_id = data.url.match(/\&v\=([^&]+)/);
					}
					video_id = video_id[1];
					var link_image = new Element('img', {
						'class': 'url item-image',
						'src': 'http://i'+(Math.floor(Math.random()*4)+1)+'.ytimg.com/vi/'+koala.helper_urlencode(video_id)+'/default.jpg'
					});
					link_image.inject(link_image_a);
					link_image_a.inject(link_element);
					
					title.inject(link_element);
				
					var video_parts = data.url.match(/\?v\=([^&]+)/);

					// url: http://www.youtube.com/watch?v=VIDEOID
					var play_video = new Element('img', {
						'class': 'koala-action-image left-koala-action-image',
						'src': 'img/play_video.png',
						'alt': '[play video]',
                        'title': koala.t['play-video-site-button'],
						'events': {
							'click': function (e) {
								
								if (e.shift) {
									koala.notify(koala.t['notify-body-added-to-playlist'], koala.t['notify-title-added-to-playlist']);
									koalaPlaylist.addVideo(video_parts[1]);
									if (!koalaPlaylist.isInitialized()) {
										koalaPlaylist.next();
									}
								} else {
									koala.playYoutubeVideo(video_parts[1]);
								}
							}
						}
					});
					var playlist_video = new Element('img', {
						'class': 'koala-action-image left-koala-action-image',
						'src': 'img/playlist_video.png',
						'alt': '[playlist video]',
                        'title': koala.t['playlist-video-site-button'],
						'events': {
							'click': function (e) {
								koala.notify(koala.t['notify-body-added-to-playlist'], koala.t['notify-title-added-to-playlist']);
								
								koalaPlaylist.addVideo(video_parts[1]);
								if (!koalaPlaylist.isInitialized()) {
									koalaPlaylist.next();
								}
							}
						}
					});
			} else {
				// var link_image_src = (Math.random()>0.5) ? 'http://www.artviper.net/screenshots/screener.php?url='+koala.helper_urlencode('http://'+data.site)+'&w=100&h=60&sdx=1024&sdy=768&q=70&userID=xxxxx' : 'http://www.thumbizy.com/go_2.php?url='+koala.helper_urlencode(data.url)+'&size=inter_ss&full=NO&effect=NO&inter_size=YES';  
				// var link_image_src = (site.charCodeAt(0) % 2 == 0) ? 'http://www.artviper.net/screenshots/screener.php?url='+koala.helper_urlencode('http://'+site)+'&w=100&h=60&sdx=1024&sdy=768&q=70&userID=xxxxx' : 'http://www.thumbizy.com/go_2.php?url='+koala.helper_urlencode('http://'+site)+'&size=inter_ss&full=NO&effect=NO&inter_size=YES';  
				var link_image_src = 'http://snapcasa.com/get.aspx?code=5506&size=t&mark=1&url='+koala.helper_urlencode('http://'+site);  
				var link_image = new Element('img', {
					'class': 'url item-image',
					'style': 'display:none',
					'src': link_image_src,
					'events': {
						'load': function (e) {
							this.setStyles({'opacity':'0','display':'block'});
							this.fade('in');
						}
					}
				});
				link_image.inject(link_image_a);
				link_image_a.inject(link_element);
				
				title.inject(link_element);
			}
			
			var filter_sites_count = 0;
			
			koala.filter_sites.each(function (el) {
				if (typeof(el) !== 'function') {
					filter_sites_count++;
				}
			});
			
			var html_summary = koala.helper_htmlspecialchars(data.summary);
			
			html_summary = html_summary.replace(/([^\s\,\.\%\-\*\+\#\$\§\"\'\!\(\)\/\\=}\{\`\´\:\;]+)/g,'<span class="fk" onclick="return koala.fk(this,event);" oncontextmenu="return koala.bk(this,event)" title="'+koala.t["inline-filter-text"]+'">$1</span>');

			$each(data.keywords, function (keyword) {
				if (koala.disabled_keywords[keyword] === undefined && koala.filter_keywords[keyword] === undefined && terms_used[keyword] === undefined) {
					koala.keywords[keyword] = koala.keywords[keyword] || {count:0, word:keyword}
					koala.keywords[keyword].count++;
				}
			});
			
			var summary = new Element('div', {
				'class': 'url item-summary',
				'html': html_summary
			});
			
			summary.inject(link_element);
			
			if (play_video !== null) {
				var play_buttons = new Element('div', {
					'style': 'float:left; clear:left; width:60px;'
				});	
				play_video.inject(play_buttons);
				playlist_video.inject(play_buttons);
				
				play_buttons.inject(link_element);
			}
			
			var url = new Element('div', {
				'class': 'url item-url'
			});
			var url_text = data.url;
			
			if (url_text.length>40) {
				url_text = url_text.substr(0,25) + '...' + url_text.substr(url_text.length-10);
			}
			var url_link = new Element('a', {
				'href': data.url,
				'text': url_text
			});
			url_link.inject(url);
			
			var new_window_img = new Element('img', {
				'class': 'koala-action-image',
				'src': 'img/new_window.png',
				'alt': '[new window]'
			});
			
			var new_window = new Element('a', {
				'href': data.url,
                'title': koala.t['open-in-new-window'],
                'style': 'margin-right:0',
                'target': '_blank'
			});
			
			new_window_img.inject(new_window);
			new_window.inject(url);
			
			if (filter_sites_count == 0) {
				var block_site = new Element('img', {
					'class': 'koala-action-image',
					'src': 'img/block_site.png',
					'alt': '[block site]',
                    'title': koala.t['block-site-button'],
					'events': {
						'click': function () {
							koala.blockSite(site);
						}
					}
				});
				
				block_site.inject(url);
				
				var filter_site = new Element('img', {
					'class': 'koala-action-image',
					'src': 'img/filter_site.png',
					'alt': '[filter site]',
                    'title': koala.t['filter-site-button'],
					'events': {
						'click': function () {
							koala.filterSite(site);
						}
					}
				});
				
				filter_site.inject(url);
			}
			
			url.inject(link_element);	
			
			link_element.inject(link_list);
		});
		
		if (result_count !== 0) {
			link_list.inject(links_div);
			var search_more_button_div = new Element('div',{'class':'koala-find-more-button-div'});
			var search_more_button = new Element('input', {
				'value': koala.t['search-more'],
				'type': 'button',
				'class': 'koala-find-more-button',
				'events':{
					'click': function () {
						koala.queryDirect(query, page + 1);
						koala.notify(koala.t['notify-body-autosearch-more'].replace(/%searchterm%/g,query), koala.t['notify-title-autosearch-more']);
						search_more_button_div.fade('hide');
					}
				}
			}).inject(search_more_button_div);
			
			search_more_button_div.inject(link_list);
			koala.repaint();
			koala.trackSearch();		
		} else {
			if (page == 1) {
				koala.notify(koala.t['notify-body-no-results'], koala.t['notify-title-no-results']);
			} else {
				koala.notify(koala.t['notify-body-no-more-results'], koala.t['notify-title-no-more-results']);
			}
		}
	},
	
	queryDirect: function (q, p) {
		var p = p || 1;
		var lang = koala.language;
		
		if (koala.query_cache[lang] === undefined) {
			koala.query_cache[lang] = {}
		}

		if (koala.query_cache[lang] === undefined) {
			koala.query_cache[lang] = {}
		}
		if (koala.query_cache[lang][q] === undefined) {
			koala.query_cache[lang][q] = {}
		}
		
		if (koala.query_cache[lang][q][p] !== undefined) {
			koala.parseSearchResult(koala.query_cache[lang][q][p], p, q);
		} else {
			new Request.JSON({url:$('base').get('href')+koala.searchengines[koala.searchengine]+'?'+(koala.language === '' ? '' : 'r='+koala.language+'&')+'p='+p+'&'+'q='+q,
				onComplete: function (data) {
					koala.query_cache[lang][q][p] = data;
					koala.parseSearchResult(koala.query_cache[lang][q][p], p, q);
				}
			}).get();	
		}

		var links_div = $('koala-links-div');
		if (p !== 1) {
			links_div = $('koala-links-div-' + p);
		} else {
			var was_visible_page = 2;
			while ($('koala-links-div-' + was_visible_page)) {
				$('koala-links-div-' + was_visible_page).dispose();
				was_visible_page++;
			}
		}
		if (links_div) {
			links_div.fade('hide');
			links_div.setStyle('display','block');
		}
		
		$('body').morph({
			'background-position':'0 -140px',
			'background-position-y':'-140px',
			'padding-top':19
		});
	}	
}

window.addEvent('domready', koala.init.bind());
window.addEvent('domready', koalaPlaylist.init.bind());

window.addEvent('domready', function () {
	var reset_search_function = function (e) {
		e = new Event(e);
		e.stop();
		koala.clearFilters();
		$('koala-links-div').setStyle('display','none');
		var was_visible_page = 2;
		while ($('koala-links-div-' + was_visible_page)) {
			$('koala-links-div-' + was_visible_page).dispose();
			was_visible_page++;
		}
		$('koala-cloud-div').setStyle('display','none');
		$('koala-refine-hint').setStyle('display','none');
		if ($defined($('koala-blocked-words'))) $('koala-blocked-words').destroy();
		if ($defined($('koala-filter-words'))) $('koala-filter-words').destroy();
		if ($defined($('koala-filter-sites'))) $('koala-filter-sites').destroy();
		if ($defined($('koala-blocked-sites'))) $('koala-blocked-sites').destroy();
		document.location = $('base').get('href')+'#q/';
		$('koala-input-text').set('value','');
		
		$('body').morph({
			'background-position':'0 0',
			'background-position-y':'0',
			'padding-top':159
		});
		
		koala.notify(koala.t['notify-body-search-reseted'],koala.t['notify-title-search-reseted']);

		$('koala-input-text').fireEvent('click');
	    $('koala-input-text').focus();
	};
		
	$('koala-search-reset-button').addEvent('click', reset_search_function);
	$('koala-header-link').addEvent('click', reset_search_function);

    $('koala-input-text').fireEvent('click');
    $('koala-input-text').focus();
});

