
var netcastMenu;


/**
 * Externals Controller
 * 
 */

var Externals = Class.create(Controller, {
	initialize: function($super, target){
		$super(new NetcastPluginsHandler(target));
		this.loaded = false;
	},

	load: function(){
		if(!this.loaded)
			this.handler.load({});
		else
			this.handler.show(this.handler.data);
	},

	onFinished: function(){
		this.loaded = true;
	}
});

/**
 * Netcasts Controller
 * 
 */

var Netcasts = Class.create(Controller, {
	initialize: function($super, listTarget, navTarget){
		$super(new NetcastListHandler(listTarget));
		this.externals = new Externals('NetcastExternalPlugins');
		this.navHandler = new NavNetcastHandler('navContent');
		this.simpleHandler = new NetcastSimpleRequestHandler();
		this.simpleEditHandler = new NetcastSimpleRequestHandler(true);
		this.simpleRemoveHandler = new NetcastSimpleRequestHandler(true);
	},

	ext: function () {
		this.externals.load();
	},				
							
	play: function (url) {
		this.simpleHandler.load('/netcast/web/play', {'url' : url});
	},

	addFavo: function (para) {
		this.simpleHandler.load('/netcast/web/add', para);
	},
	
	editFavo: function (oldname, name, url) {
		this.simpleEditHandler.load('/netcast/web/edit', {'oldname' : oldname, 'name' : name, 'url' : url});
	},
							
	removeFavo: function (name) {
		this.simpleRemoveHandler.load('/netcast/web/remove', {'name' : name});
	},

	setList: function(state){
		netcastcore.currentNetcastList = state;
	},
	
	load: function(filter){
		this.handler.load({'netcast' : filter});
		this.addFilterInput();
	},

	loadFavo: function(){
		setContentHd('Favorites');
		this.setList(netcastcore.FAVO);
		this.load('favo');
	},

	loadTop: function(){
		setContentHd('Top');
		this.setList(netcastcore.ONLINE);
		this.load('top');
	},

	loadGenre: function(){
		setContentHd('Genre');
		this.setList(netcastcore.GENRE);
		this.load('genre');
	},

	loadNav: function(){
		setNavHd('DreamNetcast');
		this.navHandler.onFinished = [this.externals.load.bind(this.externals)];
		this.navHandler.load();
	},

	onFilterFocus: function (event){
		event.element().value = '';
	},

	filter: function (event){
		var needle = event.element().value;
		if (event.keyCode == Event.KEY_RETURN) {
			setContentHd('Stations - Filter: \''+ unescape(needle) +'\'');
			this.setList(netcastcore.ONLINE);
			window.location.href = '/netcast/#!/stations/search?filter=' + needle.replace(' ', '%20');
		};
	},

	addFilterInput: function(){
		var input = new Element('input');
		input.id = 'pkgFilter';
		input.value = 'Filter Stations';
		$('contentHdExt').update(input);
		input.on('focus', this.onFilterFocus.bind(this));
		input.on('keyup', this.filter.bind(this));
	},

	search: function (needle){
			setContentHd('Stations - Filter: \''+ unescape(needle) +'\'');
			this.setList(netcastcore.ONLINE);
			window.location.href = '/netcast/#!/stations/search?filter=' + needle.replace(' ', '%20');
			this.load(needle.replace(' ', '%20'));
	},

	sort: function (by){
		this.handler.sort(by);
	},
});

/**
 * CurrentNetcast Controller
 * 
 */

