
var conf = GetURLParameter('conf');
if(conf != undefined && conf != ""){
	window.location.href = "dashboard.php?conf=" + conf;
}

$(document).ready(function(){

		
	// load the data
	$.ajax({
		url: "app/model/ControlPanel.php",
		success: function(result) {
			res = ui.ParseJSON(result);	
			if (res.Status == "Success") {

				ui.Load( res );
				cp.Load( res );
			} 
		}
	});


});

var checktimer = 0;

var cp = {};

/* -- Load inserts data into the page and adds controls on elements -- */	
cp.Load = function (data){
	
	/* -- Add the page name -- */
	$(".confname").html(ui.data.languages["_CONTROL_PANEL"]);
	$(".pagename").html(ui.data.languages["_CONTROL_PANEL"]);
	$(".locationname").html(ui.data.languages["_CONTROL_PANEL"]);

	/* -- change the search placeholder -- */
	$(".sidebar-form input").attr("placeholder", ui.data.languages["_SEARCH_SETTINGS"] + " ...");
	/* -- create the menu -- */
	ui.populatemenu(data.menu_cat);

	/* 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' , function(){
			$(".versioncheck-reload").button('reset');
			$(".versioncheck-reload").on("click", function(){
				window.location.href = window.location.href;
			});
		});
	}

	/* -- add menu handing -- */
	$(".menu-report").on("click", function(e){
		e.preventDefault();	
				
		$(".active_menu_item").not(this).removeClass("active_menu_item");
		$(this).addClass("active_menu_item");

		i = $(this).attr("name");
		eval(data.menu_items[i]['action']);
		$(".pagename").html(data.menu_items[i].text);
		history.pushState({link: data.menu_items[i]['action'], i: i}, i);

		if (i !='_INSTALLATION_SETUP' && i !='_CREATE_NEW_PROFILE' && i !='_ACTIVATE_PROFILES') {
			ui.SetCookie("last_cp_action", i);			
		}
			
	});
	
	/* -- Open the menu and Load the profile list by default, or whatever is in the cookie OR the hashtag -- */	
	if (window.location.hash.substr(1)!="") {
		i = window.location.hash.substr(1);
		
		var uname = GetURLParameter("username");
		if (i == "_EDIT_USER" && uname !== undefined && parseInt(ui.data.user.isAdmin) == 1) {
			$.ajax({
				url: "app/model/UserAdministration.php",
				type: "POST",
				data: {"username": uname },
				success: function(result) {
					var udata = ui.ParseJSON(result);
					cp.LoadView('app/views/CreateEditUser.php');						
					$.getScript( "app/controller/CreateEditUser.min.js" , function(){
							user.DisplayUser( udata.Users[0] );
					});	
				}
			});
			
		} else {
			$(".pagename").html(data.menu_items[i].text);
			$("[name='"+i+"']").addClass("active_menu_item");
			cat = $("[name='"+i+"']").attr("rel");
			$("#main-menu [data-cat='"+cat+"']").click();
			history.replaceState({link: data.menu_items[i]['action'], i: i}, i, document.location.href);
			eval(data.menu_items[i]['action']);
		}
		

	} else if (ui.GetCookie("last_cp_action")!=null  && ui.GetCookie("last_cp_action") != '_CREATE_NEW_PROFILE' && ui.GetCookie("last_cp_action") != '_INSTALLATION_SETUP') {
		i = ui.GetCookie("last_cp_action");

		if(data.menu_items[i] != undefined){
			$(".pagename").html(data.menu_items[i].text);
			$("[name='"+i+"']").addClass("active_menu_item");
			cat = $("[name='"+i+"']").attr("rel");
			$("#main-menu [data-cat='"+cat+"']").click();
			history.replaceState({link: data.menu_items[i]['action'], i: i}, document.location.href);
			eval(data.menu_items[i]['action']);			
		} else {	
			$("#main-menu li:first a:first").click();
			cp.ProfileTable();
		}
	} else {	
		$("#main-menu li:first a:first").click();
		cp.ProfileTable();
	}

}

/* -- This function is used to load additional views -- */
cp.LoadView = function(view) {
	/* -- Hide the system responses -- */
	$(".system-response .callout").hide();	

	/* -- Clean the content area -- */	
	$(".content").html("");

	/* -- Load the view -- */
	$.ajax({
        url: view,
        success: function(result) {
        	try {
		    	data = $.parseJSON(result);
		    	ui.SystemError(data);
		    } 
		    catch(err) {
        		$(".content").html(result);
		    }
        },
        async: false
    });
}

