/*  Netzsprecher.de version 1.0.0 (c) 2008 Jonas Girnatis */

var Netzsprecher = {
	init: function(){
		var ref = this;

		this.addGlobalEventHandlers();

 		//loadModules
		this.initPageLoadModule();

		//ie6 fixes
		if(typeof ltie7 != 'undefined'){ try{ fixIE(); }catch(e){} }

		if($('embed_sample_home')){
			$('embed_sample_home').update('<iframe src="' + SGL_JS_WEBROOT + '/' + (SGL_JS_FRONT_CONTROLLER != '' ? SGL_JS_FRONT_CONTROLLER + '/' : '') + 'widget/type/myspeaker/id/800008/amount/4/" frameborder="0"></iframe>');
		}
		
		$('content').select('input[title]').each(function(input){
			input.onfocus = function() { ref.showFormTip(this); };
			input.onblur = function() { ref.hideAllFormTips(); };				
		});
		
		$('content').select('.action_show_tooltip').invoke('observe', 'click', function(e){ this.previous('input').focus(); e.stop(); });


	},

	pageLoadModules: [],

	addPageLoadModule: function(obj){
		this.pageLoadModules.push(obj);
	},

	initPageLoadModule: function(){
		this.pageLoadModules.invoke('init');
	},

	addGlobalEventHandlers: function(){
		var ref = this;
		$('stage').select('.externicon').invoke('observe', 'click', function(e){ window.open(this.href); e.stop(); } );
		$('stage').select('.action_confirm').invoke('observe', 'click', function(e){ if(!confirm('Wirklich löschen?')){ e.stop(); } } );
		$('stage').select('.action_report_comment').invoke('observe', 'click', function(e){ ref.reportComment(this); e.stop(); } );
		
		if($('testspeaker_messages')){
			window.setInterval(function(){
				new Ajax.Request(Netzsprecher.getAjaxUrl({module: 'netzsprecher', action: 'getTestspeakerUpdates'}), { 
					onSuccess: function(req){
						$('testspeaker_messages').update(req.responseText).select('.action_play_comment').invoke('observe', 'click', function(e){
							NetzsprecherPlayer.playpauseComment(this); e.stop();
						});
						
					}
				});
			}, 5000);
		}
		
		if($('faq')){
			$('faq').down('select').observe('change', function(e){ ref.showFaqEntry(this); } );
			$('faq').select('li').invoke('hide');
			$('faq').down('li').show();
		}
	},

	toggleRegisterCard: function(link, targetContainer){
		var targetCard = $(link).up();
		if(targetCard.hasClassName('current')) { return false };

		targetCard.addClassName('current').adjacent('li').invoke('removeClassName', 'current');

		if(targetContainer){
			targetContainer.adjacent('.toggleable').invoke('hide');
			targetContainer.show();
		}
		link.blur();
		return false;
	},

	makeUrl: function(params){
		//  calling -> makeUrl({'module':'mymodule', 'action':'generateReport', 'param2': 'foo bar'});
		var url = SGL_JS_WEBROOT;
		var moduleName  =  (params.module) ? params.module : '';
		var managerName =  (params.manager) ? params.manager : moduleName;
		url += SGL_JS_FRONT_CONTROLLER ? '/' + SGL_JS_FRONT_CONTROLLER : '';
		url += '/' + encodeURI(moduleName) + '/' + encodeURI(managerName) + '/';
		for (var x in params) {
			if ((x == 'module') || (x =='manager')) { continue; }
			url += encodeURI(x) + '/' + encodeURI(params[x]) + '/';
		}
		return url;
	},

	getAjaxUrl: function(params){
		var aSessId = SGL_JS_SESSID.split('=');
		params[aSessId[0]] = aSessId[1];

		return this.makeUrl(params);
	},

	popUp: function(url, options){
		options = options || {};
		var width = options.width || 400;
		var height = options.height || 300;
		var left = options.left || 0;
		var top = options.top || 0;
		var resizable = options.resizable || 'yes';
		var location = options.location || 'no';
		var scrollbars = options.scrollbars || 'no';
		var status = options.status || 'no';

		var name = options.name || 'popup';

		var popup = window.open(url, name, 'width='+width+',height='+height+',left='+left+',top='+top+',resizable='+resizable+',location='+location+',scrollbars='+scrollbars+',status='+status);
		popup.focus();
	},

	reportComment: function(a){
		var id = a.id.replace(/report_id_/, '');
		new Ajax.Request(Netzsprecher.getAjaxUrl({module: 'netzsprecher', action: 'reportVoiceComment', frmVoicecommentId: id}));
	},


	showFormTip : function(obj){
		this.hideAllFormTips();
		
		var formTip = new Element('div', { 'class': 'formtip', id: 'formtip'}).update('<div>' + obj.title + '</div>');
		obj.insert({before: formTip});
	},
	
	hideAllFormTips : function(){
		$('formtip') ? $('formtip').remove() : null;
	},


	showToolTipHelp: function(a){
		$('tool_tip_help') ? $('tool_tip_help').remove() : null;
		var div = new Element('div', { 'class': 'tool_tip_help', id: 'tool_tip_help', style: 'display: none;' });
		a.insert(div.update(a.title).appear({duration: 0.2, queue: {limit: 1, scope: 'help'}}));
		a.setStyle({position: 'relative'})
	},
	
	hideToolTipHelp: function(){
		$('tool_tip_help') ? $('tool_tip_help').fade({duration: 0.2, queue: {limit: 1, scope: 'help'}}) : null;
	},
	
	showFaqEntry: function(select){
		var id = select.value.replace(/#/,'');
		$(id).show().siblings().invoke('hide');
		//window.location.hash = id;
		//Effect.ScrollTo(select.value.replace(/#/,''));
	}
}

document.observe("dom:loaded", function() { Netzsprecher.init(); } );

var NetzsprecherPlayer = {
	init: function(){
		var ref = this;
		if($('footer')) { this.embedPlayer(); }
		$('stage').select('.action_play_comment').invoke('observe', 'click', function(e){ ref.playpauseComment(this); e.stop(); });
		$('stage').select('.action_play_all_comments').invoke('observe', 'click', function(e){ ref.playpauseAllComments(this); e.stop(); });
	},

	embedPlayer: function(){
		var c = 0;
		var output = [];

		output[c++] = '<!--[if IE]>';
		output[c++] = '<object id="netzsprecher_flashBackend" name="netzsprecher_flashBackend" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="1" height="1">';
		output[c++] = '	<param name="movie" value="' + SGL_JS_WEBROOT + '/resources/player/player.swf" />';
		output[c++] = '	<param name="allowscriptaccess" value="always" />';
		output[c++] = '</object>';
		output[c++] = '<![endif]-->';
		output[c++] = '<!--[if !IE]>-->';
		output[c++] = '<object id="netzsprecher_flashBackend" name="netzsprecher_flashBackend" type="application/x-shockwave-flash" data="' + SGL_JS_WEBROOT + '/resources/player/player.swf" width="1" height="1">';
		output[c++] = ' <param name="allowscriptaccess" value="always" />';
		output[c++] = ' <param name="flashvars" value="id=netzsprecher_flashBackend" />';
		output[c++] = '</object>';
		output[c++] = '<!--<![endif]-->';

		var embedContainer = document.createElement('div');
		$('footer').appendChild(embedContainer);

		embedContainer.innerHTML = output.join('\n');

		this.player = $('netzsprecher_flashBackend');
	},

	playpauseComment: function(a){				
		if(a.hasClassName('button_stop')){
			this.player.sendEvent('stop');
			a.removeClassName('button_stop');
		}else{
			$('stage').select('.action_play_comment').invoke('removeClassName', 'button_stop');
			$('stage').select('.action_play_all_comments').invoke('removeClassName', 'button_stop');
			a.addClassName('button_stop');
			this.player.sendEvent('load', a.href);
			this.player.sendEvent('play');

			var id = a.id.match(/voicecomment_id_/) ? a.id.replace(/voicecomment_id_/, '') : a.id.replace(/voicemail_id_/, '');
			var type = a.id.match(/voicecomment_id_/) ? 'voicecomment' : 'voicemail';
			
			new Ajax.Request(Netzsprecher.getAjaxUrl({module: 'netzsprecher', action: 'addHit'}), { parameters: {frmVoiceId: id, type: type} });
		}
	},

	playpauseAllComments: function(a){
		var ref = this;
		if(a.hasClassName('button_stop')){
			this.player.sendEvent('stop');
			a.removeClassName('button_stop');
		}else{
			$('stage').select('.action_play_comment').invoke('removeClassName', 'button_stop');
			$('stage').select('.action_play_all_comments').invoke('removeClassName', 'button_stop');

			a.addClassName('button_stop');
			var anchors = a.up().next('.topic_container').select('.action_play_comment');
			var playlist = [];
			
			if(Object.isArray(anchors) && anchors.length > 0){
				anchors.reverse().each(function(a){
					playlist.push({file: a.href, type: 'sound'});
				});

				this.player.sendEvent('load', playlist);
				this.player.sendEvent('play');

			}
		}
	}
}
Netzsprecher.addPageLoadModule(NetzsprecherPlayer);

function getUpdate(typ,pr1,pr2,swf){
//	console.log(typ, pr1, pr2, swf);
}

//Header Search
var NetzsprecherHeaderSearch = {
	init: function(){
		var ref = this;

		/*
		$('searchselector').onclick = function(){ ref.toggleSearch(); };
		$('search_submit').onclick = function(){ ref.submitSearch(); return false; };
		$('search_form').onsubmit = function(){ ref.submitSearch(); return false; };
		*/
		if($('search_input')){
			$('search_input').onfocus = function(){ ref.focusSearch(this); };
			$('search_input').onblur = function(){ ref.blurSearch(this); };
		}
	},

	focusSearch: function(input){
		if(input.value == 'Suchen'){ input.value = ''; }
		input.addClassName('focus');
	},

	blurSearch: function(input){
		if(input.value == ''){ input.value = 'Suchen'; }
		input.removeClassName('focus');
	},

	submitSearch: function(){
		var ref = this;
		var query = $F('search_input') == 'Suchen' ? '' : $F('search_input');

		if($F('search_type') == '/in/FaqSearch'){
			var url = Netzsprecher.makeUrl({module: 'faq', action: 'list', filter: query});
			window.location.href = url;
		}else{
			window.location.href = $('search_form').action + encodeURIComponent(query) + $('search_type').value + '/';
		}
	}
}
Netzsprecher.addPageLoadModule(NetzsprecherHeaderSearch);


// Login Block
var NetzsprecherLoginBlock = {
	init: function(){
		var ref = this;

		if($('login_form')){
			//$('login_email').onkeypress = function(key) { if(key.keyCode == 13) { $('login_password').focus(); } };
			//$('login_password').onkeypress = function(key) { if(key.keyCode == 13) { $('login_form').submit(); } };
			$('login_submit').onclick = function(){ $('login_form').submit(); return false; };
		}
	}
}
Netzsprecher.addPageLoadModule(NetzsprecherLoginBlock);


var Cookie = {
	set: function(name, value, days) {
		var expire = '';
		if (days) {
			var d = new Date();
			d.setTime(d.getTime() + (days * 86400000));
			expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = encodeURI(name) + '=' + encodeURI(value || '') + expire + '; path=/');
	},

	get: function(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + encodeURI(name) + '=([^;\\s]*)'));
		return (cookie ? decodeURI(cookie[2]) : null);
	},

	del: function(name) {
		var cookie = this.get(name) || true;
		this.set(name, '', -1);
		return cookie;
	}
};

function fixIE() { document.execCommand("BackgroundImageCache", false, true); }