//handle target
var target = false;
var refreshInterval = null;




//CHARGEMENT DE LA PAGE
$(function(){

	if($.page()!='index' || $.urlParam('module')!=null) return;
	dashboard_dashboardwidget_search();
		
	$('#dashboardView li').click(function(){
		$('#dashboardView li').removeAttr('data-selected');
		$(this).attr('data-selected',1);
		dashboard_dashboardwidget_search();
	});
	$('#widgetList').change(function(){
		var option = $('#widgetList option:selected').data();
		option.text = $('#widgetList option:selected').text();
		$('.widgetDescription').removeClass('hidden');
		$('.widgetDescription h1 span').text(option.text);
		$('.widgetDescription h1 i').attr('class',option.icon);
		$('.widgetDescription p').text(option.description);
		$('.widgetDescription .widgetColor small').css('background-color',option.background);
		$('.widgetDescription .widgetColor span').text(option.background);
	});

	$('#dashboard').sortable({
		update:function(event,ui){
			var data = dashboard_dashboardwidget_save_position();
		}
	});
	$( ".widget" ).disableSelection();

});


function init_setting_dashboard(){
	dashboard_dashboard_search();
}

//Enregistrement des configurations
function dashboard_setting_save(){
	$.action({ 
		action : 'dashboard_setting_save', 
		fields :  $('#dashboard-setting-form').toJson() 
	},function(){ $.message('info','Configuration enregistrée'); });
}


/** DASHBOARD **/
	
//Récuperation d'une liste de dashboard dans le tableau #dashboards
function dashboard_dashboard_search(callback){
	
	$('#dashboards').fill({
		action:'dashboard_dashboard_search'
	},function(){
		if(callback!=null) callback();
	});

}

//Ajout ou modification d'élément dashboard
function dashboard_dashboard_save(){
	var data = $('#dashboard-form').toJson();
	$.action(data,function(r){
		$.message('success','Enregistré');
		dashboard_dashboard_search();
		$('#dashboard-form').attr('data-id','');
	});
}

//Récuperation ou edition d'élément dashboard
function dashboard_dashboard_edit(element){
	var line = $(element).closest('tr');
	$.action({action:'dashboard_dashboard_edit',id:line.attr('data-id')},function(r){
		$.setForm('#dashboard-form',r);
		$('#dashboard-form').attr('data-id',r.id);
	});
}


//Suppression d'élement dashboard
function dashboard_dashboard_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest('tr');
	$.action({
		action : 'dashboard_dashboard_delete',
		id : line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Élement supprimé');
	});
}

/** DASHBOARDWIDGET **/
	
//Récuperation d'une liste de dashboardwidget dans le tableau #dashboardwidgets
function dashboard_dashboardwidget_search(callback){
	
	var dashboard = $('#dashboardView li[data-selected]').attr('data-id');
	if(!dashboard || dashboard=='') return;
	$.action({
				action : 'dashboard_dashboardwidget_search',
				dashboard : dashboard
			},function(r){
				$('#dashboard .widget:visible').remove();
				for(var i in r.rows){
					var widget = r.rows[i];
					dashboard_dashboardwidget_append(widget);
					dashboard_dashboardwidget_load(widget);
				}
				clearInterval(refreshInterval);
				refreshInterval = setInterval(function(){
					$.action({
						action : 'dashboard_dashboardwidget_refresh',
						dashboard : $('#dashboardView li[data-selected]').attr('data-id')
					},function(r){

						for(var id in r.rows){
							var widget = r.rows[id];

							if(widget.widget){
								var header = $('.widget[data-id="'+id+'"]').find('.widget_header'); 
								if(widget.widget.title) header.find('span').text(widget.widget.title);
								if(widget.widget.icon) header.find('i').attr('class','fa '+widget.widget.icon);
								if(widget.widget.background) header.css('backgroundColor',widget.widget.background);
							}

							if(widget.callback){
								if(window[widget.callback]!=null) window[widget.callback]($('.widget[data-id="'+id+'"]'),widget.data);
							}
							
						}


					});
				},3000);
			});
}


