
var dashboards = {};
dashboards.list = [];
dashboards.datepickerranges = {};

dashboards.DashboardOptions = function(minimumDate, maximumDate){
	
	$("#dashopt-datepicker").daterangepicker({
	    "autoApply": true,
		opens: 'left',
		locale :{
			format: dateformat,
			customRangeLabel: ui.data.languages["_CUSTOM_RANGE"]
		},		
	    ranges: dashboards.datepickerranges,
	    startDate: minimumDate,
	    endDate: maximumDate
	},
	function(start, end) {	    
	    /* Edit the fields needed and click the reload button */
	    $(".report:not(.hidden-template)").each( function(){
	    	$(this).find(".report-options .fromRange").attr("value", start.format(dateformat) );
	    	$(this).find(".report-options .toRange").attr("value", end.format(dateformat) );
	    	$(this).find(".report-options .load-report").click();
	    });

	    $(".metric-report:not(#mini_report)").each( function(){
	    	report.OpenMetricReport( $(this).attr("report-label"), start.format(dateformat) , end.format(dateformat) );
			$(this).remove();
		});
		// update the default range		
		report.default_options.minimumDate = start.format(dateformat);
   		report.default_options.maximumDate = end.format(dateformat);
	});

	$("#dashopt-toggle").on("click", function(){
		/* Click all the collapse report buttons */
		var c = $( this ).find("i");

		if ( c.hasClass( "fa-minus" ) ) {
			c.removeClass( "fa-minus" );
			c.addClass( "fa-plus" );
			$(".report .box-body, .report:not(#report_template) .box-footer").slideUp();
		} else {
			c.removeClass( "fa-plus" );
			c.addClass( "fa-minus" );
			$(".report .box-body, .report:not(#report_template) .box-footer").slideDown();
			window.dispatchEvent(new Event('resize'));
		}	
	});

	$("#dashopt-close").on("click", function(){
		/* Click all the close report buttons */
		$(".report:not(#report_template) button[data-widget='remove']").click();
		$(".metric-report:not(#mini_report) .remove-mini").click();
	});

	$("#dashopt-export").on("click", function(){
		if(ui.BlockedBySubscription("PDF")){
			return false;
		} else {
			dashboards.PrintMode();
			window.dispatchEvent(new Event('resize'));
		}
	});

	// cycle through different layouts
	$("#dashopt-layout").on("click", function(){		
		//lets make more cols
		ncol = $(".content .connectedSortable").not(".hidden").size() -1;
		if (ncol == 7) {
			//time to reset
			$(".content .dashcol").removeClass("col-lg-7 col-lg-6 col-lg-5 col-lg-4 col-lg-3 col-lg-2 col-lg-1");
			$(".content .dashcol").not("#dashcol1, #dashcol2").addClass("hidden");
			$(".content #dashcol1").addClass("col-lg-7");
			$(".content #dashcol2").addClass("col-lg-5");
			ncol=2;
			i=1;
			$($(".content .dashcol .box.report").get().reverse()).each( function(){
				$(".content #dashcol"+i).append($(this));
				i++;
				if (i > ncol) {
					i=1;
				}
			});
			report.total_cols=3;
			window.dispatchEvent(new Event('resize'));
			return;
		}
		$(".content #dashcol"+ncol).removeClass("hidden");
		
		dashboards.SetLayout(ncol);

		i=1;
		$($(".content .dashcol .box.report").get().reverse()).each( function(){
			$(".content #dashcol"+i).append($(this));
			i++;
			if (i > ncol) {
				i=1;
			}
		});
		report.total_cols++;
		window.dispatchEvent(new Event('resize'));
		
	});

	/* -- Open the dashboard settings panel -- */
	$(".save-dashboard").on("click",function(){
		
		if (ui.data.hl==false) {
			ui.LicenseUpgrade();
			return false;
		}

		/* Show the settings area */
		ui.ShowWidget(".dashboard-settings");

		/* Edit the current dashboard */
		dashboards.EditDashboard($(".content-header .pagename").html());

		/* Disable dashboard options when it is not available in the subscriptions */
		if(ui.BlockedBySubscription("Dashboards", "Disabled", false)){				
			var msg = "<div class=\"callout-success-template callout callout-success btn-upgrade-subscription\" style='cursor:pointer'>"+ui.data.languages["_SUBSCRIPTION_UPGRADE_NOTICE"].replace("%x", "<strong>"+ ui.data.languages["_DASHBOARDS"] +"</strong>") + "<i class='fa fa-unlock-alt pull-right'></i></div>";
			$(".dashboard-settings .upgrade_message").html(msg);
			$(".dashboard-settings .upgrade_message").show();
			$(".dashboard-settings textarea").attr("disabled", "disabled");				
			$("input[name=dashboardname]").attr("disabled", "disabled");
			$("input[name=daterange_lock]").attr("disabled", "disabled");
			$("input[name=startup]").attr("disabled", "disabled");
			
		}
	});
	/* -- Close -- */

	/* -- Save the dashboard -- */
	$("body").on("click",".dashboard-settings .save-dash",function(e){
		e.preventDefault();

		if(ui.BlockedBySubscription("Dashboards")){
		 	$(".dashboard-settings textarea").removeAttr("disabled");
			$("input[name=dashboardname]").removeAttr("disabled");
			$("input[name=daterange_lock]").removeAttr("disabled");
			$("input[name=startup]").removeAttr("disabled");
		}
		if (ui.data.hl==false) {
			ui.LicenseUpgrade();
			return false;
		}		

		var f = $(this).parents("form").first();
		var f_data = f.serializeArray();
		var data = {};
		/* Get the report details from the form */
		$.each(f_data, function( k, v ) {
			data[v.name] = v.value;
		});

		
		if (data.private == "on") {			
			data.userid = ui.data.user.userid;					
		} else {
			data.userid = 0;
		}

		/* Loop through the cols to collect the reports */
		data.reports = dashboards.ListOpenReports();

		/* Loop through the cols to collect the mini reports */
		data.minis = dashboards.ListOpenMinis();

		dashboards.SaveDashboard(data["dashboardname"], data, function(r){
			var data = ui.ParseJSON(r);

			if(data.Status == "Success"){				
				dashboards.list[data.dashboard.name] = data.dashboard;
				ui.Callout({ Status: "Success", Message: "Saved " + data.dashboard.name });
			} else {
				ui.Callout(data);
			}

		});
		ui.HideWidget(".save-dashboard");
	});

	/* -- Open the manage dashboard panel -- */
	$(".manage-dashs").on("click",function(){	
		ui.ShowWidget(".manage-dashboards");
		dashboards.ManageDashboards();		
	});
		
}

