//TODOs:
// - simple pages (about, news) umbauen (analog simplePages in core.js)
// - iframe pages umbauen (analog simplePages in core.js)

var feedpage = "None";
var boxoedict = {"dm7080":"oe_2.5", "dm520":"oe_2.5", "dm525":"oe_2.5", "dm820":"oe_2.5", "dm900":"oe_2.5", "dm920":"oe_2.5", "one":"oe_2.6", "two":"oe_2.6"};
var devicedict = {"dm7080":"dm7080", "dm520":"dm520", "dm525":"dm520", "dm820":"dm820", "dm900":"dm900", "dm920":"dm920", "one":"dreamone", "two":"dreamtwo"};

var AVPreferredModes = Class.create({
	initialize: function(){
		this.preferredmodes = [];
		this.isPreferredModesLoading = false;
		this.callbacks = [];
		
		this.prefmodesprovider = new AVSettingsPreferredModesProvider(this.onPreferredModesAvailable.bind(this));
	},
	
	onPreferredModesAvailable: function(preferredmodes){
		debug("[AVPreferredModes].onPreferredModesAvailable");
		this.isPreferredModesLoading = false;
		this.preferredmodes = preferredmodes.getArray();
		var len = this.callbacks.length;
		for(var i = 0; i < len; i++){
			callback = this.callbacks.pop();
			callback(this.preferredmodes);
		}
	},
	
	getPreferredModes: function(callback, mode, preferredonly){
		this.callbacks[this.callbacks.length] = callback;
		if(!this.isPreferredModesLoading) {
			this.prefmodesprovider.load({"mode": mode, "preferredonly" : preferredonly });
			this.isPreferredModesLoading = true;
		}
	}
});


// merlin core