//Mise à jour des infos d'un élement widget à partir d'un object data
function dashboard_dashboardwidget_render(widget,data){
	widget.attr('data-id',data.id);
	widget.removeClass (function (index, css) {
		return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
	});
	widget.attr('data-id',data.id)
	.attr('data-load',data.load)
	.attr('data-configure',data.configure)
	.attr('data-delete',data.delete)
	.addClass('col-md-'+data.width)
	.find('.widget_header')
	.css('background',data.background)
	.find('i:eq(0)').attr('class','fa '+data.icon);
		
	widget.find('.widget_header span:eq(0)').html(data.title);
	widget.find('.widget_content').html(data.content);
		
	var options = '';
	for(var k in data.options){
		var option = data.options[k];
		options+='<li onclick="'+option.function+'"><i class="fa '+option.icon+'"></i> '+option.label+'</li>';
	}

	if(data.configure) options+="<li title='Configurer' onclick='configure_widget(this);'><i class='fa fa-wrench'></i></li>";
	options+="<li title='Supprimer' onclick='dashboard_dashboardwidget_delete(this);'><i class='fa fa-times'></i></li>";

	widget.find('.widget_options').html(options);
		
	widget.data('data',data);
	widget.show();
	return widget;
}

//Modification d'un widget existant
function dashboard_dashboardwidget_update(data){

	var widget = $('.widget[data-id="'+data.id+'"]');

	var data = $.extend(widget.data('data'), data);
	dashboard_dashboardwidget_render(widget,data);
}

//Ajout ou modification d'élément dashboardwidget
function dashboard_dashboardwidget_save(){
	var data = $('#dashboardwidget-form').toJson();
	$.action(data,function(r){
		
		
			$('#dashboardwidget-form').attr('data-id','');
			dashboard_dashboardwidget_search();
		
		$.message('success','Enregistré');
	});
}

//Chargement du contenu php du widget
function dashboard_dashboardwidget_load(widget){
	$.getJSON(widget.load,$.extend(widget,{content:''}),function(r){
		dashboard_dashboardwidget_update(r);
		var data = $.extend($('.widget[data-id="'+widget.id+'"]').data('data'), r.widget);
		var init = 'widget_'+widget.model+'_init';
		if(window[init]!=null) window[init]();
	});
}

//Ajout (manuel par l'user) d'un widget
function dashboard_dashboardwidget_add(){
	$.action({
		action : 'dashboard_dashboardwidget_add',
		dashboard : $('#dashboardView li[data-selected]').attr('data-id'),
		widget : $('#widgetList').val()
	},function(r){
		if(r.message) $.message('info',r.message);
		$('#dashboard_dashboardwidget_appendModal').modal('hide');
		dashboard_dashboardwidget_search();
	});
}



//Ajout (depuis le code) d'un widget
function dashboard_dashboardwidget_append(data){
	var tpl = $('#dashboard .widget:hidden').get(0).outerHTML;
	var widget = $(tpl);
	$('#dashboard').append(widget);
	if(data.js!=null){
		for(k in data.js){
			var js = data.js[k];
			if($('script[src="'+js+'"]').length!=0) continue;
			var jsFile= document.createElement('script');
			jsFile.setAttribute("type","text/javascript");
			jsFile.setAttribute("src", js);
			document.getElementsByTagName("body")[0].appendChild(jsFile);
		}
	}
		
	if(data.css!=null){
		for(k in data.css){
			var css = data.css[k];
			if($('script[src="'+css+'"]').length!=0) continue;
			var cssFile= document.createElement('link');
			cssFile.setAttribute("rel","stylesheet");
			cssFile.setAttribute("type","text/css");
			cssFile.setAttribute("href", css);
			document.getElementsByTagName("body")[0].appendChild(cssFile);
		}
	}

	
	dashboard_dashboardwidget_render(widget,data);
}

//Récuperation ou edition d'élément dashboardwidget
function dashboard_dashboardwidget_edit(widget){
	var line = $(element).closest('tr');
	$.action({action:'dashboard_dashboardwidget_edit',id:line.attr('data-id')},function(r){
		$.setForm('#dashboardwidget-form',r);
		$('#dashboardwidget-form').attr('data-id',r.id);
	});
}

//Suppression d'élement dashboardwidget
function dashboard_dashboardwidget_delete(element){
	var element = $(element).closest('.widget');
	var data = element.data('data');
	
	$.action({
		action : 'dashboard_dashboardwidget_delete',
		dashboard : $('#dashboardView li[data-selected]').attr('data-id'),
		widget : data.id,
	},function(r){
		element.remove();
		if(r.message) $.message('info',r.message);
		if(data.delete != null){
			$.getJSON(data.delete,$.extend(data,{content:''}));
		}
	});
}



//Enregistrement de toutes les positions de widget
function dashboard_dashboardwidget_save_position(){
	var positions = [];
	$('.widget:visible').each(function(i,element){
		positions.push({id:$(element).attr('data-id'),position:$(element).index()});
	});
	
	$.action({
		action : 'dashboard_dashboardwidget_save_position',
		dashboard : $('#dashboardView li[data-selected]').attr('data-id'),
		positions : positions,
	},function(r){
		
	});

}