var manager = {
	widgets: [],
	loadedWidget: undefined,
	init: function( config ){
		// Set up loader
		Loader.init( "#loadingOverlay", "#loadingText" );

		// Configure the control buttons
		var maxButtons = 4;
		for(var i = 0; i < config.length; i++)
		{
			// Add the plus items if more than 4 widgets
			if( config.length > maxButtons && i == maxButtons ){
				var plusItem = { 
					type: "Plus",
					slug: "plus",
					manager: this
				};
				var plusWidget = this.addMenuItem( plusItem, true, "plus_tmpl", config.slice(i) /* The rest of the widgets */ );
				plusWidget.bindUI();
			}
			this.addMenuItem( config[i], i >= maxButtons ? false : true, "container_tmpl" );
		}

		this.bindUI();

		// Load the first widget
		$(".tabBarView")[0].style.display = "block"; // Show the tabBarView
		if (config.length > 0)
		{
			this.loadWidget(config[0].slug);
			$.addClass( $(".tabBarControls li#btn" + config[0].slug + " a")[0], "selected" );
		}
		// Installer message
		if (window.navigator.userAgent.indexOf('iPhone') > 0 && !window.navigator.standalone)
		{
			var installation = $("#installation");
			var hide = this.hideInstaller;
			installation.style.display = "block";
			$.on(installation, "click", hide);
			setTimeout(function(){
				$.addClass(installation, "not-standalone");
				setTimeout(hide, 5000);
			}, 1500);
		}
	},
	addMenuItem: function( item, blnAddNavIcon, templateName, templateData ){
		var li = document.createElement("li"),
			a = document.createElement("a"),
			container = document.createElement("div");
		if(blnAddNavIcon){
			li.setAttribute("id", "btn" + item.slug);
			a.href = "#";
			a.innerHTML = "<img src='/public/images/buttons/" + item.slug + ".png'/>";
			li.appendChild(a);
			$(".tabBarControls")[0].appendChild(li);
		}
		container.setAttribute("id", item.slug);

		$(".tabBarPages")[0].appendChild(container);
		var widget = new window[item.type + "Widget"](item);
		this.widgets.push( widget );
		fillTemplate('#' + container.id, templateName, {"widget" : templateData || widget});
		
		return widget;
	},
	bindUI: function(){
		// Stop scrolling
		document.addEventListener('touchmove', function(e){ e.preventDefault(); });

		var _this = this;
		$.each(".tabBarControls li", function(li) {
		    $.on(li,"click", function(){
				$.each(".tabBarControls a.selected", function(item){ $.removeClass( item,"selected");} );
				$.addClass(this.querySelector("a"),"selected");
				_this.loadWidget(li.id.substring(3));
			});
		});
		$.on("#back", "click", function() {
			_this.toggleBackButton(false);
			Strike.back();
		});
	},
	loadWidget: function( slug ){
		var widget = null;
		for( var i = 0; i < this.widgets.length; i++ ){
			if( this.widgets[ i ].slug === slug ){
				widget = this.widgets[ i ];
				break;
			}
		}
		if (widget)
		{
			if (this.loadedWidget)
			{
				this.loadedWidget.unload();
			}
			widget.init();
			this.loadedWidget = widget;
			this.toggleBackButton(false);
		}
	},
	toggleBackButton : function(activate)
	{
		$("#back").style.display = activate ? "block" : "none";
	},
	hideInstaller : function()
	{
		var installation = $("#installation");
		$.addClass(installation, "timeout");
		setTimeout(function() { installation.style.display = "none"; }, 500);
	}
};

// TODO: this needs to go into the zen-mobile or Strike "control" library
function fillTemplate( element_id, template, data ){
	//$( element_id ).innerHTML = Strike.tmpl( template, data );
	Strike.template(element_id, template, data);
	setTimeout(function(){
		Strike.bindScrollers(element_id);
	},100);

}

// Spinner
var Loader = {
	// Animation
	init: function( container, textEl ){
		this.container = container;
		var containerEl = document.querySelector(container),
			canvas = containerEl.querySelector("canvas"),
			ctx = this.context = canvas.getContext('2d');
		this.textEl = containerEl.querySelector(textEl);

		var w = this.w = canvas.width,
			h = this.h = canvas.height,
			l = w/10;
		ctx.translate(w/2, h/2);
		ctx.lineWidth = l;
		ctx.lineCap = 'round';
		ctx.strokeStyle = 'rgb(255,255,255)';
	},
	dessine : function() {
		var ctx = this.context,
			w = this.w,
			h = this.h;
		ctx.clearRect(-w/2, -h/2, w, h);
		ctx.globalAlpha = 1;
		ctx.rotate( -(Math.PI/6)*11);

		for(var i=0; i<12; i++) {
			ctx.beginPath();
			ctx.moveTo(0, -(w/2)*0.5);
			ctx.lineTo(0, -(w/2)*0.9);
			ctx.stroke();
			ctx.closePath();
			ctx.rotate(-Math.PI/6);
			ctx.globalAlpha -= 1/12;
		}
	},
	start: function(message) {
		this.textEl.innerHTML = message || "chargement";
		Strike.showOverlay( this.container );
		var _this = this;
		this.theInterval = setInterval(function(){ _this.dessine(); }, 100);
	},
	stop: function() {
		Strike.hideOverlay();
		clearInterval( this.theInterval );
	}
};

