

var ui = {};
ui.error_report = "";
ui.usage_data = {};

/* -- The initializes all the setup data and listeners that need the base data -- */
ui.Load = function (data){
	/* -- Set the global variables -- */
	ui.data = data;
	ui.data.user = data.session.userinfo;
	ui.data.edition = ui.data.languages['_LOGAHOLIC_EDITION'];

	if (ui.data.lang=="german") {
		moment.locale('de');
	} else if(ui.data.lang=="french") {
		moment.locale('fr');
	} else if(ui.data.lang=="dutch") {
		moment.locale('nl');
	} else if(ui.data.lang=="italian") {
		moment.locale('it');
	} else if(ui.data.lang=="spanish") {
		moment.locale('es');
	} else if(ui.data.lang=="portuguese") {
		moment.locale('pt');
	}
	/* -- Add help details to help button -- */
	$(".header .help-menu").attr("title", ui.data.languages['HELP_VERSION_DETAILS']);

	/* -- search report menu -- */
	$(".search_menu").on("click", function(event) {
		reportmenu.toggle();
	});

	$(".search_menu").on("focus", function(event) {
		//reportmenu.open();
	});
	$(".search_menu").on("keyup", function(event) {
		reportmenu.search();
	});
	$("#search-btn").on("click", function(event) {
		if ($("#search-btn i").hasClass("fa-times")) {
			/* clear the search field */
			$(".search_menu").val("");
			reportmenu.search();
			reportmenu.close();
		} else {
			reportmenu.search();
		}
	});

	$(".updatenowlink").on("click", function() {
		window.location.href = "update.php?conf="+conf;
	});
	$(".editprofilelink").on("click", function() {
		window.location.href = "profile.php?conf="+conf;
	});

	/* -- profiles menu -- */
	/* Clone the template object. if we use the object itself here it will directly change in the dom */
	var template_menu_item = $(".profilemenu .menu").clone(true);
	// we want to save this in case we need to reload the menu later
	ui.template_menu_item = template_menu_item;

	/* Clear the element in the dom */
	$(".profilemenu .menu li").empty();

	//do we have a subscription that enables updates?
	if (ui.data.session.subscription.Update!==undefined && ui.data.session.subscription.Update=="Enabled") {
		var subupdate = ui.data.session.subscription.Update;
	} else {
		var subupdate = false;
	}

	// the first menu item here is the current conf	
	if (typeof(conf) != "undefined" && conf != "newcnf") {
		var item = template_menu_item.clone(true);
		item.find("a").attr("style", "background-color:#98BFD6");
		item.find("a").addClass("curprofile");
		item.find("h3").html(conf);
		// fix the links
		item.find(".view").attr("data-link", "dashboard.php?conf="+conf);
		item.find(".edit").attr("data-link", "profile.php?conf="+conf);
		item.find(".update").attr("data-link", "update.php?conf="+conf);
		if (ui.data.user.isAdmin!=1) {
			if (subupdate==false) {
				if (ui.data.user.accessUpdateLogs!=1) {
					item.find(".update").hide();
				}
			}
			if (ui.data.user.accessEditProfile!=1) {
				item.find(".edit").hide();
			}
		}
		//add to the dom
		$(".profilemenu .menu").append(item.html());
	}
	//now add the others
	$.each(data.profiles, function( key, value ) {

		if (typeof(conf) != "undefined" && value[0] == conf) {
			//we already did this one
			return;
		}

		//populate the profiles menu			
		var item = template_menu_item.clone(true);
		item.find("h3").html(value[0]);
		// fix the links
		item.find(".view").attr("data-link", "dashboard.php?conf="+value[0]);
		item.find(".edit").attr("data-link", "profile.php?conf="+value[0]);
		item.find(".update").attr("data-link", "update.php?conf="+value[0]);
		if (ui.data.user.isAdmin!=1) {
			if (subupdate==false) {
				if (ui.data.user.accessUpdateLogs!=1) {
					item.find(".update").hide();
				}
			}
			if (ui.data.user.accessEditProfile!=1) {
				item.find(".edit").hide();
			}
		}
		//add to the dom
		$(".profilemenu .menu").append(item.html());

	});

	// add the profile counts
	$(".dropdown .num_profiles").html(data.pcount);

	$(document).on("mouseover", ".profilemenu .menurow", function(){
		$(this).find(".btn-group").show();
	});

	$(document).on("mouseout", ".profilemenu .menurow", function(){
		$(this).find(".btn-group").hide();
	});

	$(document).on("click", ".profilemenu .menurow .btn-group button", function(){
		window.location.href = $(this).attr("data-link");
	});

	if(ui.data.user.metadata != undefined) {
		ui.data.user.metadata = ui.ParseJSON(ui.data.user.metadata);
	}

	ui.ReloadUserInfo();

	if (ui.data.ss !== false) {
		ui.CheckPro();
	}

	$(".user-menu a:first").on("click", function() {

		if(ui.data.ss != undefined && ui.data.ss !== false) {
			$.ajax({
				url : "app/model/CalculatePageviews.php?quick=1",
				success : function(result){
					res = ui.ParseJSON(result);
					/* Set the current volume */
					current_volume = res.Data.pageviews;
					$(".user-menu .cur_volume").show();
					$(".user-menu .cur_volume").html(Number(current_volume).toLocaleString() + " in " + Number(res.Data.profiles).toLocaleString() + " profile(s)." );

				}
			});
		}

	});

	$("body").on("click", ".send_error_report", function() {
		ui.SendError();
	});

	$(".content").on("click", ".display_error_report", function() {
		ui.DisplayError();
	});

	//track usage so we can improve how people navigate the software
	if(ui.data.usage_tracking === 1){
		$("body").on("mousedown", function(e){

			item = $(e.target).clone();
			item.html("");
			item = $(item).prop("outerHTML");

			if (item.length > 512) {
				// too general, never mind
				return;
			}

			if (ui.usage_data[item] == undefined) {
				ui.usage_data[item] = 1;
			} else {
				ui.usage_data[item]++;
			}
		});
		setInterval(function() {
			ui.SendUsage();
		}, 60000);
	}

	// Only add scrolling on menu when we are on a desktop view.
	if($(document).width() > 991){
		/* Set the correct height in initial status */
		$("#main-menu").css("height", ($(document).height() - 105) + "px");
		$("#main-menu").css("overflow-y", "auto");
		/* Set the correct height for the menu on resize */
		$(document).resize(function(){
			$("#main-menu").css("height", ($(document).height() - 105) + "px");
			$("#main-menu").css("overflow-y", "auto");
		});
	}

	$(".content,.modal-dialog").on("click",".btn-upgrade-subscription", function(){
		console.log(ui.data);
		if (ui.data.subscriptions_url.length > 0) {
			window.location.href= ui.data.subscriptions_url;
		} else {
			createIframeWindow("subscriptions.php", ui.data.languages["_SUBSCRIPTIONS"]);
		}
	});

	/* Delete ip number modal */
	$(".content").on("click", ".open_delete_ipnumber" , function(e){
		e.preventDefault();
		ui.ShowWidget(".delete-ipnumber-settings");
		/* Set the fields correct */
		var d = new Date();
		$("#widgetModal [name='fday']").val( d.getDate() );
		$("#widgetModal [name='fmonth']").val( d.getMonth() );
		$("#widgetModal [name='fyear']").val( d.getFullYear() );
		$("#widgetModal [name='tday']").val( d.getDate() );
		$("#widgetModal [name='tmonth']").val( d.getMonth() );
		$("#widgetModal [name='tyear']").val( d.getFullYear() );

		$("#widgetModal [name='fldvalue']").val( $(this).attr("data-ipnumber") );

		$("#widgetModal .delete-ipnumber-settings .delete-ipnumber").on("click", function(e){
			e.preventDefault();
			var f = $("#widgetModal [name='fday']").val() + "/" + $("#widgetModal [name='fmonth']").val() + "/" + $("#widgetModal [name='fyear']").val();
			var t = $("#widgetModal [name='tday']").val() + "/" + $("#widgetModal [name='tmonth']").val() + "/" + $("#widgetModal [name='tyear']").val();
			var v = $("#widgetModal [name='fldvalue']").val();

			var btn = $(this);
			btn.button('loading');

			$.ajax({
				url: 'app/model/DeleteData.php',
				type: "POST",
				data: { fldvalue : v, fldname : 'ipnumber', fromdate : f, todate : t, "conf" : conf },
				success: function(result) {
					res =  ui.ParseJSON(result);
					ui.Callout(res);
					btn.button('reset');
					if(res.Status == "Success"){
						ui.HideWidget(".delete-ipnumber-settings");
					}
				}
			});
		});
	});
	/* Delete page modal */
	$(".content").on("click", ".open_delete_page" , function(e){
		e.preventDefault();
		ui.ShowWidget(".delete-page-settings");
		/* Set the fields correct */
		var d = new Date();
		$("#widgetModal [name='fday']").val( d.getDate() );
		$("#widgetModal [name='fmonth']").val( d.getMonth() );
		$("#widgetModal [name='fyear']").val( d.getFullYear() );
		$("#widgetModal [name='tday']").val( d.getDate() );
		$("#widgetModal [name='tmonth']").val( d.getMonth() );
		$("#widgetModal [name='tyear']").val( d.getFullYear() );
		$("#widgetModal [name='fldvalue']").val( $(this).attr("data-page") );

		$("#widgetModal .delete-page-settings .delete-page").on("click", function(e){
			e.preventDefault();
			var f = $("#widgetModal [name='fday']").val() + "/" + $("#widgetModal [name='fmonth']").val() + "/" + $("#widgetModal [name='fyear']").val();
			var t = $("#widgetModal [name='tday']").val() + "/" + $("#widgetModal [name='tmonth']").val() + "/" + $("#widgetModal [name='tyear']").val();
			var p = $("#widgetModal [name='fldvalue']").val();

			var btn = $(this);
			btn.button('loading');

			$.ajax({
				url: 'app/model/DeleteData.php',
				type: "POST",
				data: { fldvalue : p, fldname : 'page', fromdate : f, todate : t, "conf" : conf },
				success: function(result) {
					res =  ui.ParseJSON(result);
					ui.Callout(res);
					btn.button('reset');
					if(res.Status == "Success"){
						ui.HideWidget(".delete-page-settings");
					}
				}
			});

		});

	});
	$(".uiloader").hide();

	$(".qalink").on("click", function(){
		Intercom('show');
	});
	var popit = false;
	if (window.location.pathname.indexOf("/index.php") > -1 || window.location.pathname.slice(-1) == "/" || window.location.pathname.indexOf("/#") > -1) {
		// we are in the control panel
		$('.dashboardtutorial,.reporttutorial').closest("li").hide();
		popit = true;
	}
	if (window.location.pathname.indexOf("/dashboard.php") > -1) {
		// we are in the dashboard
		$('.cp-profiletutorial').closest("li").hide();
		popit = true;
	}
	if (window.location.pathname.indexOf("/profile.php") > -1) {
		// we are in the profile
		$('.dashboardtutorial,.reporttutorial,.cp-profiletutorial').closest("li").hide();
	}

	if (ui.data.user['accessAddProfile']==0) {
		$('.cp-profiletutorial').closest("li").hide();
	}

	if(ui.GetCookie('notutorial') != 1 && (!ui.GetCookie('tutorialcookie') || ui.GetCookie('tutorialcookie') == 0 ) ){
		if (popit == true) {
			$('#tutorialPopUp').modal('show');
			$('#tutorialPopUp').animate({ 'top' : "100px" } , 800 , "easeOutQuint");
		}
	}

	/* Tutorial pop up handling */
	$('.close').on('click', function(){
		$('#tutorialPopUp').modal('hide');
	});

	$('#CloseButton').on('click', function(){
		$('#tutorialPopUp').modal('hide');
		if(document.getElementById('dont').checked) {
			ui.SetCookie('notutorial', 1, 86400000 * 390);
		}
	});


	$('#profiletutorial').on('click', function(e){
		if (window.location.pathname.indexOf("/profile.php") == -1) {
			e.stopPropagation();
			ui.SetCookie('tutorialcookie', 1);
			window.location.href = "profile.php?conf=newcnf&new=1";
		}

	});

	$('#dashboardtutorial').on('click', function(){
		if(conf == undefined){
		} else if($("#dashopt-datepicker").length == 0){
			e.stopPropagation();
			ui.SetCookie('tutorialcookie', 2);
			window.location.href = "dashboard.php?conf=" + conf;
		}
	});

	$('#reporttutorial').on('click', function(){
		if(conf == undefined){
		} else if($("#dashopt-datepicker").length == 0){
			e.stopPropagation();
			ui.SetCookie('tutorialcookie', 3);
			window.location.href = "dashboard.php?conf=" + conf;
		}
	});

	$(".tutorial-start").on("click", function(){
		$('#tutorialPopUp').modal('hide');

		if($(this).hasClass('disabled')){
			return false;
		}

		var tut_name = $(this).attr("data-tutorial");
		lgTutorial.settings({"Name" : "test" ,"Intro" : "ello"	,"End" : "bye" });
		lgTutorial.init(lgTutorial.tutorials[tut_name]);
		lgTutorial.start();
	});

	// THIS IS AN UNDOCUMENTED WAY TO REATTACH A STRIPE SUBSCRIPTION TO A USER ACCOUNT
	var new_stripe_cus_id = GetURLParameter('stripe_cus_id');
	var new_stripe_sub_id = GetURLParameter('stripe_sub_id');
	if (new_stripe_cus_id && new_stripe_sub_id) {
		if (ui.data.ss != false && ui.data.ss.cus_id == new_stripe_cus_id && ui.data.ss.sub_id == new_stripe_sub_id) {
			//already done, skip it
		} else {
			ui.data.ss = {};
			ui.data.ss.cus_id = new_stripe_cus_id;
			ui.data.ss.sub_id = new_stripe_sub_id;
			$("#licenseModal").show();
			ui.UpdateSub(function(){
				console.log(ui.data.ss);
			});
		}
	}

	// add the search featuire to the profile menu
	$("#psearch").on("keydown", function(){
		delay(function(){
			var request = {};
			request.term = $("#psearch").val();
			GetAvailableProfiles(request,function(data) {
				newdata = Array();
				$.each(data, function(k,v) {
					newdata[k] = Array(v.value, "1");

				});
				ui.data.profiles = newdata;
				ui.ReloadProfileMenu(ui.data);
			});
		}, 500 );

	});

	window.addEventListener('popstate', function(event) {
		//console.log('popstate fired!');
		console.log(event);
		if (event.state !== null) {
			eval(event.state.link);
			i = event.state.i;
			$(".pagename").html(data.menu_items[i].text+" ");
			$(".active_menu_item").not("[name='"+i+"']").removeClass("active_menu_item");
			$("[name='"+i+"']").addClass("active_menu_item");
			cat = $("[name='"+i+"']").attr("rel");
			if ($("#main-menu [data-cat='"+cat+"']").closest("li").hasClass("active")) {
				console.log('already open');
			} else {
				$("#main-menu [data-cat='"+cat+"']").click();
			}
		}

	});
}