/* -- This is used for toggle buttons if the functions below-- */
cp.UpdateToggleButtons = function(status, container_class) {

	if (status == "Disabled") {

		$("."+container_class+" .disable_this").removeClass("btn-default");
		$("."+container_class+" .disable_this").addClass("btn-primary disabled");

		$("."+container_class+" .enable_this").addClass("btn-default");
		$("."+container_class+" .enable_this").removeClass("btn-primary disabled");

	} else if (status == "Enabled") {				

		$("."+container_class+" .enable_this").removeClass("btn-default");
		$("."+container_class+" .enable_this").addClass("btn-primary disabled");

		$("."+container_class+" .disable_this").addClass("btn-default");	
		$("."+container_class+" .disable_this").removeClass("btn-primary disabled");
	}	
}

/* -- Controller for the profile list -- */
cp.ProfileTable = function() {
	
	/* -- Load the view -- */
	cp.LoadView('app/views/ManageProfiles.php');

	/* -- Get the template elements we need -- */
	table = $("#manage_profiles");
	tr = table.find("tbody tr").clone(true);
	plist_buttons = tr.find(".plist-buttons").clone(true);
	activated = tr.find(".plist-activated").clone(true);

	$(".content").html(table);

	//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;
	}
	/* -- set up the data table for profiles -- */
	$('#profile_table').dataTable({
		"ajax": 'app/model/ProfileList.php',
        "bPaginate": true,
        "bFilter": true,
        "bLengthChange": true,
        "bSort": true,
        "bInfo": true,
        "language": {
			"info": ui.data.languages['_SHOW'] + " _START_ - _END_ / _TOTAL_",
			"paginate": {
				"previous": ui.data.languages['_PREVIOUS'],
				"next": ui.data.languages['_NEXT']
			},
			"lengthMenu": ui.data.languages['_SHOW']+ " _MENU_"
		},
        "columnDefs": [        	
		    {"targets": [0,1,2,4,5,3],		    
		    "render": function ( data, type, full, meta ) {

			    if (meta.col==0) {			    	
			      	return '<span class="table-profilename">'+data+'</span>';
			    }
			    
			    if (meta.col==1) {
			    	c = activated.clone(true);
			    	if (data != 1) {			    		
			    		c.find(".profile-active").remove();
						c.find(".profile-disabled").show();
			    	}
			    	return c.html();			      	
			    }

			    if (meta.col==2) {
					c = plist_buttons.clone(true);
			    	if(parseInt(ui.data.user.isAdmin) == 0){
						// if the user is not allowed to edit then remove the button
						if(parseInt(ui.data.user.accessEditProfile) == 0){
							c.find(".profile-edit").remove();
						}
						if (subupdate==false) {
							// if the user is not allowed to update then remove the button
							if(parseInt(ui.data.user.accessUpdateLogs) == 0){
								c.find(".profile-update").remove();
							}			
						}
					}			    	
			      	return c.html();
			    }
			    if (meta.col==4 || meta.col==5 || meta.col==3) {
				    if ( type === 'display' || type === 'filter' ) {			            
			            return data;
			        }
			        ndata = $(data).filter(".sorter").text();			        
			       	return ndata;
			    
			    }

			}
		  } ]
    });
	ReplaceDataTablesSearch('#manage_profiles' , ui.data.languages['_SEARCH_PROFILES_MATCHING']);

	cp.ProfileButtons();

}

cp.CreateNewProfiles = function() {
	ui.SetCookie("last_cp_action", "_MANAGE_PROFILES");
	ui.SetCookie("last_p_action", "_PROFILE_INFO");
	window.location.href = 'profile.php?conf=newcnf&new=1';
}

cp.ProfileButtons = function() {
	
	$("#profile_table").on("click",".profile-view", function(e){
		conf = $(this).parents("tr").first().find(".table-profilename").html();
		document.location.href = "dashboard.php?conf="+conf;
	});

	$("#profile_table").on("click",".profile-update", function(e){
		conf = $(this).parents("tr").first().find(".table-profilename").html();
		document.location.href = "update.php?conf="+conf;
	});

	$("#profile_table").on("click",".profile-edit", function(e){
		conf = $(this).parents("tr").first().find(".table-profilename").html();
		document.location.href = "profile.php?conf="+conf;
	});
}