dashboards.SetLayout = function(ncol) {

	var layout = Math.floor(12 / ncol);
	var rest = 12 - (layout * ncol);
	
	$(".content .dashcol").not(".hidden").each( function(){
		$(this).removeClass("col-lg-7 col-lg-6 col-lg-5 col-lg-4 col-lg-3 col-lg-2 col-lg-1");				
		if ($(this).attr("id")=="dashcol1") {
			$(this).addClass("col-lg-"+(layout+rest));
		} else {
			$(this).addClass("col-lg-"+layout);
		}
		
	});
}

/* -- Fill in the manage dashboard widget -- */
dashboards.ManageDashboards = function() {
	/* Copy the template row */
	var tmp = $("#widgetModal .manage-dashboards .template-row").clone(true);

	/* Clear the table */
	var table = $("#widgetModal .manage-dashboards table tbody").empty();
	table.append(tmp);
	
	$.each(dashboards.list, function( key, value ) {
		/* Copy the template row , not overwrite it */
		var row = tmp.clone(true);
		row.removeClass("template-row");

		if(value.daterange_lock == undefined){
			value.daterange_lock = "off";
		}

		/* Add the data to the row */
		row.find("td:eq(0) span").html(key);
		row.find("td:eq(1) span").html(value.daterange_lock);
		row.find("td:eq(2) span").html(value.startup);

		if(value.daterange_lock == "on"){			
			row.find("td:eq(1) span").addClass("label-success");
		} else {
			row.find("td:eq(1) span").addClass("label-danger");
		}

		if(value.startup == "on"){	
			row.find("td:eq(2) span").addClass("label-success");
		} else {
			row.find("td:eq(2) span").addClass("label-danger");
		}

		/* Add name to the option buttons for refference */
		row.find(".view-dash").attr("name", key);
		row.find(".edit-dash").attr("name", key);
		row.find(".delete-dash").attr("name", key);

		table.append(row);

		/* -- Open dashboard for the dashboard clicked on -- */
		row.on("click",".view-dash",function(){
			dashboards.OpenDashboard($(this).attr("name"));
			ui.HideWidget(".manage-dashboards");
		});

		/* -- Open edit dashboard for the dashboard clicked on -- */
		row.on("click",".edit-dash",function(){
			ui.ShowWidget(".dashboard-settings");
			/* Edit the dashboard */
			dashboards.EditDashboard($(this).attr("name"));
			
			/* Disable dashboard options when it is not available in the subscriptions */
			if(ui.BlockedBySubscription("Dashboards", "Disabled", false)){				
				var msg = "<div class=\"callout-success-template callout callout-success btn-upgrade-subscription\" style='cursor:pointer'>"+ui.data.languages["_SUBSCRIPTION_UPGRADE_NOTICE"].replace("%x", "<strong>"+ ui.data.languages["_DASHBOARDS"] +"</strong>") + "<i class='fa fa-unlock-alt pull-right'></i></div>";
				$(".dashboard-settings .upgrade_message").html(msg);
				$(".dashboard-settings .upgrade_message").show();
				$(".dashboard-settings textarea").attr("disabled", "disabled");				
				$("input[name=dashboardname]").attr("disabled", "disabled");
				$("input[name=daterange_lock]").attr("disabled", "disabled");
				$("input[name=startup]").attr("disabled", "disabled");
				
			}

		});

		row.on("click",".delete-dash",function(){
			var dashname = $(this).attr("name");
			var btn = $(this);

			dashboards.DeleteDashboard(dashname, function(r){
				var data = ui.ParseJSON(r);
				if(data.Status == 'Success'){
					ui.Callout(data);

					btn.parents('tr').first().remove();
					$(".menu-report[rel='_DASHBOARDS'][name='"+ dashname +"']").remove();

					delete dashboards.list[dashname];
				} else {
					ui.Callout(data);
				}
				ui.HideWidget(".manage-dashboards");
			});
		});

	});
}



