
/*
 * Model(s): init.js.php
*/

var conf = GetURLParameter('conf');
var from_date;
var to_date;
var reports = [];
var categories = [];
var dateformat = "";
var lastscrollpos = 0;

var autosave_timer;

var original_conf_name = conf;
var report_multi_profiles = false;

$(document).ready(function(){	
	/* This is needed to gain full access to all features of JQplot. */
	$.jqplot.config.enablePlugins = true;
	/* check if conf is set in the url */
	if(conf != undefined && conf != ""){
		/* load the data */
		$.ajax({
			url: "app/model/dashboard.php?conf=" + conf
			,success: function(result) {
				res = ui.ParseJSON(result);
				ui.Load( res );
				InitiateData( res );

				/* Check if we need to open something at launch */
				var paramLabl = GetURLParameter("label");
				if(paramLabl != undefined){
					/* Open report */
					report.OpenReport(paramLabl);
				}
				var paramDash = GetURLParameter("dashboard");				
				if(paramDash != undefined){
					/* Open dashboard */
					dashboards.OpenDashboard(paramDash);
				}

				$("#main-menu .categorie-name").dblclick(function(e){ 					
					$(this).parents(".treeview").first().find(".menu-report").each(function() {
						$(this).click();
					});
				});				
			}
		});
	}

	if(ui.GetCookie('tutorialcookie')==2) {
		$('#tutorialPopUp').modal('hide');
		lgTutorial.init(lgTutorial.tutorials['dashboard-controls']);
		lgTutorial.start();
		ui.SetCookie('tutorialcookie', 0);
		
	}

	if(ui.GetCookie('tutorialcookie')==3) {
		$('#tutorialPopUp').modal('hide');
		lgTutorial.init(lgTutorial.tutorials['report-handling']);
		lgTutorial.start();
		ui.SetCookie('tutorialcookie', 0);
		
	}
	$(".pagename.manage-dashs").hide(); // we show a different one on the dashboard
});