cp.ImportProfiles = function() {
	
	/* -- Load the view -- */
	cp.LoadView('app/views/ImportProfiles.php');

	$("#import-profile-form").submit(function(e) {
		e.preventDefault();  
            var fd = new FormData(document.getElementById("import-profile-form"));
            fd.append("label", "WEBUPLOAD");
            $.ajax({
              url: "app/model/ImportProfiles.php",
              type: "POST",
              data: fd,
              enctype: 'multipart/form-data',
              processData: false,  // tell jQuery not to process the data
              contentType: false   // tell jQuery not to set contentType
            }).done(function( data ) {
                
                data = ui.ParseJSON(data);
                
                if (data.Status == "Error") {
                	mes = $(".callout-danger-template").clone(true);
                	mes.removeClass("callout-danger-template");
                	
                } else if (data.Status == "Success"){
                	mes = $(".callout-success-template").clone(true);
                	mes.removeClass("callout-success-template");
                	// REload the data
					$.ajax({
						url: "app/model/index.php"
						,success: function(result) {
							ui.ReloadProfileMenu( ui.ParseJSON(result) );
						}
					});

                } else {
                	mes = $(".callout-danger-template").clone(true);
                	mes.removeClass("callout-danger-template");
                	data.Message = ui.data.languages["_IMPORT_PROFILE_BAD_RESPONSE"];
                }
                mes.find("h4").html(data.Message);
                $(".import-response").prepend(mes);
                mes.fadeIn(100);


            });
            return false;
    });

}

cp.ActivateAllProfiles = function() {
	var confirmation = confirm(ui.data.languages['_ACTIVATE_ALL_PROFILES_CONFIRM']);
	if(confirmation == true) {
		$.ajax({
			url: "app/model/ActivateAllProfiles.php?activateall=1",
			success: function(result) {
				window.location = window.location;
			}
		});

	}
	return false;
}

cp.UserAdministration = function() {
	/* -- Load the view -- */
	cp.LoadView('app/views/UserAdministration.php');
	$.getScript( "app/controller/UserAdministration.min.js");
}

cp.CreateEditUser = function() {
	/* -- Load the view -- */
	cp.LoadView('app/views/CreateEditUser.php');
	$.getScript( "app/controller/CreateEditUser.min.js");
}

cp.AuthenticationMethod = function() {
	/* -- Load the view -- */
	cp.LoadView('app/views/AuthenticationMethod.php');
	$.getScript( "app/controller/AuthenticationMethod.min.js");
}

cp.ChangeDefaultLang = function() {

	/* -- Load the view -- */
	cp.LoadView('app/views/ChangeDefaultLang.php?lang='+ui.data.lang);

	/* -- Select the current default lang -- */	
	$("[data-lang="+ui.data.lang+"]").removeClass("btn-default");
	$("[data-lang="+ui.data.lang+"]").addClass("btn-primary");
	$("[data-lang="+ui.data.lang+"]").addClass("disabled");

	/* -- Add click event to the language buttons-- */
	$(".change_language_link").on("click", function(e) {
		
		var setlang = $(this).attr("data-lang");
		
		$.ajax({
			url: "app/model/ChangeDefaultLang.php",
			type: "POST",
			data: { lang: setlang },
			success: function(result) {
				
				var res =  ui.ParseJSON(result);

				if (res.Status == "Success") {					
                	$(".callout-success-template").show();
                	
                	/* -- Select the new default lang -- */	
                	$("[data-lang="+ui.data.lang+"]").removeClass("btn-primary");
					$("[data-lang="+ui.data.lang+"]").addClass("btn-default");
					$("[data-lang="+ui.data.lang+"]").removeClass("disabled");

					$("[data-lang="+setlang+"]").removeClass("btn-default");
					$("[data-lang="+setlang+"]").addClass("btn-primary");
					$("[data-lang="+setlang+"]").addClass("disabled");

					/* -- Reload the screen to load the new language everywhere -- */	
					var count = 3;
					var countdown = setInterval(function(){
						$("#countdown").html(count);
						if (count == 0) {
							clearInterval(countdown);
							window.location = window.location;
						}
						count--;
					}, 1000);               	
                	
				} else {					
					$(".callout-danger-template h4").html(res);
					$(".callout-danger-template").show();
				}
				
			}
		});

	});
}
	
cp.ChangeDefaultDateFormat = function() {
	
	/* -- Load the view -- */
	cp.LoadView('app/views/ChangeDefaultDateFormat.php?lang='+ui.data.lang);

    function UpdatePreview() {
    	$(".callout-success-template").hide();
        $.ajax({
          url: 'includes/dateReturner.php',
          data: {dateString : $(".format1").val()+$(".seperator1").val()+$(".format2").val()+$(".seperator2").val()+$(".format3").val()+$(".seperator3").val()+$(".format4").val()},
          success: function(result) {
                $(".datepreview").html( ui.data.languages["_PREVIEW"] +": <strong>"+result+"</strong>");
          }
       });             
   	}

	/* -- Update the view -- */
   	UpdatePreview();

	/* -- Set up some click events -- */
	$("#change_custom_format select").change( function() {
    	UpdatePreview();
    });

	$(".restore-default-date-format-settings").click( function(){
		
        $(".format1 option[value='d']").attr('selected', 'selected');
        $(".seperator1 option[value=' ']").attr('selected', 'selected');
        $(".format2 option[value='M']").attr('selected', 'selected');
        $(".seperator2 option[value=' ']").attr('selected', 'selected');
        $(".format3 option[value='Y']").attr('selected', 'selected');
        $(".seperator3 option").removeAttr('selected');
        $(".format4 option[value='']").attr('selected', 'selected');
        
        UpdatePreview();
        $(".sumbitDefaultFormat").click();        
    });
	
    /* -- Add click event to the save button-- */
	$(".sumbitDefaultFormat").on("click", function(e) {
		
	    fmt = new FormData(document.getElementById("DateFormatForm"));
	    
	    $.ajax({
			url: "app/model/ChangeDefaultDateFormat.php?sumbitDefaultFormat=1",
			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 ) {        	
        	res =  ui.ParseJSON(data);        	
        	ui.Callout(res);
        });
	});	
}