/* -- Edit the dashboard -- */
dashboards.EditDashboard = function(name) {

	/* return if the dashboard is new */
	if(dashboards.list[name] == undefined){
		return;
	}

	/* Get the dash to edit */
	var dash = dashboards.list[name];

	/* Set the correct settings in the elements */
	$("#widgetModal .dashboard-settings input[name='dashboardname']").val(dash.name);
	$("#widgetModal .dashboard-settings textarea[name='dashboarddescription']").val(dash.description);

	if(dash.daterange_lock == 'on'){
		$(".dashboard-settings input[name='daterange_lock']").prop("checked", true);
	} else {
		$(".dashboard-settings input[name='daterange_lock']").prop("checked", false);
	}

	if(dash.startup == 'on'){
		$(".dashboard-settings input[name='startup']").prop("checked", true);
	} else {
		$(".dashboard-settings input[name='startup']").prop("checked", false);
	}

	if(dash.private == 'on'){
		$(".dashboard-settings input[name='private']").prop("checked", true);
		
	} else {
		$(".dashboard-settings input[name='private']").prop("checked", false);
	}

}
/* -- Close -- */

dashboards.OpenDashboard = function(name){
	/* close current dashboard */
	$(".content .report:not(#report_template)").remove();
	$(".content .metric-report:not(#mini_report)").remove();

	if(dashboards.list[name] == undefined){
		console.log("could not find "+ name +" in dashboards list");
		return false;
	}

	var dashboard = dashboards.list[name];
	if(dashboard.minis != undefined){		
		$.each(dashboard.minis, function(k,v){
			report.OpenMetricReport(v);
		});
	}


	$(".pagename").html(name);

	i = 0;
	var done=0;
	var ncol=2;	
	while (i < 7) {
		if(dashboard.reports[i] != undefined) {
			dashboard.reports[i].reverse();
			$.each(dashboard.reports[i], function( key, r ) {
				report.OpenReport(r.label, i, r.url);
				if (i > 2 && done!=i) {
					ncol++;
					done=i;					
				}		
			});
		}
		i++;
	}
	
	if (ncol > 2) {
		i = 2;	
		while (i <= ncol) {
			$("#dashcol"+(i)).removeClass("hidden");		
			i++;	
		}
		dashboards.SetLayout(ncol);
		report.total_cols=ncol+1;
	}

}