var CurrentNetcast = Class.create(Controller, {
	initialize: function($super, curTarget, volTarget){
		$super(new CurrentNetcastHandler(curTarget, volTarget));
		this.handler.onFinished[this.handler.onFinished.length] = this.onFinished.bind(this);
		this.display = 'none';
	},

	load: function(){
		this.handler.load({});
	},

	toggleVisibility: function(element){
		debug('toggleVisibility - start');
		var ext = $('trExtCurrent');
		var title = $('trExtCurrentTitle');
		if(ext){
			//debug('toggleVisibility - ext');
			var bullet = element.down('.currentBulletToggle');
			if(ext.visible()){
				bullet.src = '/web-data/img/toggle_expand.png';
				bullet.alt = "+";
				ext.hide();
				title.show();
			}else{
				bullet.src = '/web-data/img/toggle_collapse.png';
				bullet.alt = "-";
				ext.show();
				title.hide();
			}
			this.display = ext.style.display;
			setMaxHeight('contentMain');
		}
	},

	onFinished: function(){
		setMaxHeight('contentMain');
		var ext = $('trExtCurrent');
		if(ext){
			ext.style.display = this.display;
			var bullet = $('currentName').down('.currentBulletToggle');
			if(ext.visible()){
				bullet.src = '/web-data/img/toggle_collapse.png';
				bullet.alt = "-";
			}else{
				bullet.src = '/web-data/img/toggle_expand.png';
				bullet.alt = "+";
			}
		}
		netcastcore.currentData = this.handler.data;
	}
});

/**
 * NetcastCore Class
 * 
 */