/* -- Functions below use this to safely parse json -- */
ui.ParseJSON = function(data) {
	try {
		data = $.parseJSON(data);
	}
	catch(err) {

		if (ui.data == undefined) {

			ui.data = { "languages" : {"_CAUSED_BY_OUTPUT": "Error", "_SEND_ERROR_REPORT": "Send Error Report", "_DISPLAY_ERROR": "Display Error", "_UNEXPECTED_INTERNAL_ERROR": "Unexpected internal error"} };
		}
		ui.error_report = err.message + "\n"+ ui.data.languages["_CAUSED_BY_OUTPUT"] +":\n" + data;
		console.log(ui.error_report);
		console.log(err.stack);
		Intercom('trackEvent', 'encountered-ui-parsing-error');

		data = {};
		data.Status = "Error";
		data.Message = ui.data.languages["_UNEXPECTED_INTERNAL_ERROR"];
		data.Message += "&nbsp;&nbsp;<button class='btn btn-lg btn-success send_error_report'>"+ ui.data.languages["_SEND_ERROR_REPORT"] +"</button>";
		data.Message += "&nbsp;&nbsp;<button class='btn btn-lg btn-danger display_error_report' data-toggle='modal' data-target='#errorModal'>"+ ui.data.languages["_DISPLAY_ERROR"] +"</button>";
		data.ParseError = true;
		//callout the error to the user
		ui.Callout(data);

		// even though we have an error, try to find some JSON ...
		x = ui.error_report;
		if(x.lastIndexOf("}")>0) {
			var newres = x.substring(x.indexOf("{"), x.lastIndexOf("}")+1);
			try {
				data = $.parseJSON(newres);
				data.withErrors = true;
			}
			catch(err) {
				// never mind
			}
		}
	}

	/* If we have a key Callout set in the result then show the callout in the ui */
	if(data.Callout != undefined && data.Callout == true){
		ui.Callout(data);
	}

	/* if we receive a not logged in error, redirect the user to the login screen */
	if (data.Status=="Error" && data.Message=="You are not logged in.") {
		window.location.href = "login.php";
	}
	return data;

}