dashboards.AutoSave = function(callback, instantly){	
	autosave_timer;
	clearTimeout(autosave_timer);

	/* Get current time for description */
	var current_time = new Date();
	current_time = current_time.getMonth() + "/" + current_time.getDate() + "/" + current_time.getFullYear() + ", " + current_time.getHours() + ":" + current_time.getMinutes() + ":" + current_time.getSeconds();

	if(dashboards.list['Autosaved Workspace'] == undefined){
		var autosave = {
			name : "Autosaved Workspace",
			description : ui.data.languages["_DASHBOARD_AUTOSAVED_ON"] +" " + current_time + ".",
			reports : [],
			force : true
		};
	} else {
		var current = dashboards.list['Autosaved Workspace'];
		var autosave = {
			name : "Autosaved Workspace",
			description : ui.data.languages["_DASHBOARD_AUTOSAVED_ON"] +" " + current_time + ".",
			label : current.label,		
			reports : [],
			daterange_lock : current.daterange_lock,
			startup : current.startup,
			force : true
		};
	}	

	/* default callback is empty function */
	if(callback == undefined) {
		callback = function(){};
	}
	
	/* Loop through the cols to collect the reports */
	autosave.reports = dashboards.ListOpenReports();

	/* Loop through the cols to collect the mini reports */
	autosave.minis = dashboards.ListOpenMinis();

	/* Save it to the system */
	if(instantly == undefined) {
		autosave_timer = setTimeout(function() {
			dashboards.SaveDashboard("Autosaved Workspace", autosave , callback);
		}, 5000);
	} else {
		dashboards.SaveDashboard("Autosaved Workspace", autosave , callback);
	}
	
}

dashboards.ListOpenMinis = function(){
	var data = [];
	var i = 0;
	$(".content .metric-report").each( function(){
		if($(this).attr("report-label") != null){
			data[i] = $(this).attr("report-label");
			i++;
		}
		
	});
	return data;
}

/* -- Loop through the cols to collect the reports -- */
dashboards.ListOpenReports = function(){
	var data = [];
	var col = 0;
	/* Loop through the cols to collect the reports */
	$(".content .row:eq(1) section").each( function(){
		/* Preset Key as array */
		data[col] = [];		
		/* Loop through the reports */
		$(this).find(".report").each(function(){			
			var ropts = report.GetReportOptions($(this).attr("id"));

			var rl = $(this).attr("label");
			var rurl = report.GetReportUrl(rl,ropts);
			var rname = $(this).find(".box-title").html();

			var r = {
				label : rl,
				name : rname,
				url : rurl
			}
			data[col].push(r);
		});		
		col ++;
	});	
	return data;
}
/* -- Close -- */

dashboards.CheckDashboardData = function(name, data) {
	/* Set defaults for not given data */
	if(data.label == undefined) { data.label = name; }
	if(data.daterange_lock == undefined) { data.daterange_lock = "off"; }
	if(data.startup == undefined) { data.startup = "off"; }
	if(data.reports == undefined) { data.reports = []; }
	if(data.name == undefined) { data.name = name; }

	/* Check data for duplicate save if we are not forcing it */
	if(data.force == undefined){
		if(dashboards.list[name] != undefined){
			var c = confirm( ui.data.languages["_DASHBOARD_NAME_EXISTS"] );
			if(c){
				return data;
			} else {
				return false;
			}
		}
	}
	return data;
}