cp.Signup = function() {

	function UpdateView(status) {
		
		cp.UpdateToggleButtons(status,"signup");	
		
		if (status == "Disabled") {
			$(".signup .alert.enable").show();
			$(".signup .alert.disable").hide();

		} else if (status == "Enabled") {				
			$(".signup .alert.disable").show();
			$(".signup .alert.enable").hide();
		}		
	}

	function Toggle(current) {
		$.ajax({
			url: "app/model/Signup.php?toggle=1",
			success: function(result) {
				res =  ui.ParseJSON(result);
				ui.Callout(res);
				if (res.Status != "Success") {					
					//it failed, reset the button 
        			UpdateView(current);
				}
			}
		});
	}

	function SetSettings(settings){
		$.each(settings , function(k,v){
			$(".signupsettings [name='"+ k +"']").val(v);
			if(v == true){
				$(".signupsettings [name='"+ k +"']").attr('checked','checked');
			}
		});
	}

	function SignupModel(postdata, cb){
		$.ajax({
			url: "app/model/Signup.php",
			type : 'POST',
			data : postdata,
			success: function(result) {
				res =  ui.ParseJSON(result);
				UpdateView(res.Status);
				if(res.Settings != undefined){
					SetSettings(res.Settings);
				}

				if(cb != undefined){
					cb(res);
				}
			}
		});
	}

	/* -- Load the view -- */
	cp.LoadView('app/views/Signup.php');

	/* -- Update the view -- */
	SignupModel({});


	/* -- Add click event to the buttons -- */
	$(".toggle button").on("click", function(e) {
		if ($(this).hasClass("disabled")) {	
			return;
		}

		if ($(this).hasClass("enable_this")) {			
			UpdateView("Enabled");
			Toggle("Disabled");
		} else {		
			UpdateView("Disabled");
			Toggle("Enabled");
		}
	});

	$(".save-signupsettings").on("click", function(e){
		e.preventDefault();
		var data = FormObjectToArray( $("#signupSettingsForm") );
		SignupModel(data, function(res){
			ui.Callout(res);
		});
	});
}

cp.UsageTracking = function(){
	
	function UpdateView(status) {
		
		cp.UpdateToggleButtons(status,"usagetracking");	
		
		if (status == "Disabled") {
			$(".usagetracking .alert.enable").show();
			$(".usagetracking .alert.disable").hide();

		} else if (status == "Enabled") {				
			$(".usagetracking .alert.disable").show();
			$(".usagetracking .alert.enable").hide();
		}		
	}

	function Toggle(current) {
		$.ajax({
			url: "app/model/UsageTracking.php?toggle=1",
			success: function(result) {
				res =  ui.ParseJSON(result);
				ui.Callout(res);
				if (res.Status != "Success") {					
					//it failed, reset the button 
        			UpdateView(current);
				}
			}
		});
	}

	/* -- Load the view -- */
	cp.LoadView('app/views/UsageTracking.php');

	/* -- Update the view -- */
	$.ajax({
		url: "app/model/UsageTracking.php",
		success: function(result) {
			res =  ui.ParseJSON(result);
			UpdateView(res.Status);
		}
	});

	/* -- Add click event to the buttons -- */
	$(".toggle button:not(.disabled)").on("click", function(e) {
		if ($(this).hasClass("disabled")) {	
			return;
		}

		if ($(this).hasClass("enable_this")) {			
			UpdateView("Enabled");
			Toggle("Disabled");
		} else {			
			UpdateView("Disabled");
			Toggle("Enabled");
		}
	});
}