/* -- The initializes all the setup data and listeners that need the base data -- */	
function InitiateData(data){
	/* -- Set the global variables -- */
	conf = data.conf;
	from_date = data.from_date;
	to_date = data.to_date;
	reports = data.reports;
	categories = data.categories;
	dashboards.list = data.dashboards;
	original_conf_name = conf;
	dateformat = data.dateformat;
	profile = data.profile;
	
	// set default report options
	report.default_options.minimumDate = data.minimumDate;
	report.default_options.maximumDate = data.maximumDate;

	dashboards.datepickerranges[ data.languages["_TODAY"] ] = [moment(), moment()];
    dashboards.datepickerranges[ data.languages["_YESTERDAY"] ] = [moment().subtract(1,'days'), moment().subtract(1,'days')];
    dashboards.datepickerranges[ data.languages["_LAST_7_DAYS"] ] = [moment().subtract(6,'days'), moment()];
    dashboards.datepickerranges[ data.languages["_LAST_30_DAYS"] ] = [moment().subtract(29,'days'), moment()];
    dashboards.datepickerranges[ data.languages["_THIS_MONTH"] ] = [moment().startOf('month'), moment().endOf('month')];
    dashboards.datepickerranges[ data.languages["_LAST_MONTH"] ] = [moment().subtract(1,'month').startOf('month'), moment().subtract(1,'month').endOf('month')];
    dashboards.datepickerranges[ data.languages["_LAST_3_MONTHS"] ] = [moment().subtract(2,'month').startOf('month'), moment().endOf('month')];
    dashboards.datepickerranges[ data.languages["_THIS_YEAR"] ] = [moment().startOf('year'), moment().endOf('year')];
    dashboards.datepickerranges[ data.languages["_LAST_YEAR"] ] = [moment().subtract(1,'year').startOf('year'), moment().subtract(1,'year').endOf('year')];

	/* Check if we need the version check */
	if(data.version_check === true){
		$(".versioncheck-reload").button('loading');
		$("#versionCheckModal").modal('show');
		$("#versionCheckModal .modal-body").load('app/model/VersionCheck.php?conf='+ conf , function(){
			$(".versioncheck-reload").button('reset');
			$(".versioncheck-reload").on("click", function(){
				window.location.href = window.location.href;
			});
		});
	}

	/* -- Add the profile name -- */
	$(".confname").html(conf);
	$(".pagename").html("New Workspace");
	
	/* -- Add the dashboard controls -- */
	dashboards.DashboardOptions(data.minimumDate, data.maximumDate);
	
	
	/* -- Setup the grid -- */
	var grid = $(".content_templates #the_grid").clone(true);
	$("section.content").append( grid.html() );
	$("#the_grid").remove();
	/* Make the dashboard widgets sortable Using jquery UI */
	
     $(".connectedSortable").sortable({
        placeholder: "sort-highlight",
        connectWith: ".connectedSortable",
        handle: ".box-header, .nav-tabs",
        forcePlaceholderSize: true,
        zIndex: 999999,
        update: function( event, ui ) {        	
        	window.dispatchEvent(new Event('resize'));
        	if (event.target.id == "full-dash") {        		
        		ui.item.find(".box-tools .expand i").switchClass("fa-expand", "fa-compress");
        		ui.item.attr('data-oripos', $(ui.sender).attr('id'));
        	} else {
        		ui.item.find(".box-tools .expand i").switchClass("fa-compress", "fa-expand");
        		ui.item.attr('data-oripos', '');
        	}
        	scroll(0,$(ui.item).offset().top -247);      	
        }
    });

     $(".keyMetricsRow").sortable({
        placeholder: "sort-highlight",
        forcePlaceholderSize: true,
        zIndex: 999999,
        update: function( event, ui ) {
        	window.dispatchEvent(new Event('resize'));        	
        }
    });


	/* -- change the search placeholder -- */
	$(".sidebar-form input").attr("placeholder", data.languages["_SEARCH"]+ "...");
	
	/* -- Add the categories and reports to the sidemenu -- */	
	/* Clone the template object. if we use the object itself here it will directly change in the dom */
	var template_item = $(".sidebar-menu[name='reports-menu']").clone(true);
	var template_list = $(".sidebar-menu[name='reports-menu'] .treeview-menu").clone(true);

	/* Clear the element in the dom */
	$(".sidebar-menu[name='reports-menu']").empty();
	
	$.each(categories, function( key, value ) {
		/* Clone the template because we do not want to change the template */
		var item = template_item.clone(true);

		/* add the category name and classes needed for the item */
		item.find(".treeview .categorie-name").html(value.name);
		item.find(".treeview i:first").addClass("category-"+ key);

		/* Clear the list */
		item.find(".treeview-menu").empty();

		$.each(value.data, function( k, label ) {
			/* Clone the template because we do not want to change the template */
			var r = template_list.clone(true);

			/* add the report label and category needed for reference on the click listener */
			
			r.find("a").addClass("menu-report");
			r.find("a").attr("rel",key);
			r.find("a").attr("name",k);
			r.find("a").attr("title",label);

			/* add the report name and classes needed for the item */
			r.find("i").addClass("menu-"+ k);

			/* remove categroy from the report name in the menu ea: Facebook -> age */
			var n = label.indexOf(value.name + " ");
			if(n === 0){
				r.find(".report-name").html(label.replace(value.name + " ", "")); 
			} else {
				r.find(".report-name").html(label);
			}


			/* add the report to the list */
			item.find(".treeview-menu").append(r.html());
		});

		/* add the category to the menu */
		$(".sidebar-menu[name='reports-menu']").append(item.html());

		
	});
	/* Sidebar tree view */
	$(".sidebar .treeview").tree();
	// we need some space at the bottom
	$(".sidebar-menu[name='reports-menu']").append("<li style='border-bottom:0;'><div style='height:50px;background-color:#F4F4F4;'></div></li>");


	/* Open Report listener to sidemenu report buttons */
	$(".menu-report").on("click", function(e){
		/* cancel click to href */
		e.preventDefault();

		//scroll the reports area to the top
		//$("html, body").animate({ scrollTop: 0 }, "fast");
		window.scrollTo(0, 0);

		/* -- get vars -- */
		var c = $(this).attr("rel");
		var r = $(this).attr("name");

		if(c == "_DASHBOARDS"){
			dashboards.OpenDashboard(r);
		} else if(c == "_KEY_METRIC") {
			report.OpenMetricReport(r, $(".report-options .fromRange").val(),$(".report-options .toRange").val());				
		} else {				
			report.OpenReport(r);
		}
		dashboards.AutoSave();
	});

	
	$.each(dashboards.list, function(k,v){
		if(v.startup == 'on'){
			dashboards.OpenDashboard(v.name);

		}
	});

	$(".content").on("click", ".open_edit_visitor" , function(e){
		e.preventDefault();		
		ui.ShowWidget(".edit-visitorid");
		$.ajax({
			url: 'app/model/EditVisitor.php',
			type: "POST",
			data: { action : "editvisitorid", visitorid : $(this).attr("data-vid"), "conf" : conf },
        	success: function(result) {    	
	        	res =  ui.ParseJSON(result);
	        	if(res.Status != "Success"){
	        		ui.Callout(res);
	        		return;
	        	}
	        	
        		$("#widgetModal .edit-visitorid .visitorid").html(res.Data[0].visitor);
        		$("#widgetModal .edit-visitorid .location").html(res.Data[0].location);

        		$("#widgetModal .edit-visitorid [name='visid']").val(res.Data[0].id);
        		$("#widgetModal .edit-visitorid [name='ipnumber']").val(res.Data[0].ip);
        		$("#widgetModal .edit-visitorid [name='label']").val(res.Data[0].label);

        		if(parseInt(res.Data[0].crawl) != 0){
        			$("#widgetModal .edit-visitorid name='setting'").val("bot");
        		}

        		$("#widgetModal .edit-visitorid .save-visitor").on("click", function(e){
					e.preventDefault();	
					$.ajax({
						url: 'app/model/EditVisitor.php',
						type: "POST",
						data: { 
							action : "savevisitor", 
							id : $("#widgetModal .edit-visitorid [name='visid']").val(), 
							label : $("#widgetModal .edit-visitorid [name='label']").val(), 
							setting : $("#widgetModal .edit-visitorid [name='setting']").val(), 
							"conf" : conf 
						},
			        	success: function(result) {	
	        				res = ui.ParseJSON(result);
	        				ui.Callout(res);
	        				if(res.Status == "Success"){
	        					ui.HideWidget(".edit-visitorid");
	        				}
			        	}
        			});
        		});
        		
        	}
    	});
	});

	/* When a HTML-element with the class open_in_iframe_window is being clicked, we want to open a JQuery dialog, based on the href attribute of the HTML-element */
	$(".content").on("click", ".open_iframe_window" , function(e){
		e.preventDefault();

		createIframeWindow($(this).attr('href'), $(this).attr("data-title"), $(this).parents(".report").first().attr("id"));
		return false;
	});

	// add help link event for reports
	$(".content").on("click", ".box-tools .help", function(e) {		
		toggleReportHelp($(this));
	});
	$(".content").on("click", ".help_content .close_help", function(e) {
		$(this).parents(".help_content").hide();
	});

	// add handling for full width
	$(".content").on("click",".box-tools .expand", function(e) {
		if ($(this).find("i").hasClass("fa-expand")) {			
			// change the icon
			$(this).find("i").switchClass("fa-expand", "fa-compress");			
			// select the report box
			var box = $(this).parents(".box").first();
			// remember where it came from
			box.attr('data-oripos',$(this).parents("section").attr("id"));			
			// move it to the full screen section
			$(".content .row:eq(1) section").eq(0).prepend(box);
		} else {
			// change the icon
			$(this).find("i").switchClass("fa-compress", "fa-expand");			
			// select the report box
			var box = $(this).parents(".box").first();
			// get it's original location and clear the attibute
			oripos = box.attr('data-oripos');
			if (!oripos || oripos == "full-dash") {
				oripos = "dashcol1";
			}			
			box.attr('data-oripos', '');
			// move it back
			$("#"+oripos).prepend(box);
		}		
		window.dispatchEvent(new Event('resize'));
		scroll(0,$(box).offset().top -247);
	});
	
	$(".content").on("click", ".box-tools .mail", function(e) {

		e.preventDefault();

		var box = $(this).parents(".box").first();
		
		$("#emailModal input[name='subject']").val(box.find(".box-title").html() + " on " + data.profile.confdomain);
		$("#emailModal input[name='box-id']").val(box.attr("id"));

	});

	$("#emailModal .send_report_email").on("click", function(e) {
		e.preventDefault();
		$("#emailModal .form-group").removeClass("has-error");
		
		var error = 0;
		if(!ValidateEmail($('#emailModal input[name="email"]').val())) {
			$('#emailModal input[name="email"]').parents(".form-group").first().addClass("has-error");
			error++;
		}
		if(!ValidateEmail( $('#emailModal input[name="fromemail"]').val() )){
			$('#emailModal input[name="fromemail"]').parents(".form-group").first().addClass("has-error");
			error++;
		}

		if (error > 0) {
			return;
		}
		bid = $("#emailModal input[name='box-id']").val();

		var options = report.GetReportOptions(bid);
		var report_url = report.GetReportUrl($("#"+ bid).attr("label"), options);
		report_url += "&outputmode=email";

	    fmt = new FormData(document.getElementById("send_report_email_form"));
	    $.ajax({
			url: report_url,
			type: "POST",
			data: fmt,
			enctype: 'multipart/form-data',
            processData: false,  // tell jQuery not to process the data
            contentType: false   // tell jQuery not to set contentType
        }).done(function( data ) {
        	$("#emailModal .close").click();        	
        	res =  ui.ParseJSON(data);        	
        	ui.Callout(res);
        });

	});

	$(".response .close").on("click", function() {
		$(this).parents(".callout").fadeOut();
	});



	$(".content").on("click",".open_in_this_dialog", function(e){
		e.preventDefault();

		if($(this).hasClass("with_confirm") == true) {
			var c = confirm( $(this).attr("title") );
			if(c == false){
				return false;
			}
		}
		
		var href = $(this).attr("href");
		
		var box = $(this).parents(".box").first();

		report.LoadReport( box.attr("id") , {} , href);
	});

	/* when a form in a report is submitted post it within the report div. */
	$(".content").on("submit","form", function(e) {
				
		if ($(this).attr("target")) {
			return;
		}
		e.preventDefault();
		var action = $(this).attr("action");
		// Action is not set so we set it default to reports.php
		if(action == undefined){
			action = "reports.php";
		}
		if (action.indexOf('?') != -1) {
			var data = "&" + $(this).serialize(); 
		} else {
			var data = "?conf="+conf_name+"&"+ $(this).serialize();
		}
		
		var box = $(this).parents(".box").first();

		report.LoadReport( box.attr("id") , {} ,  action + data);
		
		return false;
	});

	$(".content").on("click",".open_in_new_dialog", function(e){
		e.preventDefault();	
		lastscrollpos = $('html,body').scrollTop();

		if($(this).hasClass("with_confirm") == true) {
			var c = confirm( $(this).attr("title") );
			if(c == false){
				return false;
			}
		}
			
		var label = $(this).attr("type");
		var col = report.GetBestColNumber();
		var href = $(this).attr("href");

		report.OpenReport(label,col,href);
	});

	$(".content").on("click",".report .close_report", function(e){
		if (lastscrollpos!=0) {
			$('html,body').animate({scrollTop: lastscrollpos},700);
		}
		//one time use only
		lastscrollpos=0;
		
	});

	// $(document).keydown(function (e) {
	//     if ($(e.target).is('input')) { 
	//     	return true;
	//     } else {
	//     	console.log(e.key);
	//     	oldval = $(".sidebar [name='searchmenu']").val();
	//     	$(".sidebar [name='searchmenu']").val(oldval+e.key);
	//     	//$(".sidebar [name='searchmenu']").focus();
	//     	reportmenu.search();
	//     }
	    
	// });

	// $(window).scroll(function() {
 //  		lastscrollpos = $('html,body').scrollTop();
 //  		console.log("updated: "+lastscrollpos);
	// });


	$(".content").on("click",".storeurl", function(){
		ui.SetCookie("last_cp_action", "_INSTALL_REPORTS");
	});

	$(".content").on("click",".actionmenu-filter", function(e){
		var options = ui.ParseJSON($(this).attr("data-filter"));
		ui.LoadSegments($(this).parents(".box").first().find("input[name='conf']").val()  , function(){
			$(".new-segment-btn").click();
			$.each(options, function(k,v){				
				console.log(k);
				$(".manage-segments .filters-form [name='"+ k +"']").val(v);
				$(".manage-segments .filterradiooption input[name='optradio']:first").attr("checked", "checked");
			});			

		});
	});

	$("#widgetModal").on("hidden.bs.modal", function(){
		var report_id = $("#widgetModal .iframe-widget").attr("data-report");
		/* If there is no src or iframe then return */
		if(report_id == undefined){ return; }
		report.LoadReport(report_id , {} , undefined, undefined, 1);
	});

	$("body").on("click contextmenu", ".ss_overlay", function(e) {
		$(this).find(".report_preview").remove();
	});

	// pressing the ` key will reveal report load times
	$(window).keypress(function(event) {		
	    if (event.which == 96) {
	    	//alert('Ha!');
	    	$(".report_took").show();
	    }

	});

	// collapse or decollapse entries for a day
	$(".content").on("click",".news.timeline .time-label span", function(e){
		e.preventDefault();

		li = $(this).parent();

		if (li.find("i").hasClass("fa-angle-right") ) {
			li.nextUntil( ".time-label" ).show("slow");
			li.find("i").removeClass("fa-angle-right");
			li.find("i").addClass("fa-angle-down");
			$('html,body').animate({scrollTop: li.offset().top-300},'slow');
			
		} else {
			li.nextUntil( ".time-label" ).hide("slow");
			li.find("i").removeClass("fa-angle-down");
			li.find("i").addClass("fa-angle-right");
			$('html,body').animate({scrollTop: li.offset().top-115},1000);
		}   	

	});

	// toggle which news topics to show/hide
	$(".content").on("click",".newslegendtopic i", function(e){
		e.preventDefault();

		// lets see first if all the items are selected, if so, we are going to toggle diffrently and ONLY show the selected item
		var all = 1;
		$(this).closest(".box").find(".newslegendtopic i").each(function() {
			if (!$(this).hasClass("selected")) {
				all = 0;
			}
		});
		if (all == 1) {
			$(this).closest(".box").find(".newslegendtopic i").each(function() {
				$(this).removeClass("selected");
				$(this).addClass("bg-gray");
			});
			//$(this).addClass("selected");
		}
		
		if (!$(this).hasClass("selected")) {
			//it's off, turn on
			$(this).removeClass("bg-gray");
			$(this).addClass("selected");		
		} else {
			// turning off
			$(this).addClass("bg-gray");
			$(this).removeClass("selected");		
		}
		
		//get all the new timeline items, check if the type is selected
		$(this).closest(".box").find(".news.timeline .timeline-item").each(function() {			
			t = $(this).prev().attr("data-type");
			sel = $(this).closest(".box").find(".newslegendtopic [data-type='"+t+"']").hasClass("selected");
			if (sel ==true) {
				$(this).parent().show();
			} else {
				$(this).parent().hide();
			}
		});
	});
}