var MerlinCore = Class.create({
	initialize: function(name){
		// Check WebIf Version
		if (typeof core == "undefined"){
			alert("Old WebInterface found!\nPlease update the WebInterface Plugin first.");
			return;
		}
		// Start Merlin WebIf
		// Instantiate all elements
		this.menu = new MerlinMenuController('contentMerlinMenu');
		this.about = new AboutPage('contentMerlinContent');
		this.feed = new FeedPage('contentMerlinContent');
		this.feednav = new FeedNavPage('navContent');
		this.settingsnav = new MerlinSettingsNavPage('navContent');
		this.settings = new MerlinSettingsController('contentMerlinContent');
		this.channellistsettings = new ChannellistSettingsController('contentMerlinContent');
		this.dmmsettings = new DMMSettingsController('contentMerlinContent');
		this.avsettings = new AVSettingsController('contentMerlinContent');
		this.preferredmode = new AVSettingsPreferredModeHandler();
		this.avsettingspm = new AVPreferredModes();
		this.piconmapper = new PiconMapperController('contentMerlinContent');
		this.infonav = new InfoNavPage('navContent');
		this.meminfo = new MemoryInfoController('contentMerlinContent');
		this.sessionProvider = new SessionProvider( this.onSessionAvailable.bind(this) );
		this.sessionProvider.load({});
	},
	
	onSessionAvailable: function(sid){
		debug("[MerlinWebinterface].onSessionAvailable, " + sid)
		global_sessionid = sid;
		
		// Display menu
		this.menu.load();
		// Register Events
		this.registerEvents();
	},
	
	registerEvents: function(){
		var contentmerlinnavi = $('navContent');
		var device = merlincore.getDevice();
		contentmerlinnavi.on(
			'click',
			'.boxfeed',
			function(event, element){
				if(opener)
				{
					var dirname = devicedict[device];
					this.setFeedPage(dirname, device);
					this.feed.load($('contentMerlinContent'));
				}
			}.bind(this)
		);
		contentmerlinnavi.on(
			'click',
			'.all',
			function(event, element){
				this.setFeedPage("all", device);
				this.feed.load($('contentMerlinContetnt'));
			}.bind(this)
		);
		contentmerlinnavi.on(
			'click',
			'.mipsel',
			function(event, element){
				if(opener)
				{
					var mipselfeed = "cortexa15hf-neon-vfpv4";
					if (device == "dm820"  || device == "dm7080" || device == "dm520" || device == "dm525" )
					{
						mipselfeed = "mips32el";
					}
					else if (device == "dm900" || device == "dm920")
					{
						mipselfeed = "cortexa15hf-neon-vfpv4";
					}
					else {
						mipselfeed = "armv7vehf-neon-vfpv4";
					}
					this.setFeedPage(mipselfeed,device);
					this.feed.load($('contentMerlinContent'));
				}
			}.bind(this)
		);
		contentmerlinnavi.on(
			'click',
			'.third-party',
			function(event, element){
				var thirdpartyfeed = "merlin4-thirdparty";
				this.setFeedPage(thirdpartyfeed,device);
				this.feed.load($('contentMerlinContent'));
			}.bind(this)
		);		
		contentmerlinnavi.on(
			'click',
			'.merlin4-plugins',
			function(event, element){
				this.setFeedPage("merlin4-plugins",device);
				this.feed.load($('contentMerlinContent'));
			}.bind(this)
		);		
		contentmerlinnavi.on(
			'click',
			'.merlin4-skins',
			function(event, element){
				this.setFeedPage("merlin4-skins",device);
				this.feed.load($('contentMerlinContent'));
			}.bind(this)
		);				
		contentmerlinnavi.on(
			'click',
			'.merlinsettings',
			function(event, element){
				this.settings.loadList($('contentMerlinContent'));
			}.bind(this)
		);		
		contentmerlinnavi.on(
			'click',
			'.channellistsettings',
			function(event, element){
				this.channellistsettings.loadList($('contentMerlinContent'));
			}.bind(this)
		);
		
		contentmerlinnavi.on(
			'click',
			'.dmmsettings',
			function(event,element){
				this.dmmsettings.loadList($('contentMerlinContent'));
			}.bind(this)
		);
		
		contentmerlinnavi.on(
			'click',
			'.avsettings',
			function(event,element){
				this.avsettings.loadList($('contentMerlinContent'));
			}.bind(this)
		);
		
		contentmerlinnavi.on(
			'click',
			'.piconmapper',
			function(event,element){
				this.piconmapper.loadList($('contentMerlinContent'));
			}.bind(this)
		);
		
		var contentmerlin = $('contentMerlinContent');
		contentmerlin.on(
			'click',
			'.mSettingsButton',
			function(event, element){
				this.settings.save($('settingsEditForm'));
			}.bind(this)
		);
		contentmerlin.on(
			'click',
			'.mChannellistSettingsButton',
			function(event, element){
				this.channellistsettings.save($('settingsEditForm'));
			}.bind(this)
		);
		contentmerlin.on(
			'click',
			'.mAVSettingsButton',
			function(event, element){
				this.avsettings.save($('settingsEditForm'));
			}.bind(this)
		);
		contentmerlin.on(
			'change',
			'select[name="config.av.preferred_modes_only"]',
			function(event, element){
				debug('changed');
				var portelement = document.getElementById('config.av.videoport_select');
				var portvalue = portelement.options[portelement.selectedIndex].value;
				debug('portvalu', element.options[element.selectedIndex].value);
				this.preferredmode.updateModes(portvalue, element.options[element.selectedIndex].value);
			}.bind(this)
		);
	},
	
	getFeedPage: function(){
		return feedpage;
	},
	
	resetNavigation: function(id, text){
		
		$(id).update('<div class="block center fullwidth oneliner">' + text + '</div>');
	},
	
	setFeedPage: function(dir,device){
		var oe = boxoedict[device];
		var devicepath = devicedict[device];
		var feedurl = "http://feed.dreamboxtools.de/" + oe + "/deb/";
		feedpage = feedurl + devicepath + "/" + dir;
	},
	
	getDevice: function(){
		var device = "unknown";
		if (opener) {
			device = opener.core.deviceInfo.info.devicename;
		}
		return device;
	},
	
	getPreferredModes: function(mode){
		
	}
	
});

// controllers

var MerlinMenuController  = Class.create(Controller, {
	initialize: function($super, target){
		$super(new MerlinMenuHandler(target));
	},
	
	back: function(){
		window.close();
	},
	
	load: function(){
		this.handler.load({});
	},
	
	feed: function(){
		merlincore.feednav.load();
		merlincore.feed.load();
	},
	
	about: function(){
		merlincore.about.load();
	},
	
	settings: function(){
		merlincore.settingsnav.load();
		merlincore.settings.loadList();
	},
	
	merlininfo: function(){
		merlincore.infonav.load();
		merlincore.meminfo.loadList();
	},

	registerEvents: function(){
		$('back').on(
			'click',
			function(event, element){
				this.back();
			}.bind(this)
		);
		$('back').title = "Return to Dreambox Webcontrol";

		$('feed').on(
			'click',
			function(event, element){
				this.feed();
			}.bind(this)
		);
		$('feed').title = "Show Merlin Feed";
		
		$('settings').on(
			'click',
			function(event, element){
				this.settings();
				//this.settings.loadList.bind(this.settings);
			}.bind(this)
		);
		$('settings').title = "Show Merlin Settings";

		$('merlininfo').on(
			'click',
			function(event, element){
				this.merlininfo();
			}.bind(this)
		);
		$('merlininfo').title = "Show Merlin info";
		
		$('about').on(
			'click',
			function(event, element){
				this.about();
			}.bind(this)
		);
		$('about').title = "Some information about author, license, support...";
	},
	
	onFinished: function(){
		merlincore.about.load();
	}
});

