
var report = {};
report.total_cols = 3;
report.default_options = {};
report.selected_dates = {};


report.GetReportUrl = function(label, options){
	if(options.profileselector != undefined && options.profileselector != conf){
		var url = "reports.php?conf="+ options.profileselector + "&labels=" + label;
	} else {
		var url = "reports.php?conf="+ conf + "&labels=" + label;
	}

	for(var key in options) {
		/* Skip conf and labels keys */
		if(key == "labels" || key == "conf"){
			continue;
		}
		url += "&" + key + "=" + options[key];
	}
	
	return url;
}

report.LoadReport = function(id , options , url, callback, showoptions){
	if(options == undefined){ options = { }; }
	
	/* Create the report URL */
	if(url == undefined){
		var report_url = report.GetReportUrl($("#"+ id).attr("label"), options);
	} else {
		var report_url = url;
	}
	report_url = encodeURI(report_url);
		
	/* Unset Listener on the toggle */
	$("#"+ id +" .report-options-toggle").attr("data-target","");
	$("#"+ id +" .dialog_info").attr("data-target","");

	/* Add Loading to the content */
	$("#"+ id +" > .box-body").html("<div class='loading-report'>"+ ui.data.languages["_LOADING"] +"...</div>");

	$("#"+ id + " .box-header [data-widget='remove']").on("click",  function() {
        //Find the box parent        
        var box = $(this).parents(".box").first();
        box.slideUp();

        /* after close remove the report */
        setTimeout(function() {
          box.remove();
          dashboards.AutoSave();
        }, 1500);

        
    });

    if (ui.data.hl==false) {
		$("#"+ id +" .box-header .report-settings a.xml").attr("target","");
		$("#"+ id +" .box-header .report-settings a.xml").attr("onclick","ui.LicenseUpgrade()");
		
		$("#"+ id +" .box-header .report-settings a.json").attr("target","");
		$("#"+ id +" .box-header .report-settings a.json").attr("onclick","ui.LicenseUpgrade()");
		
		$("#"+ id +" .box-header .report-settings a.csv").attr("target","");
		$("#"+ id +" .box-header .report-settings a.csv").attr("onclick","ui.LicenseUpgrade()");

		$("#"+ id +" .box-header .report-settings a.mail").attr("data-target","");
		$("#"+ id +" .box-header .report-settings a.mail").attr("onclick","ui.LicenseUpgrade()");			
		
	} else {
		$("#"+ id +" .box-header .report-settings a.xml").attr("href",report_url + "&outputmode=xml");
		$("#"+ id +" .box-header .report-settings a.json").attr("href",report_url + "&outputmode=json");
		$("#"+ id +" .box-header .report-settings a.csv").attr("href",report_url + "&outputmode=csv");
	}
	
	/* Get the report content */
	$.ajax({
		url: report_url
		,type: 'POST'
		,async: true
		,contentType: "application/x-www-form-urlencoded;charset=UTF-8"		
		,success: function(result) {
			/* Do we have a callback function ? */
			if(callback != undefined){
				callback(result);
			} else {
				/* set the content */
				$("#"+ id +" .box-body").html(result);

				if(report_multi_profiles){
					$('.addlabel-profile-selector').css('display','inline');
				}

				/* Resolve IP's when needed */
				report.ResolveIps(id);

				/* add option handling */				
				report.HandleReportOptions(id);

				if(showoptions != undefined){
					$("#"+ id +" .report-options-toggle").click();
				}	
			}

		}
	});
}

report.GetResolveIpData = function(table_id){
	var data = [];
	var i = 0;
	$("#"+ table_id +" .resolve").each(function(){
		var c = $("#"+ table_id +" [name='conf']").val();
		var id = $(this).attr("id");
		var vid = $(this).attr("data-visitorid");
		var row = $(this).attr("data-row");

		var which = table_id + " #" + id;

		data[i] = [row, which, vid, c];
		i ++;
	});
	return data;
}