cp.IPmasking = function() {
	
	function UpdateView(status) {
		
		cp.UpdateToggleButtons(status,"ipmasking");	
		
		if (status == "Disabled") {
			$(".ipmasking .alert.enable").show();
			$(".ipmasking .alert.disable").hide();

		} else if (status == "Enabled") {				
			$(".ipmasking .alert.disable").show();
			$(".ipmasking .alert.enable").hide();
		}		
	}

	function ToggleEncoding(current) {
		$.ajax({
			url: "app/model/IPmasking.php?toggle_ipencode=1",
			success: function(result) {
				res =  ui.ParseJSON(result);
				ui.Callout(res);
				if (res.Status != "Success") {					
					//it failed, reset the button 
        			UpdateView(current);
				}
			}
		});
	}

	/* -- Load the view -- */
	cp.LoadView('app/views/IPmasking.php');

	/* -- Update the view -- */
	$.ajax({
		url: "app/model/IPmasking.php",
		success: function(result) {
			res =  ui.ParseJSON(result);
			UpdateView(res.Status);
		}
	});

	/* -- Add click event to the buttons -- */
	$(".toggle button:not(.disabled)").on("click", function(e) {
		if ($(this).hasClass("disabled")) {	
			return;
		}

		if ($(this).hasClass("enable_this")) {			
			UpdateView("Enabled");
			ToggleEncoding("Disabled");
		} else {			
			UpdateView("Disabled");
			ToggleEncoding("Enabled");
		}

	});
}

cp.EmailAlerts = function() {
	
	function UpdateView(status) {

		cp.UpdateToggleButtons(status,"emailalerts");	

		if (status == "Disabled") {
			$(".emailalerts .alert.enable").show();
			$(".emailalerts .alert.disable").hide();
			
		} else if (status == "Enabled") {				
			$(".emailalerts .alert.disable").show();
			$(".emailalerts .alert.enable").hide();

		}		
	}

	function ToggleAlerts(current) {
		$.ajax({
			url: "app/model/EmailAlerts.php?toggle_emailalerts=1",
			success: function(result) {
				res =  ui.ParseJSON(result);
				ui.Callout(res);
				if (res.Status != "Success") {					
					//it failed, reset the button 
        			UpdateView(current);
				}
			}
		});
	}

	/* -- Load the view -- */
	cp.LoadView('app/views/EmailAlerts.php');

	/* -- Update the view -- */
	$.ajax({
		url: "app/model/EmailAlerts.php",
		success: function(result) {
			res =  ui.ParseJSON(result);
			UpdateView(res.Status);
		}
	});

	/* -- Add click event to the buttons -- */
	$(".toggle button").on("click", function(e) {
		if ($(this).hasClass("enable_this")) {
			
			UpdateView("Enabled");
			ToggleAlerts("Disabled");

		} else {
			
			UpdateView("Disabled");
			ToggleAlerts("Enabled");

		}

	});
	
}

cp.DatabaseInfo = function() {
	
	/* -- Load the view -- */
	cp.LoadView('app/views/DatabaseInfo.php');	

	/* -- Update the view -- */
	$(".dbinfo .numprofiles").html(ui.data.pcount);
	$(".dbinfo .numtables").html((ui.data.pcount*20));

	maxp = $(".dbinfo .progress-bar-yellow").attr("data-max");
	if (maxp < 1) {
		maxp = 1;
	}
	
	p = (ui.data.pcount / maxp) * 100;
	p = p + '%';
	t = ((ui.data.pcount*20) / (1000*15)) * 100;
	t = t + '%'	
	$(".dbinfo .progress-bar-yellow").width(p);
	$(".dbinfo .progress-bar-danger").width(t);

	$.ajax({
		url: "app/model/DatabaseInfo.php?getdbsize=1",
		success: function(result) {
			res =  ui.ParseJSON(result);
			if (res.Status == "Success") {
				$(".dbsize span").html(res.data); 
				     		
			} else {
				$(".dbsize span").html('Failed');
			}
		}
	});

	/* -- let's warn that root is not a good idea -- */
	if ($(".dbinfo .dbuname").html()=="root") {
		$(".dbinfo .dbuname_info span").switchClass("bg-green", "bg-red", 0);
		$(".dbinfo .dbuname_info i").switchClass("fa-check", "fa-exclamation", 0);
		$(".dbinfo .dbuname_info").append(ui.data.languages['_NON_ROOT_RECOMMENDED']);
	}

	/* -- load global stats -- */
	$('#globalstats_table').dataTable( {
		"aaSorting": [],
        "ajax": 'app/model/DatabaseInfo.php?globalstats=yes',
        "columns": [
            { "title": ui.data.languages['_PROFILE'] },
            { "title": ui.data.languages['_TABLE'] },
            { "title": ui.data.languages['_USER'] },
            { "title": ui.data.languages['_VISITS'] },
            { "title": ui.data.languages['_AVG_VISITS_DAY'] },
            { "title": ui.data.languages['_DATE_FROM'] },
            { "title": ui.data.languages['_DATE_TO'] },
            { "title": ui.data.languages['_LAST_UPDATED'] }
        ]
    } );    
	ReplaceDataTablesSearch('.globalstats' , ui.data.languages['_SEARCH']);


	/* -- Add click event to the estimate button -- */
	$(".estimate-button").on("click", function () {
		var confirmation = confirm(ui.data.languages['_ESTIMATE_CONFIRM']);
		if(confirmation == true) {

			$.ajax({
				url: "app/model/DatabaseInfo.php?estimatedbsize=1",
				success: function(result) {
					res =  ui.ParseJSON(result);
					if (res.Status == "Success") {
						$(".dbsize span").html(res.data); 						
					} else {
						$(".dbsize span").html('Failed');
						console.log(result)		        		
					}
				}
			});
		}

	});
}