ui.ReloadUserInfo = function(){
	/* -- User Name -- */
	$(".user-menu .member_since").html("");
	$(".user-menu .username, .user-menu .userusername").html( ui.data.user.username );


	if (ui.data.user.name==null) {

		$(".user-menu .ufn").hide();
		$(".user-menu .userfullname").hide();

	} else {
		$(".user-menu .userfullname").html(ui.data.user.name);
	}

	var d = new Date(ui.data.user.created * 1000);
	$(".user-menu .member_since").html(d.toLocaleDateString());

	if(ui.data.user.email == null){
		$(".user-menu .uem").hide();
		$(".user-menu .useremail").hide();
	} else {
		$(".user-menu .useremail").html( ui.data.user.email );

	}

	/* -- languages menu -- */
	ui.languagemenu(ui.data.available_langs, ui.data.lang);

	if(ui.data.user.metadata != undefined){

		if(parseInt(ui.data.user.metadata.changeAccountInfo) === 1 || parseInt(ui.data.user.isAdmin) === 1){
			$(".user-account-btn").on("click", function(){
				ui.SetCookie("last_cp_action","_EDIT_USER");
			});
		} else{
			$(".user-account-btn").remove();
		}

	}

	if(ui.data.ss.type == "user") {
		$(".user-menu .prolabels").show();
		$(".user-menu .upgrade-but").hide();
		$(".user-menu .userplan").html( ui.data.ss.plan);
		d = new Date(ui.data.ss.current_period_end * 1000);
		$(".user-menu .userperiod").html( d.toLocaleDateString());
	} else if (ui.data.ss.type == "server") {
		$(".user-menu .prolabels").show();
		$(".user-menu .userplan").html("Pro");
		$(".user-menu .upgrade-but").hide();
	} else if (ui.data.hl == true) {
		$(".user-menu .userplan, .user-menu .uplan").hide();
		$(".user-menu .upgrade-but").hide();
	}


	$(".logout-btn").on("click", function(){
		Delete_Cookie('last_cp_action');
		Delete_Cookie('last_p_action');
		ui.Logout();
	});
}