var NetcastCore = Class.create(E2WebCore, {
	initialize: function(){
		this.mode = "";
		this.subMode = "";
		this.volume = new Volume('volContent');
		this.epg = new EPG(new EpgListHandler());
		this.netcasts = new Netcasts('contentMain');
		this.current = new CurrentNetcast('currentContent', 'volContent');
		this.settings = new NetcastSettingsHandler('contentMain');
		this.saveSetting = new NetcastSimpleRequestHandler();
		this.saveSort = new NetcastSimpleRequestHandler();
		this.sessionProvider = new SessionProvider( this.onSessionAvailable.bind(this) );
		//this.remote = new RemoteControl(); 377

		this.FAVO=0;
		this.ONLINE=1;
		this.GENRE=2;
		this.NONE=3;
		this.currentNetcastList = this.FAVO;
		this.currentNetcast = {};

		//create required Instances
		this.navlut = {
			'stations': {
				'top' : this.netcasts.loadTop.bind(this.netcasts),
				'genre' : this.netcasts.loadGenre.bind(this.netcasts),
				'favo' : this.netcasts.loadFavo.bind(this.netcasts),
				'settings' : this.settings.load.bind(this.settings),
				'search' : this.searchNetcast.bind(this)
			}
		};
	},

	loadFavo: function(){
		this.netcasts.loadFavo();
	},

	searchNetcast: function(){
		var needle = hashListener.getHash().replace(/.+filter\=/,'');
		if(needle != '')
			this.netcasts.search(needle);
	},

	updateItems: function(){
		debug("[NetcastCore].updateItems");
		netcastcore.current.load();
	},

	onHashChanged: function(isReload){
		var hash = hashListener.getHash();
		var parts = hash.split("/");

		var len = parts.length;
		debug('[onHashChanged:hash]' + hash);
		debug('[onHashChanged:parts]' + parts);
		debug('[onHashChanged:len]' + len);
		if(len >= 2){
			var mode = parts[1];
			if(mode != this.mode || isReload || (len <= 2 && this.subMode != '') ){
				this.switchMode(mode, len == 2);
				this.subMode = '';
			}
			this.mode = mode;
			if(len > 2){
				var subMode = parts[2];
				debug("[NetcastCore].subMode - parts[2] " + parts[2]);
				if(subMode != this.subMode || isReload){
					this.subMode = subMode.replace(/\?.+/,'');
					if(!this.navlut[this.mode][this.subMode]){
						return;
					} else {
						if(this.mode != 'settings')
							this.navlut[this.mode][this.subMode]();
					}
				}
				if(len > 3){
					debug("[NetcastCore].subMode - parts[3] " + parts[3]);
					switch(this.mode){
					case 'stations':
						if(subMode == 'settings'){
							debug("[NetcastCore].subMode == 'settings'");
						}
						event.stop();
						break;
					default:
						return;
					}
				}
				debug("[onHashChanged:this.mode"+this.mode);
				debug("[onHashChanged:subMode"+subMode)
			}
		}
	},

	getBaseHash: function(){
		var hash = ['#!', this.mode].join("/");
		if(this.subMode != ''){
			hash = [hash, this.subMode].join("/");
		}
		debug("[getBaseHash:hash] "+hash);
		return hash;
	},

	loadDefault: function(){
		debug("[NetcastCore].loadDefault");
		window.location.href='/netcast/#!/stations/favo';
	},

	run: function(){
		debug("[NetcastCore].run");
				this.sessionProvider.load({});
	},

	onSessionAvailable: function(sid){
				debug("[NetcastCore].onSessionAvailable, " + sid)
				global_sessionid = sid;

		if (typeof document.body.style.maxHeight == undefined) {
			alert("Due to the tremendous amount of work needed to get everthing to " +
			"work properly, there is (for now) no support for Internet Explorer Versions below 7");
		}
		hashListener.onHashChanged = this.onHashChanged.bind(this);
		hashListener.init();

		this.registerEvents();

		if(!hashListener.getHash().length >= 1)
			this.loadDefault();
		else
			//this.netcasts.loadNav();

		this.startUpdateCurrentPoller();
		this.updateItems();
	},

	registerEvents: function(){
		debug("[NetcastCore].registerEvents");
		//Hash-Reload-Fix
		//HACK :: THIS IS EVIL VOODOO, DON'T TRY THIS AT HOME! => I HAD TO TOOK THAT EVIL, I HAD HAVE NEEDED ;-)
		document.on(
			'click',
			'a',
			function(event, element){
				var parts = element.href.split('#');
				var curHost = window.location.href.split('#')[0];
				debug("parts, curHost "+parts+ " "+curHost);
				//Don't do this crazy stuff when the target is another host!
				if(curHost == parts[0]){
					debug("curHost == parts[0]"+parts[0]+ " "+curHost);
					if (parts.length > 1){
						if(parts[1] != ''){
							if(window.location == element.href){
								this.onHashChanged(true);
								debug("[if window.location == element.href]" + window.location);
								return;
							}else{
								window.location == element.href;
								debug("[else window.location element.href]" + window.location + " == " + element.href);
								return;
							}
						} else {
							debug("[parts[1] != ''else-> element.href window.location]" + element.href + " " + window.location);
							element.href = window.location;
						}
						debug("[parts.length > 1, return false;");
						return false;
					}
				}
			}.bind(this)
		);
		//Current
		$('current').on(
			'click',
			'.currentExtShowHide',
			function(event, element){
				this.current.toggleVisibility(element);
				event.stop();
			}.bind(this)
		);

		//EPG-Search
		$('epgSearchForm').on(
			'submit',
			function(event, element){
				this.epg.search($F('epgSearch'));
				event.stop();
			}.bind(this)
		);
		$('epgSearch').on(
			'focus',
			function(event, element){
				element.value = "";
			}.bind(this)
		);
		$('epgSearchClear').on(
				'click',
				function(event, element){
					$('epgSearch').value = '';
					return false;
				}.bind(this)
		);
		//Volume
		$('navVolume').on(
			'click',
			'a.volume',
			function(event, element){
				this.volume.set(element.readAttribute('data-volume'));
				event.stop();
				return false;
				
			}.bind(this)
		);
		//WebTv
		$('webTv').on(
			'click',
			function(event, element){
				window.open('/web-data/tpl/default/streaminterface/index.html', 'WebTV', 'scrollbars=no, width=800, height=740');
				event.stop();
			}.bind(this)
		);
		//main Content
		var content = $('contentMain');
		//Settings
		content.on(
			'click',
			'.saveSettings',
			function(event, element){
				this.saveSettings();
			}.bind(this)
		);
		//Netcast Link
		content.on(
			'click',
			'a.sNetcastLink',
			function(event, element){
				this.currentNetcast = new iNetcast(element);
				if((this.currentNetcast.url !== '') || (this.currentNetcast.id !== '')){
					if(this.currentNetcast.url !== '')
						this.netcasts.play(this.currentNetcast.url);
					else
						this.netcasts.play(this.currentNetcast.base+'?id='+this.currentNetcast.id);
					this.updateItems();
				}
				else
					this.netcasts.search(this.currentNetcast.name);
				
				event.stop();
			}.bind(this)
		);
		//Remove Favorits
		content.on(
			'click',
			'a.sRemoveFavoLink',
			function(event, element){
				var rm = new iNetcast(element.up(3).down(4));
				this.netcasts.removeFavo(rm.name);
			}.bind(this)
		);
		//Edit Favorits
		content.on(
			'click',
			'a.sEditFavoLink',
			function(event, element){
				var edit = new iNetcast(element.up(3).down(4));
				var name = prompt("Edit Favorit Name:									", edit.name);
				if (name==null) {
					event.stop();
					return;
				}
				var url = prompt("Edit Favorit Url:										", edit.url);
				if (((url==null) && (name==edit.name)) || ((name==edit.name) && (url==edit.url))) {
					event.stop();
					return;
				}
				if (url==null)
					url=edit.url;
				
				this.netcasts.editFavo(edit.name, name, url);
				
			}.bind(this)
		);
		//Add Favorits
		content.on(
			'click',
			'a.sAddFavoLink',
			function(event, element){
				var add = new iNetcast(element.up(3).down(4));
				var name = add.name;
				if(add.url !== '')
					this.netcasts.addFavo({'name' : name, 'url' : add.url});
				else if(add.id !== '')
					this.netcasts.addFavo({'name' : name, 'url' : add.base+'?id='+add.id});
				else
					this.netcasts.addFavo({'name' : name, 'url' : 'none' });
				event.stop();
			}.bind(this)
		);

		$('navContainer').on(
			'click',
			'a.sNetcastFiltersLink',
			function(event, element){
				if (this.currentNetcastList < 3) {
					var by = parseInt(element.readAttribute('data-sort'));
					var img = $('NetcastFilterImg');
					if (by > 1)
						by = 0;
					else
						by +=1;
					this.netcasts.sort(by);
					element.title = netcastMenu.sort_txt +': ' + netcastMenu.Sorter[by];
					element.innerHTML = '';
					element.appendChild(img);
					element.innerHTML += ' ' + netcastMenu.Sorter[by];
					element.setAttribute('data-sort', String(by));
					this.saveSorted(by);
					event.stop();
				}
			}.bind(this)
		);
	},

	switchMode: function(mode, initContent){
		if(initContent){
			this.setEmptyContent('contentMain', 'please select a submenu on the left...');
			setContentHd('...');
		}

		switch(mode){
		case "stations":
			debug('[switchMode] mod=stations');
			this.netcasts.loadNav();
			break;
		case "settings":
			window.location.href='/netcast/#!/stations/settings';
			break;

		default:
			break;
		}
	},

	saveSettings: function(){
		if ($('recPathNetcast')){
			this.saveSetting.load('/netcast/web/save',
				{ 'bitrate' : $('bitrateNetcast').value,
					'onlympeg' : $('onlyMpegNetcast').checked == true ? 1 : 0,
					'conststream' : $('constRecNetcast').checked == true ? 1 : 0,
					'recdir' : $('recPathNetcast').value,
					'background' : $('mviPathNetcast').value 
			});
		}
		else {
			this.saveSetting.load('/netcast/web/save',
				{ 'bitrate' : $('bitrateNetcast').value,
					'onlympeg' : $('onlyMpegNetcast').checked == true ? 1 : 0,
					'background' : $('mviPathNetcast').value 
			});
		};

	},

	saveSorted: function(by){
		this.saveSort.load('/netcast/web/sort',
				{ 'by' : by 
		});
	}
});

var netcastcore = new NetcastCore();