dashboards.DeleteDashboard = function(name, callback) {
	if(callback == undefined) {
		callback = function(result) {};
	}

	$.post('includes/savedashboard.php', { saveDashboard: 'delete', dashboardname: name, conf: conf }, function(result) {
		callback(result);
	});
}

dashboards.SaveDashboard = function(name, data, callback) {
	/**
		This function will save the dashboard.
		
		Arguments:
		- name
			The name of the dashboard.
		- data
			The data of the dashboard.
	**/
	
	if(callback == undefined) {
		callback = function() {};
	}

	data = dashboards.CheckDashboardData(name,data);
	if(data === false){
		return false;
	}

	/* stringify the data to send with the post */
	var data_string = JSON.stringify(data);	

	$.ajax({
	    type: "POST",
	    url: "includes/savedashboard.php",

        data: { saveDashboard: data_string, dashboardname: name, conf: conf },
        contentType: "application/x-www-form-urlencoded; charset=utf-8; charset=utf-8",
	    success: function(result) {
	    	/* Call the callback function */
			callback(result);

	        /* Add the new dashboard to the dashboard category menu if needed */
			if(dashboards.list[name] == undefined){
				var ctree = $(".category-_DASHBOARDS").parents(".treeview").first();
				var li = $(".sidebar-menu[name='reports-menu'] .treeview-menu > li:first").clone(true);
				li.find(".report-name").html(name);

				li.find("i").removeAttr("class");
				li.find("i").attr("class", "fa fa-angle-double-right menu-"+name);
				li.find("a").attr("name", name);

				ctree.find(".treeview-menu").append(li);

			}

			/* add / overwrite to the dashbaords list */
			dashboards.list[name] = data;

			
	    },
	    error: function (xhr, textStatus, errorThrown) {
	        console.log(xhr.responseText);
	    }
	});	


	// $.post('includes/savedashboard.php', { saveDashboard: data_string, dashboardname: name, conf: conf }, function(result) {		
	// 	/* Add the new dashboard to the dashboard category menu if needed */
	// 	if(dashboards.list[name] == undefined){
	// 		var ctree = $(".category-_DASHBOARDS").parents(".treeview").first();
	// 		var li = $(".sidebar-menu[name='reports-menu'] .treeview-menu > li:first").clone(true);
	// 		li.find(".report-name").html(name);

	// 		li.find("i").removeAttr("class");
	// 		li.find("i").attr("class", "fa fa-angle-double-right menu-"+name);
	// 		li.find("a").attr("name", name);

	// 		ctree.find(".treeview-menu").append(li);

	// 	}

	// 	/* add / overwrite to the dashbaords list */
	// 	dashboards.list[name] = data;

	// 	/* Call the callback function */
	// 	callback(result);
		
	// }, 'text/html;charset=utf-8');	
}

dashboards.ReportMode = function(){	
	$(".content > .print-wrapper").remove();
	$(".content > .row").show();
}

dashboards.ReturnReports = function(){
	dashboards.printData = {};
	dashboards.ReportMode();
	if($(".left-side").hasClass("collapse-left")){
		$(".header .sidebar-toggle").click();
	}

	dashboards.OpenDashboard('Autosaved Workspace');
	
	$("html, body").animate({ scrollTop: 0 }, "fast");
}

dashboards.printData = {};

dashboards.PrintMode = function(){
	/* Instant auto save dashboard */
	dashboards.AutoSave(function(){}, true);	

	$(".content > .print-wrapper").remove();
	$(".sidebar-toggle").click();	

	var print = $(".content_templates .print-wrapper").clone(true);

	/* Add the print title */
	print.find(".print-title").html(conf);

	/* Copy the header and remove from the page */
	var header = print.find(".h1-title").clone(true);
	print.find(".h1-title").remove();

	/* Add the header as starters data */
	dashboards.printData[0] = header;

	var i = 1;
	$(".content .row .metric-report").each( function(){
		/* First we clone the report then remove the original */
		var report = $(this);

		dashboards.printData[i] = report;
		i ++;
	});

	$(".content .row .report").each( function(){
		/* First we clone the report then remove the original */
		var report = $(this);

		dashboards.printData[i] = report;
		i ++;
	});

	dashboards.CreatePrint(print);
}