ui.ReloadProfileMenu = function(data) {
	ui.data = data;

	var template_menu_item = ui.template_menu_item;
	template_menu_item.find("a").removeClass("curprofile");
	template_menu_item.find("a").attr("style", "");

	$(".profilemenu .menu li").remove();

	$.each(data.profiles, function( key, value ) {

		//populate the profiles menu			
		var item = template_menu_item.clone(true);
		item.find("h3").html(value[0]);
		// fix the links
		item.find(".view").attr("data-link", "dashboard.php?conf="+value[0]);
		item.find(".edit").attr("data-link", "profile.php?conf="+value[0]);
		item.find(".update").attr("data-link", "update.php?conf="+value[0]);

		//add to the dom
		$(".profilemenu .menu").append("<li>"+item.html()+"</li>");

	});
	$(".dropdown .num_profiles").html(data.pcount);

}

ui.LoadSegments = function(open_conf, callback){
	/* Select the widget area */
	var widgetarea = $("#widgetModal");
	/* Show widget */
	widgetarea.find(".modal-body").empty();
	widgetarea.find(".modal-title").html("Manage Segmentation Filters");
	widgetarea.modal("show");

	widgetarea.find(".modal-body").load("app/views/ManangeSegmentFilters.php?conf="+ open_conf, function(){
		$.getScript( "app/controller/ManangeSegmentFilters.min.js" ).done(function() {
			// loaded the widget controller
			$.ajax({
				url: "app/model/ManangeSegmentFilters.php?conf=" + open_conf,
				success: function(result) {
					var res = ui.ParseJSON(result);
					seg.Load(res);

					if(callback != undefined){ callback(); }
				}
			});
		});
	});

}

/* -- Show an element in the widget area -- */
ui.ShowWidget = function(widget){

	/* Select the widget area */
	var widgetarea = $("#widgetModal");
	/* Show widget */
	widgetarea.find(".modal-body").empty();

	var temp = $(".content_templates " + widget).clone(true);

	if(temp.attr('data-title') != undefined){
		widgetarea.find(".modal-title").html( temp.attr('data-title') );
	} else {
		widgetarea.find(".modal-title").html("&nbsp;");
	}

	/* Show element */
	widgetarea.find(".modal-body").html(temp);
	widgetarea.modal("show");
}

/* -- Hide an element in the widget area -- */
ui.HideWidget = function(widget){
	/* Select the widget area */
	var widgetarea = $("#widgetModal");
	widgetarea.find(".modal-body").empty();
	widgetarea.modal("hide");
}