cp.DataManager = function() {
	
	/* -- Load & update the view -- */
	cp.LoadView('app/views/DataManager.php');

	$("#maxManagerStorage").ionRangeSlider({
        min: 100,
        max: 50000,
        step: 100,
        postfix: " MB"        
    });
    
    function CheckPath() {
		$.ajax({
			url: "app/model/DataManager.php?checkpath=" + $(".datadir input").val(),
			success: function(result) {
				res =  ui.ParseJSON(result);
				if (res.Status == "Success") {
					$(".datadir i").css("color", "green");
					$(".datadir").attr("title", "");					
					$(".datadir i").switchClass("fa-exclamation-triangle", "fa-check",0);
				} else {
					$(".datadir i").css("color", "red");
					$(".datadir").attr("title", ui.data.languages["_PATH_NOT_WRITEABLE"]);
					$(".datadir i").switchClass("fa-check","fa-exclamation-triangle",0);
				}
			}
		});
	}

	CheckPath();

	/* -- Check the path on every keystroke-- */
	$(".datadir input").on("keyup", function() {
		CheckPath();
	});

	/* -- Add click event to the save button-- */
	$("#datamanform button").on("click", function(e) {
		e.preventDefault();

	    fmt = new FormData(document.getElementById("datamanform"));
	    
	    $.ajax({
			url: "app/model/DataManager.php?saveDataManagerSettings=1",
			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 ) {        	
        	res =  ui.ParseJSON(data);
        	ui.Callout(res);				
        });
	});	
}

cp.ChangeUploadDirectory = function() {
	
	/* -- Load & update the view -- */
	cp.LoadView('app/views/ChangeUploadDirectory.php');
	$(".upload_warning").hide();

	function CheckPath() {
		$.ajax({
			url: "app/model/ChangeUploadDirectory.php?check_upload_dir="+$("#upload_dir").val(),
			success: function(result) {
				res =  ui.ParseJSON(result);
				if (res.Status == "Success") {
					$(".upload_warning").hide();
					$(".uploaddir i").css("color", "green");
					$(".uploaddir").attr("title", res.Message);
					$(".uploaddir i").removeAttr("class");
					$(".uploaddir i").attr("class", "fa fa-check");
					$(".uploadbutton").switchClass("btn-danger", "btn-primary");					
					
				} else if (res.Status == "Warning") {
					$(".upload_warning").show();
					$(".uploaddir i").css("color", "red");
					$(".uploaddir").attr("title", res.Message);
					$(".uploaddir i").removeAttr("class");
					$(".uploaddir i").attr("class", "fa fa-check");
					$(".uploadbutton").switchClass("btn-danger", "btn-primary");
					
				} else if (res.Type!==undefined) {
					$(".upload_warning").hide();
					$(".uploaddir i").css("color", "red");
					$(".uploaddir").attr("title", res.Message);
					$(".uploaddir i").removeAttr("class");
					$(".uploaddir i").attr("class", "fa fa-lock");
					$(".uploadbutton").switchClass("btn-primary", "btn-danger");					
					
				} else {
					$(".upload_warning").hide();
					$(".uploaddir i").css("color", "red");
					$(".uploaddir").attr("title", res.Message);
					$(".uploaddir i").removeAttr("class");
					$(".uploaddir i").attr("class", "fa fa-exclamation-triangle");
					$(".uploadbutton").switchClass("btn-primary", "btn-danger");				
					
				}
			}
		});
	}

	CheckPath();

	/* -- Check the path on every keystroke-- */
	$(".uploaddir input").on("keyup", function() {
		CheckPath();
	});

	/* -- Add click event to the save button-- */
	$(".uploadbutton").on("click", function(e) {
		e.preventDefault();

	    $.ajax({
			url: "app/model/ChangeUploadDirectory.php?change_upload_dir="+$("#upload_dir").val(),
			success: function(result) {
				res =  ui.ParseJSON(result);
				ui.Callout(res);
			}
		});
	});
}