dashboards.CreatePrint = function(print){

	/* Copy the print wrapper and remove the header */
	var wrapper = $(".content_templates .print-wrapper").clone(true);
	var print = wrapper.find(".print");
	print.find(".h1-title").remove();
	
	/* Add the print preview */
	$(".content > .row").hide();
	$(".content").append(wrapper);	
	/* Setup counters for pixels and current page */
	var totalHeight = 0;
	var allowedHeight = 600;
	var page = 0;

	/* Create a copy of the first page */
	var new_page = print.find(".page:eq(0)").clone(true);
	// new_page.css('page-break-before','always');

	/* set a target page */
	var current_page = print.find(".page:eq("+ page +")");
	var i=1;
	$.each(dashboards.printData, function(key, obj){

		title = obj.find(".box-title").html();		

		/* Add to the page */		
		current_page.find(".print-grid").append(obj);

		/* Get the height of the current page */
		var height = current_page.find(".print-grid").outerHeight();


		/* Now lets do some tricky stuff! */
		if (height > allowedHeight) { /* this one is going to be too long anyway, so lets just print it */			
			totalHeight = height;
			print.append(new_page.clone(true)); page ++;			
		}		
		i++;
		/* Reset based on page, in case there is a new page added*/
		current_page = print.find(".page:eq("+ page +")");
	});


	/* remove last blank page */
	if(print.find(".page:eq("+ page +") .report").length == 0){
		print.find(".page:eq("+ page +")").remove();
	}

	dashboards.PrintListeners(wrapper);
}

dashboards.PrintListeners = function(wrapper){

	$(".print-form").on("submit", function(e){
		if (ui.data.hl==false) {
			ui.LicenseUpgrade();
			return false;
		}
		var print_as = $(this).find("[name='output']").val();

		/* Add the stylesheets to the content */
		var content = "<div id='printer' class='content'>" + wrapper.find(".print").html() +"</div>";
		
		/* for pdf add head links and encode the html */	
		content = "<!DOCTYPE html><html><head>" + $("head").html() + "</head><body>" + content + "</body></html>";
		content = base64_encode(content);
		
		$(this).find("[name='content']").val(content);
		$(this).find("[name='name']").val(conf + ".pdf" );		
		$(this).find("[name='version']").val(ui.data.languages['LOGAHOLIC_VERSION_NUMBER']);

		Intercom('trackEvent', 'requested-custom-pdf');
	
	});
	$(".print-sizes button").on("click", function(){
		/* Reset active size button */
		$(".print-sizes button").removeClass("active");
		$(this).addClass("active");

		/* Remove size classes */
		$(".print .page").removeClass("A4");
		$(".print .page").removeClass("letter");

		/* Get the size */
		var size = $(this).val();
		$(".print .page").addClass(size);
	});
	
	$(".print-alerts .dropdown-menu button").on("click", function(){
		/* what type pf alert? */
		var type = $(this).val();
		/* what text? */
		var selection = document.getSelection();
		/* Copy template alert */
		var alert = $("#alert-templates .alert-" + type).clone(true);

		/* Add the content to the alert */
		alert.find(".alert-body").html( selection.toString() );

		document.execCommand("insertHTML", false,"<div class=\"alert alert-"+ type +" alert-dismissable\">" + alert.html() + "</div>");
	});

	$(".print-restyling button").on("click", function(){
		if($(this).hasClass("active")){
			$(this).removeClass("active");
		} else {
			$(this).addClass("active");
		}

		var set = $(this).val();
		document.execCommand(set);
	});

	$(".print-command button").on("click", function(){
		document.execCommand(  $(this).val() );
	});

	/* Remove some handling in the reports when shown in the pdf. */
	$(".print .open_in_new_dialog").removeAttr("href");
	$(".print .open_in_new_dialog").removeClass("open_in_new_dialog");
	$(".print .report_table td a").removeAttr("onclick");
}

dashboards.PrintHtml = function(){

	if (ui.data.hl==false) {
		ui.LicenseUpgrade();
		return false;
	}		
	window.print();
	dashboards.ReturnReports();
}