ui.languagemenu = function(available_languages, selected) {
	$.each(available_languages, function( key, value ) {

		if (selected == value) {
			active = "active";
		} else {
			active = "";
		}

		value = value.substr(0,1).toUpperCase()+value.substr(1);

		$(".user-body .btn-group").append("<button class=\"btn btn-default "+active+"\" type=\"button\" title=\""+ value.toLowerCase() +"\"><img src=\"images/flags/"+value+".png\"></button>");
	});
	$(".user-body .btn-group .btn").on("click", function(e){
		e.preventDefault();
		var setlang = $(this).attr("title");
		$.ajax({
			url: "app/model/ChangeDefaultLang.php",
			type: "GET",
			data: { lang: setlang },
			success: function(result) {
				window.location.reload(); // window.location = window.location; // history.go(0);
			}
		});
	});
}

ui.captureforms = function() {
	$("body").on("submit", ".content .box form"  , function(e){
		e.preventDefault();
		$.ajax({
			url: $(this).attr('action'),
			type: "POST",
			data : $(this).serialize(),
			success: function(){
				//console.log('form submitted.');
			}
		});
	});
}

ui.populatemenu = function(menu_cat) {
	/* -- 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(menu_cat, 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.text);
		item.find(".treeview .categorie-name").attr("data-cat", key);
		item.find(".treeview i:first").addClass(value.icon);


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

		$.each(value.data, function( k, v ) {
			/* 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",v.text);

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

			/* 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();
}

ui.SetCookie = function (key, value, expire_time) {
	if(expire_time == undefined){
		expire_time = 86400000;
	}

	var expires = new Date();
	expires.setTime(expires.getTime() + (expire_time));
	document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

ui.GetCookie = function (key) {
	var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
	return keyValue ? keyValue[2] : null;
}

ui.SendError = function() {

	$.ajax({
		url: "https://software.logaholic.com/receive_error_report.php",
		type: "POST",
		crossDomain: true,
		data: { source: window.location.href, user: ui.data.user.username, email: ui.data.user.email, data: ui.error_report },
		success: function(result) {
			result = ui.ParseJSON(result);
			$(".response .callout-danger h4").html(result.Message);
		}
	});
}

ui.SendUsage = function() {
	if (Object.keys(ui.usage_data).length ==0) {
		//console.log("no usage data");
		return;
	}
	$.ajax({
		url: document.location.protocol + "//software.logaholic.com/receive_usage_data.php",
		type: "POST",
		crossDomain: true,
		data: { data: ui.usage_data },
		success: function(result) {
			//console.log(result);			
			ui.usage_data = {};
		}
	});
}

ui.LoadNews = function() {
	var newsmd5 = "";

	$.ajax({
		url: "includes/getrss.php",
		type: "GET",
		success: function(result) {

			result = ui.ParseJSON(result);
			if (result.Status=="Error") {
				ui.Callout(result);
			}
			newsmd5 = result.md5;

			var i = 0;
			$.each(result, function(k,v) {

				if (v.title==undefined || v.desc==undefined || v.link == undefined) {
					return;
				}
				item = $(".messages-menu .menu li:first").clone(true);
				item.show();
				item.find("strong").html(v.title);
				item.find("a").append(v.desc.substr(0, 80)+"...<br><small>"+v.date+"</small> ");
				item.find("a").attr("href", v.link);
				$(".messages-menu .menu").append(item);
				i++;
			});
			if (ui.GetCookie("newsitems")!=newsmd5) {
				$(".messages-menu .label-danger").html(i).show();
			}
			$(".messages-menu .mesnum").html("You have "+i+" messages");
		}
	});

	$(".messages-menu").on("click", function() {
		ui.LoadNews();
		ui.SetCookie("newsitems", newsmd5, (86400000 * 365) );
		$(".messages-menu .label-danger").fadeOut();
	});
}

/* -- This handles common calout displaying for some of the functions below-- */
ui.Callout = function(res) {

	if (res.Status=="Success") {
		if (res.withErrors == true) {
			// leave the error
		} else {
			$(".response .callout-danger-template").hide();
		}
		$(".response .callout-success-template").hide();
		$(".response .callout-success-template h4").html(res.Message);
		$(".response .callout-success-template").fadeIn();
		//console.log(res);
	} else {
		$(".response .callout-danger-template").hide();
		$(".response .callout-success-template").hide();
		$(".response .callout-danger-template h4").html(res.Message);
		$(".response .callout-danger-template").fadeIn();
		console.log(res);
	}
	return res;
}

ui.DisplayError = function() {
	//console.log($("#errorModal .modal-body").html());
	$("#errorModal .modal-body").html(ui.error_report);
	// $(".content").remove();

	// $(".system-response .callout-danger-system").hide();
	// $(".system-response .callout-danger-system h4").html(res.Message);
	// $(".system-response .callout-danger-system").fadeIn();
	// console.log(res);

	return res;
}


var reportmenu = {}
reportmenu.state = 0;
reportmenu.search = function() {

	/* Hide reports that don't match the criteria, and show the ones that do */
	$(".sidebar-menu .treeview").hide();

	$(".menu-report").each(function() {
		if($(this).html().toLowerCase().indexOf($(".search_menu").val().toLowerCase()) >= 0) {
			$(this).show();
			$(this).closest(".treeview").show();
		} else {
			$(this).hide();
		}
	});

	// this searches the editprofile view and shows the related menu iten
	$(".content .editprofile .box.box-solid").each(function() {
		if($(this).html().toLowerCase().indexOf($(".search_menu").val().toLowerCase()) >= 0) {
			rel = $(this).attr("rel");
			if (rel!=undefined) {
				$("[name="+rel+"]").show();
			}
		}
	});

	if (reportmenu.state!=1) {
		reportmenu.open();
	}

	if($(".search_menu").val() == "") {
		$("#search-btn i").removeClass("fa-times");
		$("#search-btn i").addClass("fa-search");
	} else {
		$("#search-btn i").removeClass("fa-search");
		$("#search-btn i").addClass("fa-times");
	}
}

reportmenu.open = function() {
	$(".sidebar-menu .treeview-menu").slideDown();
	$(".sidebar-menu .treeview .fa-angle-left").removeClass("fa-angle-left").addClass("fa-angle-down");
	$(".sidebar-menu .treeview").addClass("active");
	reportmenu.state=1;
	reportmenu.search();
}

reportmenu.close = function() {
	$(".sidebar-menu .treeview-menu").slideUp();
	$(".sidebar-menu .treeview.active .fa-angle-down").removeClass("fa-angle-down").addClass("fa-angle-left");
	$(".sidebar-menu .treeview.active").removeClass("active");
	reportmenu.state=0;
}

reportmenu.toggle = function() {
	if (reportmenu.state==1) {
		reportmenu.close();

	} else {
		reportmenu.open();

	}
}

ui.Logout = function(){
	$.ajax({
		url: "app/model/Authentication.php",
		type : 'POST',
		data : { action : "logout" },
		success: function(result) {
			var r = $.parseJSON(result);

			if(r.Status == undefined || r.Status != "Success"){
			} else if(r.Status == "Success"){
				if (r.redirect == undefined) {
					window.location.href = 'login.php';
				} else {
					window.location.href = r.redirect;
				}
			}
		}
	});
}

ui.SystemError = function(res) {
	$(".content").remove();

	$(".system-response .callout-danger-system").hide();
	$(".system-response .callout-danger-system h4").html(res.Message);
	$(".system-response .callout-danger-system").fadeIn();
	console.log(res);

	return res;
}

ui.BlockedBySubscription = function(option, value, show, error){
	if(value == undefined){ value = "Disabled";	}
	if(show == undefined){ show = true;	}

	//console.log(ui.data.session.subscription);

	if(ui.data.session.subscription != undefined && ui.data.session.subscription[option] != undefined){
		if(ui.data.session.subscription[option] == value){
			//if(error == undefined){
			var msg = ui.data.languages["_SUBSCRIPTION_UPGRADE_NOTICE"].replace("%x", "<strong>"+ option +"</strong>") + ".<br/><br/><button class='btn-upgrade-subscription btn btn-primary'>"+ ui.data.languages["_UPGRADE_NOW"] +"</button>";
			if (show ==true){
				ui.Callout({ Status : "Success", Message : msg });
			}
			//}
			return true;
		}
	}
	return false;
}

ui.LicenseUpgrade = function() {

	if(parseInt(ui.data.user.isAdmin) == 0){
		$("#licenseModal .product_name").html('Logaholic Pro Account');
		$("#licenseModal .username").html(ui.data.user.username);

		$("#licenseModal #license_user_help").show();

	} else {
		$("#licenseModal #license_admin_help").show();

	}
	$("#licenseModal").modal('show');
	ui.currency = 'usd';
	$("#licenseModal .stripe-load").load("https://software.logaholic.com/stripe/submodal-quaderno.php?currency="+ui.currency);

	Intercom('trackEvent', 'checked-out-pro-pricing');

}

ui.ChangeCurrency = function() {
	if (ui.currency == 'usd') {
		ui.currency = 'eur';
	} else {
		ui.currency = 'usd';
	}
	$("#licenseModal .stripe-load").load("https://software.logaholic.com/stripe/submodal-quaderno.php?currency="+ui.currency);
}

ui.ProLicenseInfo = function() {

	$(".license_info .upgrade-but").hide();
	$(".license_info .subscribed").show();
	$(".license_info").show();

	ui.UpdateSub(function(){
		d = new Date(ui.data.ss.start * 1000);
		d2 = new Date(ui.data.ss.current_period_end * 1000);
		$(".license_info .billing_name").html(ui.data.ss.name);
		$(".license_info .billing_address").html(ui.data.ss.address);
		$(".license_info .planname").html(ui.data.ss.plan);
		$(".license_info .billing_email").html(ui.data.ss.email);
		$(".license_info .billing_started").html(d.toLocaleDateString());
		$(".license_info .billing_cc").html(ui.data.ss.cc);
		$(".license_info .billing_current_period_end").html(d2.toLocaleDateString());
		$(".license_info .billing_pageviews").html(" / "+Number(ui.data.ss.pageviews).toLocaleString());

		$.ajax({
			url : "app/model/CalculatePageviews.php",
			success : function(result){
				res = ui.ParseJSON(result);
				/* Set the current volume */
				current_volume = res.Data.pageviews;
				$(".license_info .billing_pageviews").prepend(Number(current_volume).toLocaleString());
			}
		});
	});
}
ui.CancelPro = function() {
	var confirmation = confirm('Are you sure you want to cancel your subscription?\n\nIf you choose OK, your access to Pro features will be removed.');
	if(confirmation == true) {
		$("#licenseModal").modal('show');
		$("#licenseModal .modal-body").html("<div style='text-align:center'><i class='fa fa-spinner fa-spin'> </i> Please wait");

		$.post(
			"https://software.logaholic.com/stripe/cancelsub.php",
			{ cus: ui.data.ss.cus_id, sub: ui.data.ss.sub_id },
			function(data) {
				res = ui.ParseJSON(data);
				//console.log(res);
				$.ajax({
					url : "includes/cancelsub.php",
					success : function(result){
						$("#licenseModal .modal-body").html(result);
						$("#licenseModal .reload").show();
					}
				});
			}
		);
	}
}
var MD5=function(s){function L(k,d){return(k<<d)|(k>>>(32-d))}function K(G,k){var I,d,F,H,x;F=(G&2147483648);H=(k&2147483648);I=(G&1073741824);d=(k&1073741824);x=(G&1073741823)+(k&1073741823);if(I&d){return(x^2147483648^F^H)}if(I|d){if(x&1073741824){return(x^3221225472^F^H)}else{return(x^1073741824^F^H)}}else{return(x^F^H)}}function r(d,F,k){return(d&F)|((~d)&k)}function q(d,F,k){return(d&k)|(F&(~k))}function p(d,F,k){return(d^F^k)}function n(d,F,k){return(F^(d|(~k)))}function u(G,F,aa,Z,k,H,I){G=K(G,K(K(r(F,aa,Z),k),I));return K(L(G,H),F)}function f(G,F,aa,Z,k,H,I){G=K(G,K(K(q(F,aa,Z),k),I));return K(L(G,H),F)}function D(G,F,aa,Z,k,H,I){G=K(G,K(K(p(F,aa,Z),k),I));return K(L(G,H),F)}function t(G,F,aa,Z,k,H,I){G=K(G,K(K(n(F,aa,Z),k),I));return K(L(G,H),F)}function e(G){var Z;var F=G.length;var x=F+8;var k=(x-(x%64))/64;var I=(k+1)*16;var aa=Array(I-1);var d=0;var H=0;while(H<F){Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=(aa[Z]| (G.charCodeAt(H)<<d));H++}Z=(H-(H%4))/4;d=(H%4)*8;aa[Z]=aa[Z]|(128<<d);aa[I-2]=F<<3;aa[I-1]=F>>>29;return aa}function B(x){var k="",F="",G,d;for(d=0;d<=3;d++){G=(x>>>(d*8))&255;F="0"+G.toString(16);k=k+F.substr(F.length-2,2)}return k}function J(k){k=k.replace(/rn/g,"n");var d="";for(var F=0;F<k.length;F++){var x=k.charCodeAt(F);if(x<128){d+=String.fromCharCode(x)}else{if((x>127)&&(x<2048)){d+=String.fromCharCode((x>>6)|192);d+=String.fromCharCode((x&63)|128)}else{d+=String.fromCharCode((x>>12)|224);d+=String.fromCharCode(((x>>6)&63)|128);d+=String.fromCharCode((x&63)|128)}}}return d}var C=Array();var P,h,E,v,g,Y,X,W,V;var S=7,Q=12,N=17,M=22;var A=5,z=9,y=14,w=20;var o=4,m=11,l=16,j=23;var U=6,T=10,R=15,O=21;s=J(s);C=e(s);Y=1732584193;X=4023233417;W=2562383102;V=271733878;for(P=0;P<C.length;P+=16){h=Y;E=X;v=W;g=V;Y=u(Y,X,W,V,C[P+0],S,3614090360);V=u(V,Y,X,W,C[P+1],Q,3905402710);W=u(W,V,Y,X,C[P+2],N,606105819);X=u(X,W,V,Y,C[P+3],M,3250441966);Y=u(Y,X,W,V,C[P+4],S,4118548399);V=u(V,Y,X,W,C[P+5],Q,1200080426);W=u(W,V,Y,X,C[P+6],N,2821735955);X=u(X,W,V,Y,C[P+7],M,4249261313);Y=u(Y,X,W,V,C[P+8],S,1770035416);V=u(V,Y,X,W,C[P+9],Q,2336552879);W=u(W,V,Y,X,C[P+10],N,4294925233);X=u(X,W,V,Y,C[P+11],M,2304563134);Y=u(Y,X,W,V,C[P+12],S,1804603682);V=u(V,Y,X,W,C[P+13],Q,4254626195);W=u(W,V,Y,X,C[P+14],N,2792965006);X=u(X,W,V,Y,C[P+15],M,1236535329);Y=f(Y,X,W,V,C[P+1],A,4129170786);V=f(V,Y,X,W,C[P+6],z,3225465664);W=f(W,V,Y,X,C[P+11],y,643717713);X=f(X,W,V,Y,C[P+0],w,3921069994);Y=f(Y,X,W,V,C[P+5],A,3593408605);V=f(V,Y,X,W,C[P+10],z,38016083);W=f(W,V,Y,X,C[P+15],y,3634488961);X=f(X,W,V,Y,C[P+4],w,3889429448);Y=f(Y,X,W,V,C[P+9],A,568446438);V=f(V,Y,X,W,C[P+14],z,3275163606);W=f(W,V,Y,X,C[P+3],y,4107603335);X=f(X,W,V,Y,C[P+8],w,1163531501);Y=f(Y,X,W,V,C[P+13],A,2850285829);V=f(V,Y,X,W,C[P+2],z,4243563512);W=f(W,V,Y,X,C[P+7],y,1735328473);X=f(X,W,V,Y,C[P+12],w,2368359562);Y=D(Y,X,W,V,C[P+5],o,4294588738);V=D(V,Y,X,W,C[P+8],m,2272392833);W=D(W,V,Y,X,C[P+11],l,1839030562);X=D(X,W,V,Y,C[P+14],j,4259657740);Y=D(Y,X,W,V,C[P+1],o,2763975236);V=D(V,Y,X,W,C[P+4],m,1272893353);W=D(W,V,Y,X,C[P+7],l,4139469664);X=D(X,W,V,Y,C[P+10],j,3200236656);Y=D(Y,X,W,V,C[P+13],o,681279174);V=D(V,Y,X,W,C[P+0],m,3936430074);W=D(W,V,Y,X,C[P+3],l,3572445317);X=D(X,W,V,Y,C[P+6],j,76029189);Y=D(Y,X,W,V,C[P+9],o,3654602809);V=D(V,Y,X,W,C[P+12],m,3873151461);W=D(W,V,Y,X,C[P+15],l,530742520);X=D(X,W,V,Y,C[P+2],j,3299628645);Y=t(Y,X,W,V,C[P+0],U,4096336452);V=t(V,Y,X,W,C[P+7],T,1126891415);W=t(W,V,Y,X,C[P+14],R,2878612391);X=t(X,W,V,Y,C[P+5],O,4237533241);Y=t(Y,X,W,V,C[P+12],U,1700485571);V=t(V,Y,X,W,C[P+3],T,2399980690);W=t(W,V,Y,X,C[P+10],R,4293915773);X=t(X,W,V,Y,C[P+1],O,2240044497);Y=t(Y,X,W,V,C[P+8],U,1873313359);V=t(V,Y,X,W,C[P+15],T,4264355552);W=t(W,V,Y,X,C[P+6],R,2734768916);X=t(X,W,V,Y,C[P+13],O,1309151649);Y=t(Y,X,W,V,C[P+4],U,4149444226);V=t(V,Y,X,W,C[P+11],T,3174756917);W=t(W,V,Y,X,C[P+2],R,718787259);X=t(X,W,V,Y,C[P+9],O,3951481745);Y=K(Y,h);X=K(X,E);W=K(W,v);V=K(V,g)}var i=B(Y)+B(X)+B(W)+B(V);return i.toLowerCase()};

ui.CheckPro = function() {
	if (ui.CheckExpires()==false) {
		ui.CheckUsage();
	}

}

ui.CheckUsage = function() {
	if (ui.data.user.metadata) {
		if (ui.data.user.metadata.current_usage != undefined && ui.data.user.metadata.current_usage.pageviews) {
			if (ui.data.user.metadata.current_usage.pageviews > ui.data.ss.pageviews) {
				// over the limit
				$("#licenseModal .modal-title").html('Please upgrade your Logaholic Pro Subscription');
				$("#licenseModal .license_pageviews").html('The pageview limit for your plan has been exceeded ('+ui.data.user.metadata.current_usage.pageviews.toLocaleString()+' / '+Number(ui.data.ss.pageviews).toLocaleString()+').<br>Please choose a new monthly pageview limit:');
				$("#licenseModal .license_price .description").html('Any remaining balance is prorated towards your new plan.');
				ui.LicenseUpgrade();
			}
		}
	}
}

ui.PlanChange = function() {
	$("#licenseModal .modal-title").html('Change Logaholic Pro Subscription');
	$("#licenseModal .license_price .description").html('Any remaining balance is prorated towards your new plan.');
	ui.LicenseUpgrade();
}

ui.CheckExpires = function() {

	if ((ui.data.ss.current_period_end*1000) < Date.now()) {
		// sub has expired, let check to see if a payment has been made
		ui.UpdateSub(function() {
			// now check again
			if ((ui.data.ss.current_period_end*1000) < Date.now()) {
				$("#licenseModal .modal-title").html('Your Logaholic Pro Subscription has expired');
				ui.LicenseUpgrade();
				return true;
			}
		});

	}
	return false;

}

ui.UpdateSub = function(callback) {

	$.post(
		"https://software.logaholic.com/stripe/getsub.php", /* your route here */
		{ cus: ui.data.ss.cus_id, sub: ui.data.ss.sub_id },
		function(data) {
			res = ui.ParseJSON(data);
			// now save it
			if (res.Status == "Success") {
				pdata = {
					Status : "Success",
					name: res.name,
					address: res.address,
					current_period_end: res.current_period_end,
					current_period_start: res.current_period_start,
					cus_id: ui.data.ss.cus_id,
					email: res.email,
					pageviews: res.pageviews,
					plan: res.plan,
					sub_id: ui.data.ss.sub_id,
					start: res.start,
					cc: res.cc
				};
				//console.log(pdata);

				$.post("includes/process_charge.php", pdata, function(d) {
					// $("#licenseModal .modal-title").html('Your Logaholic Pro Subscription has been updated');
					// $("#licenseModal").modal('show');
					//console.log(pdata.pageviews + ' >' + ui.data.user.metadata.current_usage.pageviews);
					//console.log($('#licenseModal').is(':visible'));

					if ($('#licenseModal').is(':visible') && (pdata.pageviews > ui.data.user.metadata.current_usage.pageviews)) {
						$("#licenseModal .modal-body").html(d);
						$("#licenseModal .reload").show();
					}
					console.log('Updated subscription info');
					ui.data.ss = pdata;
					callback();
				});
			} else {
				$("#licenseModal .modal-body").html("There was a problem retrieving your subscription info.");
				$("#licenseModal .reload").show();
			}

		}
	);
}