report.StoreResolveIP  = function(data, i){
	if(data[i] == undefined){
		return;
	}

	$.get("includes/resolve.php", { "q": data[i][0],"vid": data[i][2], "conf":data[i][3], "sid": Math.random() },  function(result){
		// If the element is still available
		if($("#" + data[i][1]).length != 0){
			$("#" + data[i][1]).html(result);

			report.StoreResolveIP(data, (i + 1));
		}
    });
}

report.ResolveIps = function(table_id){
	if( $('#printer').length > 0 ){
		$("#"+ table_id +" .resolve").hide();
		return;
	} 

	var data = report.GetResolveIpData(table_id);

	if(data.length > 0){
		report.StoreResolveIP(data, 0);
	}
}

report.OpenReport = function(label , col , url){
	/* Set dashboard to report mode ( This closses the print mode ) */
	dashboards.ReportMode();

	if(reports[label] == undefined){
		console.log("could not find "+ label +" in reports array");
		return;
	}

	var r = $(".content_templates #report_template").clone(true);

	var id = "DT" + Date.now() + Math.floor(Math.random() * 100);

	/* default set to col with the least reports */
	if(col == undefined){
		col = report.GetBestColNumber();
	}

	/* set the header */
	r.find(".box-title").html(reports[label].name);
	//r.find(".box-title").html(label);

	/* edit the links in the settings */
	if(url == undefined){		
		var url = report.GetReportUrl(label,report.default_options);
	}
	
	/* add the new report */
	
	$(".content .row:eq(1) section").eq(col).prepend("<div id='"+ id +"' label='"+ label +"' style='display:none' class='box report " + boxstyle.randomstyle() + "'>" + r.html() + "</div>");
	$("#" + id).slideDown(100);	
	scroll(0,$("#" + id).offset().top -247);

	report.LoadReport(id, {} , url);
	
}