cp.UrlCaseSensitivity = function() {
	
	function UpdateView(status) {
		cp.UpdateToggleButtons(status,"urlcase");	
	}

	function Toggle(current) {
		$.ajax({
			url: "app/model/UrlCaseSensitivity.php?toggle=1",
			success: function(result) {
				res =  ui.ParseJSON(result);
				ui.Callout(res);
				if (res.Status != "Success") {					
					//it failed, reset the button 
        			UpdateView(current);
				}
			}
		});
	}

	/* -- Load the view -- */
	cp.LoadView('app/views/UrlCaseSensitivity.php');

	/* -- Update the view -- */
	$.ajax({
		url: "app/model/UrlCaseSensitivity.php",
		success: function(result) {
			res =  ui.ParseJSON(result);
			UpdateView(res.Status);
		}
	});

	/* -- Add click event to the buttons -- */
	$(".toggle button").on("click", function(e) {
		if ($(this).hasClass("enable_this")) {			
			UpdateView("Enabled");
			Toggle("Disabled");

		} else {			
			UpdateView("Disabled");
			Toggle("Enabled");

		}
	});
}


cp.SetupSubscriptions = function() {
	/* -- Load & update the view -- */
	cp.LoadView('app/views/SetupSubscriptions.php');
	$.getScript( "app/controller/SetupSubscriptions.min.js");
}

cp.ChangeAffiliateID = function() {
	
	/* -- Load & update the view -- */
	cp.LoadView('app/views/ChangeAffiliateID.php');

	$(".joinaffiliate").on("click", function(e) {
		window.open("https://store.logaholic.com/index.php?route=affiliate/login", "_blank");
	});

	/* -- Add click event to the save button-- */
	$( ".changeidbutton" ).on("click", function() { 
        $.ajax({
           	type: "POST",
           	url: "app/model/ChangeAffiliateID.php",
           	data: "new_affiliate_id="+document.getElementById("new_affiliate_id").value,
           	success: function(result){
            	res =  ui.ParseJSON(result);
				ui.Callout(res);
           }
         });
         return false;
    });
}

cp.ClusterManager = function() {	

	/* -- Load & update the view -- */
	cp.LoadView('app/views/ClusterManager.php');

	function CheckPath() {
		clearTimeout(checktimer);
		checktimer = setTimeout(function() {
			$.ajax({
				url: "app/model/ClusterManager.php?checkapipath=" + $("#cloudapipath").val(),
				success: function(result) {
					res =  ui.ParseJSON(result);
					if (res.Status == "Success") {
						$(".cloudapipath i").css("color", "green");
						$(".cloudapipath").attr("title", res.Message);					
						$(".cloudapipath i").switchClass("fa-exclamation-triangle", "fa-check",0);
						$(".btn-primary.installbutton").removeClass("disabled");
						// file is abvailable to disable the download button
						$(".downloadbutton").fadeOut();

						if (res.Installed==1) {
							// if we are already installed, switch to an uninstall button instead
							$(".btn-primary.installbutton").hide();
							$(".btn-danger.uninstallbutton").show();
						}

					} else {
						$(".cloudapipath i").css("color", "red");
						$(".cloudapipath").attr("title", res.Message);
						$(".cloudapipath i").switchClass("fa-check","fa-exclamation-triangle",0);
								        		
					}
				}
			});
		}, 500);
	}

	CheckPath();

	/* -- Check the path on every keystroke-- */
	$("#cloudapipath").on("keyup blur change mouseout", function() {
		CheckPath();
	});

	/* -- Add click event to the save button-- */
	$( ".btn-primary.installbutton" ).on("click", function() { 
        $.ajax({
           	type: "POST",
           	url: "app/model/ClusterManager.php",
           	data: "cloudapipath="+document.getElementById("cloudapipath").value,
           	success: function(result){
           		res =  ui.ParseJSON(result);
            	ui.Callout(res);
           }
         });
         return false;
    });

    $(".uninstallbutton").on("click", function() {
    	$.ajax({
    		type: "POST",
    		url: "app/model/ClusterManager.php",
    		data: "uninstall=1",
    		success: function(result) {
    			res =  ui.ParseJSON(result);
				ui.Callout(res);
				if (res.Status == "Success") {
					// if we've uninstalled, make sure to reset the ui to that state too
					$("#cloudapipath").val("");
					$(".btn-primary.installbutton").addClass("disabled");
					$(".btn-primary.installbutton").show();
					$(".btn-danger.uninstallbutton").hide();
				}
    		}
    	});
    	return false;
    });
}

cp.Installation = function() {
	document.location.href="install.php";
}