var MerlinSettingsController = Class.create(Controller, {
	initialize: function($super, target){
		$super(new MerlinSettingsListHandler(target));
		this.merlinsettingshandler = new MerlinSettingsHandler(target, this.loadList.bind(this), []);
	},
	
	loadList: function(){
		$('headermerlincontent').innerHTML = "Merlin-Settings";
		this.handler.load({});
	},
	
	save: function(element){
		debug("MerlinSettingsController.save");
		//alert(element);
		
		this.merlinsettingshandler.commitForm(element);
	},
});

var ChannellistSettingsController = Class.create(Controller, {
	initialize: function($super, target){
		$super(new ChannellistSettingsListHandler(target));
		this.channellistsettingshandler = new ChannellistSettingsHandler(target, this.loadList.bind(this), []);
	},
	
	loadList: function(){
		$('headermerlincontent').innerHTML = "Channel Settings";
		this.handler.load({});
	},
	
	save: function(element){
		debug("ChannellistSettingsController.save");
		
		this.channellistsettingshandler.commitForm(element);
	}
});

var PiconMapperController = Class.create(Controller, {
	initialize: function($super, target){
		$super(new PiconMapperListHandler(target));
		this.piconmapperhandler = new PiconMapperHandler(target, this.loadList.bind(this), []);
	},
	
	loadList: function(){
		$('headermerlincontent').innerHTML = "Picon Mapper";
		this.handler.load({});
	},
});

var DMMSettingsController = Class.create(Controller, {
	initialize: function($super, target){
		$super(new DMMSettingsListHandler(target));
		this.dmmsettingshandler = new DMMSettingsHandler(target, this.loadList.bind(this), []);
	},
	
	loadList: function(){
		$('headermerlincontent').innerHTML = "DMM-Settings";
		this.handler.load({});
	},
	
	save: function(element){
		debug("DMMSettingsController.save");
		
		this.dmmsettingshandler.commitForm(element);
	}
});

var AVSettingsController = Class.create(Controller, {
	initialize: function($super, target){
		$super(new AVSettingsListHandler(target));
		this.avsettingshandler = new AVSettingsHandler(target, this.loadList.bind(this), []);
	},
	
	loadList: function(){
		$('headermerlincontent').innerHTML = "AV Settings";
		this.handler.load({});
	},
	
	save: function(element){
		debug("AVSettingsController.save");
		
		this.avsettingshandler.commitForm(element);
	},
		
	updateModes: function(port, preferredOnly){
		this.avsettingshandler.updateModes(port, preferredOnly);
	},
});

var MemoryInfoController = Class.create(Controller, {
	initialize: function($super, target){
		$super(new MemDevicesListHandler(target));
	},
	
	loadList: function(){
		$('headermerlincontent').innerHTML = "Merlin-Info: Memory";
		this.handler.load({});
	}
});

// pages
var AboutPage = Class.create({
	initialize: function(target){
		this.simpleHandler = new MerlinSimplePageHandler(target);
	},

	show: function(tpl, data){
		if(!data)
			data = {};
		this.simpleHandler.show(tpl, data);
	},

	load: function(){
		merlincore.resetNavigation('navContent','');
		$('navHd').innerHTML = "Merlin About";
		$('headermerlincontent').innerHTML = "Merlin WebIf About";
		this.show('tplAbout');
	},
});

var FeedNavPage = Class.create({
	initialize: function(nav){
		this.simpleHandler = new MerlinSimplePageHandler(nav);
	},
	
	show: function(tpl, data){
		if(!data)
			data = {};
		this.simpleHandler.show(tpl, data);
	},
	
	load: function(){
		$('navHd').innerHTML = "Merlin-Feeds";
		this.show('tplNaviMerlinFeed');
	},
	
});

var FeedPage = Class.create({
	initialize: function(content){
		this.simpleHandler = new MerlinSimplePageHandler(content);
	},
	
	show: function(tpl, data){
		if(!data)
			data = {};
		this.simpleHandler.show(tpl, data);
	},
	
	load: function(){
		$('headermerlincontent').innerHTML = "Merlin-Feeds";
		this.show('tplMerlinFeed');
	},
});

var InfoNavPage = Class.create({
	initialize: function(nav){
		this.simpleHandler = new MerlinSimplePageHandler(nav);
	},
	
	show: function(tpl, data){
		if(!data)
			data = {};
		this.simpleHandler.show(tpl, data);
	},
	
	load: function(){
		$('navHd').innerHTML = "Merlin-Info";
		this.show('tplNaviMerlinInfo');
	},
});

var MerlinSettingsNavPage = Class.create({
	initialize: function(nav){
		this.simpleHandler = new MerlinSimplePageHandler(nav);
	},
	
	show: function(tpl, data){
		if(!data)
			data = {};
		this.simpleHandler.show(tpl, data);
	},
	
	load: function(){
		$('navHd').innerHTML = "Merlin-Settings";
		this.show('tplNaviMerlinSettings');
	},
});