report.GetReportOptions = function(report_id){
	var reportoptions = {};
	$("#"+ report_id +" .report-options").find('input:not(.noOption), select:not(.noOption), textarea:not(.noOption)').each(function() {
		if($(this).attr('id') == undefined || $(this).attr('id') == '') {
			var optionID = $(this).attr('name');
		} else {
			var optionID = $(this).attr('id');
		}
		if($(this).attr('type') != undefined && ($(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio')) {
			if($(this).is(":checked") == true) {
				if($(this).attr('value') != undefined) {
					reportoptions[optionID] = $(this).attr('value');
				} else {
					reportoptions[optionID] = true;
				}
			}
		} else if($(this).is('select') == true) {
			reportoptions[optionID] = $(this).val();
		} else {
			if(optionID.indexOf("[]") != -1) {
				var tmp_id = optionID.replace("[]","");
				if(handled_ids[tmp_id] != undefined) { handled_ids[tmp_id] ++; } else { handled_ids[tmp_id] = 1; }
				reportoptions[tmp_id + handled_ids[tmp_id]] = $(this).val();
			} else if(optionID == 'minimumDate' || optionID == 'maximumDate') {
				reportoptions[optionID] = $(this).val();
			} else if(optionID == 'from' || optionID == 'to') {
				reportoptions[optionID] = $(this).val();
			} else {
				reportoptions[optionID] = php_urlencode($(this).val());
			}
		}		
	});

	return reportoptions;
}

report.HandleReportOptions = function(report_id){
	/* add the report options to the correct div and remove from the body */	
	options = $("#"+ report_id +" .box-body .report-options").clone(true);
	$("#"+ report_id +" .report-options").remove();

	/* add listener for opening the advanced report options */
	options.on("click", ".advanced-options-toggler", function() {	
		var box = $(this).parents(".box").first();
		box.find(".advanced-options-form").toggle();
	});

	/* add listener for submitting report options */
	options.on("click",".load-report", function(e){		
		e.preventDefault();

		var box = $(this).parents(".box").first();

		/* Check the options */
		var options_array = report.GetReportOptions(box.attr("id"));

		/* Reload the report */
		if(box.find(".close-options").is(":visible")){
			box.find(".close-options").click();
		}

		report.LoadReport(box.attr("id") , options_array);

		// check if we've manually selected a new date range and if so, update the defaults so any new reports opened from the side menu will use this range
		if (report.selected_dates[report_id]!=undefined) {		
				report.default_options.minimumDate = report.selected_dates[report_id]['start'];
   				report.default_options.maximumDate = report.selected_dates[report_id]['end'];
   				report.selected_dates = [];
		}

	});
	/* -- Close -- */	

	/* now add the element to the dom */
	$("#"+ report_id).prepend( options );
	$("#"+ report_id +" .report-options").attr("id","options-"+report_id);
	$("#"+ report_id +" .report-options-toggle").attr("data-target","#options-"+report_id);	
	$("#"+ report_id +" .report-header-content .dialog_info").attr("data-target","#options-"+report_id);
	$("#"+ report_id +" .report-header-content .dialog_info").attr("data-toggle","modal");
	
	var report_options_array = report.GetReportOptions(report_id);
	
	/* initialize the datepicker on the report */
	var targetdatepicker  = "#"+ report_id + " .report-options";
	$("#"+ report_id +" .daterange").daterangepicker({
		opens: 'left',
		parent : targetdatepicker,
	    autoApply: true,	    
		locale :{
			format: dateformat,
			customRangeLabel: ui.data.languages["_CUSTOM_RANGE"]
		},
	    ranges: dashboards.datepickerranges,
	    startDate: report_options_array.minimumDate,
	    endDate: report_options_array.maximumDate
	},
	function(start, end) {
	    $("#"+ report_id +" .fromRange").attr("value", start.format(dateformat) );
		$("#"+ report_id +" .toRange").attr("value", end.format(dateformat) );		
		report.selected_dates[report_id] = [];
		report.selected_dates[report_id]['start'] = start.format(dateformat);
		report.selected_dates[report_id]['end'] = end.format(dateformat);
	});

	$("#"+ report_id +" .manage_segment_filters").on("click", function(){
		$(".report-options").modal('hide');
		ui.LoadSegments($("#"+ report_id +" input[name='conf']").val());
	});

	conf_name = conf;

	// this is for the single profile selector
	$("#"+ report_id +" .report-options [name='profileselector']" ).autocomplete({
		appendTo: "#" + report_id + " .modal-content",
		delay: 600,
		source: function(request, callback){
			request['report_id'] = report_id;
			GetAvailableProfiles(request,callback);
		},
		minLength: 0
	}).bind('click', function(){ $(this).autocomplete("search"); } );

	$("#"+ report_id +" .report-options [name='profileselector']").on("autocompleteselect", function(event, ui){
		$(this).attr("value",ui.item.value);
		switchProfile($(this));
	});

	// this is for a generic multi tag selector
	if ($("#"+ report_id +" .tagBox").attr("type")=="text") {
		// get the val and the target url for the menu
		tbname = $("#"+ report_id +" .tagBox").attr("name");
		tbval = $("#"+ report_id +" .tagBox").val();	
		
		$("#"+ report_id +" .tagBox").after("<div class='tag-box'><ul class='tag-list'><li class='input'><input type='text' value='' name='tag-search' class='search noOption' placeholder='...'></li></ul><div style='clear:both; height: 1px;'>&nbsp;</div></div>");

		if (tbval !="") {			
			sp = decodeURIComponent(report_options_array[tbname]).split(";");
			$.each(sp, function( i,v ) {
		  		//alert( index + ": " + value );
		  		$("#"+ report_id +" .tag-box .tag-list").append("<li class='users-tag bg-success'><span class='name'>"+ v +"</span><i class='fa fa-times'></i></li>");
				$("#"+ report_id +" .tag-box .tag-list").append( $("#"+ report_id +" .tag-box .input") );
			});
		}

		// add the autocomplete
		$("#"+ report_id +" .tag-box .search").autocomplete({
			appendTo: "#" + report_id + " .modal-content",
			source: function(request, callback){
				$.ajax({
					type: 'POST',
					url: $("#"+ report_id +" .tagBox").attr("data-url"),
					data:{
						search : request['term']
					},
					success: function(result) {
						// check if it is an array
						if(result.charAt(0) == '['){
							callback(JSON.parse(result));
						} else {
							console.log(result);
						}
					}
				});
			},		    
			minLength : 0 
		}).bind('click', function(){ $(this).autocomplete("search"); } );

		$("#"+ report_id +" .tag-box .search").on("autocompleteselect", function(e, obj){
			var v = obj.item.value;
			if(v == ""){
				return;
			}
			
			// add the value to the tagbox and the actual input box
			sp = v.split(",");
			$.each(sp, function( i,v ) {		  		
		  		$("#"+ report_id +" .tag-box .tag-list").append("<li class='users-tag bg-success'><span class='name'>"+ v +"</span><i class='fa fa-times'></i></li>");
				$("#"+ report_id +" .tag-box .tag-list").append( $("#"+ report_id +" .tag-box .input") );
			});

		   	var plist="";
		   	$("#"+ report_id +" .users-tag").each( function(){
		   		if (plist != "") {
		   			plist = plist + ";" + $(this).find(".name").html();	
		   		} else {
					plist = $(this).find(".name").html();
				}
			});
			$("#"+ report_id +" .report-options [name='"+tbname+"']").val(plist);

			//clear the value and focus the field so the user can keep typing
			obj.item.value ='';
			$("#"+ report_id +" .tag-box .input .search").focus();
		});

		//add the remove button
		$("#"+ report_id +" .tag-list").on("click", ".users-tag i", function(){
			var item = $(this).parent("li");
			var p = item.find("span").html();
			item.remove();
			var plist="";
		   	$("#"+ report_id +" .users-tag").each( function(){
		   		if (plist != "") {
		   			plist = plist + ";" + $(this).find(".name").html();	
		   		} else {
					plist = $(this).find(".name").html();
				}
			});
			$("#"+ report_id +" .report-options [name='"+tbname+"']").val(plist);
		});
	}
	// end generic autocomplete


	$("#" + report_id + " .twitter-profiles").on("click", function(){
		window.twttr.widgets.load();
	});

	remove_outputmodes = $("#" + report_id + " .remove_outputmodes").attr("data-outputmodes");	
	if (remove_outputmodes!==undefined) {
		remove_outputmodes = $.parseJSON(remove_outputmodes);		
		$.each(remove_outputmodes, function(k,v) {
			if (v == "all") {
				$("#" + report_id + " .export_buttons").hide();
				return;
			}
			if (v == "mail") {
				$("#" + report_id + " .dropdown-menu.report-settings .divider").hide();	
			}
			$("#" + report_id + " .dropdown-menu.report-settings ." + v).hide();
		});
	} else {
		$("#" + report_id + " .dropdown-menu.report-settings a").show();
		$("#" + report_id + " .export_buttons").show();
	}


}

report.OpenMetricReport = function(label, from, to, id){
	/* Set dashboard to report mode ( This closses the print mode ) */
	dashboards.ReportMode();

	if(reports[label] == undefined){
		console.log("could not find "+ label +" in reports array");
		return;
	}

	if (id == undefined) {
		var r = $(".content_templates #mini_report").clone(true);

		/* Overwrite ID */
		var id = "DT" + Date.now() + Math.floor(Math.random() * 100);
		r.attr("id", id);
		r.attr("report-label", label);

		$(".content .row:eq(0)").append(r);
	}

	/* edit the links in the settings */
	var url = report.GetReportUrl(label,report.default_options);

	if(from != undefined && to != undefined){ 
		if(isNaN(from)){
			url += "&minimumDate="+ from;
		} else {
			url += "&from="+ from;
		}

		if(isNaN(to)){
			url += "&maximumDate="+ to;
		} else {
			url += "&to="+ to;
		}
	}	

	url = url + "&outputmode=json";

	// Even if the metric is not loaded we do need to be able to remove the metric wrapper	
	$("#"+ id).find(".remove-mini").on("click", function(){
		$(this).parents(".metric-report").first().remove();
		dashboards.AutoSave();
	});

	report.LoadReport(id, {} , url, function(result){

		try {
    		var data = $.parseJSON(result);
    	} 
    	catch(err) {
    		if (result=="Another process is creating data for this report, please reload later") {
    			$("#"+ id).find(".title").html("Another process is creating "+reports[label].name+" data, please reload later");
			} else {
				var data = ui.ParseJSON(result);
				$("#"+ id).find(".title").html("&nbsp;<br>Failed loading "+reports[label].name+"");
			}
			
			$("#"+ id).find(".more-link").html("Try again <i class=\"fa fa-refresh\"></i>");
			$("#"+ id).find(".more-link").on("click", function(){				
				report.OpenMetricReport(label, from, to, id);
				$("#"+ id).find(".more-link").html("More info <i class=\"fa fa-arrow-circle-right\"></i>");
			});
			return;
    	}

		
		$("#"+ id).find(".title").html( data[0] );
		$("#"+ id).find(".number").html( data[1] );

		var icon = "ion-pie-graph";
		if(data[3] != undefined){
			icon = data[3];
		}
		$("#"+ id).find(".ion").addClass(icon);
		$("#"+ id).find(".small-box").removeClass("bg-dark-gray");
		$("#"+ id).find(".small-box").removeClass("loading");

		if(data[4] != undefined){
			color = data[4];
		} else {
			var color = report.MiniBackgroundColor();
		}		

		$("#"+ id).find(".small-box").addClass( color );

		if(data[5] != undefined){
			$("#"+ id).attr("data-original-title", data[5]);
			$("#"+ id).tooltip({
				html:true, 
				container : "#"+ id, 
				trigger: 'manual', 
				delay : 0 , 
				animation : false,
				template: '<div class="tooltip widget-report-tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
			});

			$("#"+ id + ", #"+ id + " *").mouseover(function(){
				$(this).tooltip('show');
			}).mouseout(function(){
				$("#"+ id).tooltip('hide');
			});
		}

		$("#"+ id).find(".more-link").on("click", function(){
			if (data[6]!=undefined) {
				var col = report.GetBestColNumber();
				var url = report.GetReportUrl(data[2],report.default_options);
				url = url + data[6];
				report.OpenReport(data[2], col, url);
			} else {
				report.OpenReport(data[2]);
			}
			
		});
	});	
}

report.MiniBackgroundColor = function(key){
	if(key == undefined){
		key = Math.floor(Math.random() * 4);
	}
	var minicolors = [
		"bg-aqua"
		,"bg-green"
		,"bg-yellow"
		,"bg-red"
	];
	return minicolors[key];
	
}

/* This function returns the grid col number of the grid with the least reports */
report.GetBestColNumber = function(){
	var counts = [];
	var i = 1; // start at col one (don;t fill the full width one)
	while(i < report.total_cols){
		counts.push({
			key : i,
			count : parseInt($(".content .row:eq(1) section:eq("+ i +") > .report").length)
		});
		i++;
	}
	counts = sortByKey(counts,"count");	
	

	//or we can see which col is shorter
	var counts = [];
	var i = 1;
	while(i < report.total_cols){
		counts.push({
			key : i,
			count : parseInt($(".content .row:eq(1) section:eq("+ i +")").height())
		});		
		i++;
	}
	counts = sortByKey(counts,"count");

	return counts[0].key;

}