cp.UpdateLogaholic = function() {
	
	/* -- Load & update the view -- */
	cp.LoadView('app/views/UpdateLogaholic.php');

	$.getScript("https://updates.logaholic.com/echocurver.php", function(data) {
		// hier  moeten we nog wat leuks mee doen
		// console.log(logaholic_latest_version);
	});
		
	
	$(".backupbutton").on("click", function() {
		
		var btn = $(this);
    	btn.button('loading');

    	$.ajax({
    		type: "POST",
    		url: "app/model/UpdateLogaholic.php",
    		data: "backup=1",
    		success: function(result) {
    			btn.button('reset');    			
    			res =  ui.ParseJSON(result);
				ui.Callout(res);
				if (res.Status == "Success") {
					
					
				}
    		}
    	});
    	return false;
    });

    $(".removepreviousbackups").on("click", function() {
    	$.ajax({
    		type: "POST",
    		url: "app/model/UpdateLogaholic.php",
    		data: "removepreviousbackups=1",
    		success: function(result) {
    			//console.log(result);
    			res =  ui.ParseJSON(result);
				ui.Callout(res);
				if (res.Status == "Success") {
					
					
				}
    		}
    	});
    	return false;
    });

}

cp.GetLicense = function() {
	
	/* -- Load & update the view -- */
	cp.LoadView('app/views/GetLicense.php');
	
	if (ui.data.ss.type == "server") {
		ui.ProLicenseInfo();
	} else if (ui.data.hl == false) {
		$(".license_info").show();
	}

	// step 1: fill in the form, click the button
	$(".getlicensebutton").on("click", function(e) {
		e.preventDefault();

		// validate the form
		$(".getlicense .form-group").removeClass("has-error");

		if (!ValidateEmail( $(".getlicense input[name='e']").val() )) {
			$(".getlicense input[name='e']").parents(".form-group").first().addClass("has-error");
			return;
		}
		
		//submit the form
		var fd = new FormData(document.getElementById("getlicenseform"));
		$.ajax({
			url: "//software.logaholic.com/install/makelicensev6.php",
			type: "POST",
			processData: false,
            contentType: false,
            data: fd,
            success: function(result) {
            	res = ui.ParseJSON(result);
            	if (res.Status=="Success") {
            		$(".getlicense .box-body").html(res.Message); 
            		$(".response .callout").hide();           		
            	} else {
            		ui.Callout(res);
            		return;
			    }


            	// step 2: choose the order for this license
            	//$(".getlicense .box-body").html(result);
            	
				$(".getlicense .box-body .licenselink").on("click", function(){
					oid = $(this).attr("data-orderid");
					fd.append('forceorderid', oid);
					$.ajax({
						url: "//software.logaholic.com/install/makelicensev6.php",
						type: "POST",
						processData: false,
			            contentType: false,
			            data: fd,
			            success: function(result) {

			            	// step 3: receive and save the license
			            	res = ui.ParseJSON(result);

			            	if (res.Status=="Success") {
			            		$(".getlicense .box-body").html(res.Message + "<hr>");
			            		SaveLicense(res.license);
			            	} else {
			            		$(".getlicense .box-body").html(result);
			            	}
			            } 

					});

				});
            } 

		});


	});
	
	function SaveLicense(license) {
		$.ajax({
			url: "app/model/GetLicense.php",
			data: "license="+license,
			type: "POST",
			success: function(result) {

				$(".getlicense .box-body").append(result);
				$(".licenseinfo .box-body").hide();
				$(".licenseinfo .box-body").load("app/model/GetLicense.php");
				$(".licenseinfo .box-body").fadeIn();
			}
		});

	}
	
}

cp.UninstallLogaholic = function() {
	
	/* -- Load & update the view -- */
	cp.LoadView('app/views/UninstallLogaholic.php');

	$(".uninstall").on("click", function() {
		
		var confirmation = confirm(ui.data.languages['_LAST_CHANCE_TO_CANCEL']);
		if(confirmation == true) {
			$.ajax({
				url: "app/model/UninstallLogaholic.php?uninstall=confirm",
				success: function(result) {
					res =  ui.ParseJSON(result);
					ui.Callout(res);
					if (res.Status == "Success") {
						//$(".callout-success").fadeOut(5000);
						$(".sidebar-form").toggle("explode", 1000);
						$(".sidebar-menu").toggle("explode", 1500);
						$(".navbar-right").toggle("explode", 2000);
						$(".btn.btn-danger.uninstall").toggle("explode", 2000);
						$(".alert-danger").toggle("explode", 3000);
						$(".content-header").toggle("explode", 1500);
						$(".callout-success").toggle("explode", 2000);
						$(".uninstall .box-body ol li:first").fadeOut(4000);												
					}
				}
			});

		}
		return false;
	});
    

}