var boxstyle = {}
boxstyle.laststyle=0;

boxstyle.randomstyle = function() {
	/* pick a random style */
	b = {};

	b[0] = "box";
	b[1] = "box-danger";
	b[2] = "box-warning";
	b[3] = "box-success";
	b[4] = "box-primary";
	//b[4] = "box-solid";
	

	// b[0] = "box";
	// b[1] = "box-solid box-primary";
	// b[2] = "box-danger";
	// b[3] = "box-warning";
	// b[4] = "box-solid box-info";
	// b[5] = "box-success";
	// b[6] = "box-solid box-danger";
	// b[7] = "box-primary";
	// b[8] = "box-solid box-success";
	// //b[5] = "box-solid";
	// b[9] = "box-solid box-warning";

	if (boxstyle.laststyle==4) { 
		boxstyle.laststyle=0;
	} else {
		boxstyle.laststyle++;
	}
	return b[boxstyle.laststyle];

	/*
	min = 0;
	max = 10;
	if (box.laststyle > 4) {
	 	min = 0;
	 	max = 7;
	} else {
	 	min = 3;
	 	max = 10;
	}
	i = 0;
	while (true) {
		i = Math.floor(Math.random() * (max - min)) + min;
		if (i != box.laststyle) {
			break;
		}
	}

	box.laststyle = i;
	return b[i];
	*/

};
