

$(document).ready(function(){
	var request_url = "app/model/Profile.php?conf="+conf;
	if(conf == 'newcnf'){
		var request_url = "app/model/Profile.php?conf="+conf + "&new=1";
	}

	// load the data
	$.ajax({
		url: request_url,
		success: function(result) {
			res = ui.ParseJSON(result);
			ui.Load( res );
			p.Load( res );
		}
	});


});

var checktimer = 0;
var conf = GetURLParameter('conf');
var p = {};

/* -- Load inserts data into the page and adds controls on elements -- */	
p.Load = function (data){
	if(data.Status != 'Success'){
		$(".sidebar-toggle").click();
		ui.SystemError(data);
		return;
	}

	p.data = data;

	/* Set a default for this variable because in some cases it's missing.. check later why that is.. (first time create profile after install)*/
	if(p.data.session.metadata == undefined){
		p.data.session.metadata = {};
	}
	
	/* In this function all the permissions will be checked and if it is needed it removes elements.. */
	p.PermissionChecks();

	/* 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 page name -- */
	if (p.data.new==1) {		
		$(".confname").html(ui.data.languages['_CREATE_NEW_PROFILE']);
		$(".pagename").html("");
	} else {				
		$(".confname").html(ui.data.languages['_EDIT_PROFILE']);
		$(".pagename").html("<strong>"+data.profile.profilename+ "</strong> ("+data.profile.confdomain+")");
		
	}

	$(".locationname").html(ui.data.languages['_EDIT_PROFILE']);
	$(".content-header").prepend($(".saveprofile"));

	$("#profile-view").on("click", function(e){
		window.location.href = "dashboard.php?conf=" + data.profile.profilename;
	});

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

	/* -- add menu handing -- */
	$(".menu-report").on("click", function(e){
		e.preventDefault();
		
		//make sure some extra stuff is closed
		$(".loglist, .exportedfiles, .progressListener, .datamLogsList").hide();
		
		$(".active_menu_item").not(this).removeClass("active_menu_item");
		$(this).addClass("active_menu_item");

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

	});

	/* -- load the data into the form -- */
	p.PopulateForm();
	
	// display the js tracking codes
	$("#copy_tracking_div").html(p.data.codespace);
	$("#copy_tracking_div2").html(p.data.codespace2);
	$("#copy_exit_tracking_div").html(p.data.exitclicks);
	$("#copy_inpage_div").html(p.data.inpage);
	$("#copy_tracking_div").on("click",function(){ p.SelectText("copy_tracking_div"); });
	$("#copy_tracking_div2").on("click",function(){ p.SelectText("copy_tracking_div2"); });
	$("#copy_exit_tracking_div").on("click",function(){ p.SelectText("copy_exit_tracking_div"); });
	$("#copy_inpage_div").on("click",function(){ p.SelectText("copy_inpage_div"); });


	/* -- if something changes, show the save button -- */
	$("form#editprofile_form :input").on("change keyup", function(e) {
		$(".saveprofile").fadeIn();		
	});

	$(".saveprofile .btn-danger").on("click", function(e) {
		p.SaveForm();
	});	

	$(".saveprofile .btn-default").on("click", function(e) {
		window.location.href = window.location.href;
	});	

	$(".form-group").on("mouseover", function(e) {		
		var txt = $(this).attr("data-help");
		var title = $(this).find("label:first").html();
		p.UpdateHelp(title,txt);

	});

	/* -- Open the Profiles 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);
		if(data.menu_items[i] != undefined){
			$("[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 {
			$("#main-menu li:first a:first").click();
			p.ProfileInfo();
		}	
	} else if (ui.GetCookie("last_p_action")!=null) {
		
		i = ui.GetCookie("last_p_action");
		if(data.menu_items[i] != undefined){
			$("[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 {
			$("#main-menu li:first a:first").click();
			p.ProfileInfo();
		}		
	} else {	
		$("#main-menu li:first a:first").click();
		p.ProfileInfo();
	}
	// if we are making a new profile,set this here so it gets passed on when saving the form
	if (p.data.new==1) {
		data.profile.profilename = "newcnf&new=1";
	}

	// prevent enter key from submitting the form, cus that won't work brotha
	$("#editprofile_form").keydown(function(event){
	    if(event.keyCode == 13) {
	      event.preventDefault();
	      return false;
	    }
  	});

  	$(".helptxt").on("click",".link-to-exitclicks", function(e){
  		e.preventDefault();
  		window.location.href = "dashboard.php?conf=" + data.profile.profilename + "&label=_EXIT_CLICKS"; 
  	});

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

}

/* In this function all the permissions will be checked and if it is needed it removes elements.. */
p.PermissionChecks = function(){
	/* we are admin so return */
	if(parseInt(p.data.session.userinfo.isAdmin) == 1){
		return true;
	}

	/* Check if we need to remove data collecting methods */
	var remove_modes = [];
	for (var i = 0; i <= 3; i++) {
		if(p.data.session.metadata["trackermode_" + i] != undefined && p.data.session.metadata["trackermode_" + i] == 0){
			remove_modes.push("#trackermode option[value='"+ i +"']");
		}
	}
	/* If all collection methods are disabled for a user then disable all fields and show the current trackermode */
	if(remove_modes.length == 4){
		$("#trackermode option").not("#trackermode option[value='"+ p.data.profile.trackermode +"']").remove();
		$(".datacollection .form-control, #recursive").attr("disabled","disabled");
	} else {
		/* If there is an option left to use for a user then remove the others that are not available */ 
		$( remove_modes.join(", ") ).remove(); 

	}

	/* The user can only change the profilename if it can add profiles */
	if(parseInt(p.data.session.userinfo.accessAddProfile) != 1){
		$("#newconfname").attr("disabled","disabled");
		//$("#statusactivated").attr("disabled","disabled");
		$("#confdomain").attr("disabled","disabled");
	}

	if(parseInt(p.data.session.userinfo.accessUpdateLogs) != 1){
		$(".updateoptions .box-body").html(ui.data.languages['_HANDLING_BY_ADMIN'] + ".<div style='clear:both'><br></div>")
	}


}

p.SaveForm = function() {
	
	var fd = new FormData(document.getElementById("editprofile_form"));

    $.ajax({
		url: "app/model/EditProfile.php?conf="+p.data.profile.profilename+"&saveprofile=1",
		type: 'POST',
		data: fd,
		processData: false,  // tell jQuery not to process the data
        contentType: false,   // tell jQuery not to set contentType
		success: function(result) {
		    result = ui.ParseJSON(result);
		    ui.Callout(result);
		    if (result.Status == "Success") {
		    	//reload the data		    	

		    	if (result.NewName != p.data.profile.profilename) {
		    		fade_timer = setTimeout(function() {
						window.location.href = "profile.php?conf=" + result.NewName;
   					}, 1000);		    		
		    	} else {
			    	$.ajax({
						url: "app/model/Profile.php?conf="+result.NewName,
						success: function(result) {
							p.data = ui.ParseJSON(result);
							$(".saveprofile").hide();
							fade_timer = setTimeout(function() {
								$(".response .callout").fadeOut('fast');
   						 	}, 1000);
   						 	if (p.data.new == 1) {
   						 		Intercom("saved-new-profile");
   						 	}
							
						}
					});
		    	}
		    }

		}
   });             	
}

/* -- This function is used to load additional views -- */
p.ShowView = function(view) {

	/* -- Clean the content area -- */
	$(".formarea .box:not([rel="+view+"])").hide(0, function() {
		/* -- Load the view -- */
		$("[rel="+view+"]").fadeIn();	
	});
	p.UpdateHelp("Info", $("[rel="+view+"]").attr("data-help"));
	$(".response .callout").hide();	
}

p.UpdateHelp = function(title,txt) {

	if (txt==undefined) {
		txt =  ui.data.languages['_MOVE_YOUR_MOUSE_FOR_HELP'];
		title = ui.data.languages['_HELP'];
	}
	if (title == $(".helptxt .box-title span").html()) {
		return;
	}	

	$(".helptxt .box-body").fadeOut(100, function(){
		$(".helptxt .box-title span").html(title);
		$(".helptxt .box-body").html(txt);
		$(".helptxt .box-body").fadeIn();
	});
}

p.SelectText = function (element, win) {

	var el = document.getElementById(element);
	win = win || window;
    var doc = win.document, sel, range;
    if (win.getSelection && doc.createRange) {
        sel = win.getSelection();
        range = doc.createRange();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (doc.body.createTextRange) {
        range = doc.body.createTextRange();
        range.moveToElementText(el);
        range.select();
    }
}

p.PopulateForm = function() {
	
	var trackermode_displayed = false;

	$.each(p.data.profile, function(k, v) {
		
		// the form element for profilename is called newconfname in the form
		if (k == "profilename") { k = "newconfname";}
		
		// change view according to trackermode setting
		if (k == "trackermode") {
			if(p.data.session.metadata['trackermode_' + v] == undefined || p.data.session.metadata['trackermode_' + v] == 1){				
				trackermode_displayed = true;
				$(".trackersub").hide();
				$(".trackermode"+v).show();
				if (v == 0 || v == 2) {
					$(".misc_lf_options").appendTo(".trackermode"+v);			
				}
				if (v == 3) {
					p.UploadFiles();
					$(".lf_basics").appendTo(".trackermode"+v);
					$(".misc_lf_options").appendTo(".trackermode"+v);
					$("#logfilefullpath").val(p.data.upload_dir);
					$("#logfilefullpath").prop('disabled', true);
					$("#recursive").prop('disabled', true);
					$(".loglist").fadeIn();	
				}				
			}
		}		

		// these radio buttons require special handling
		if (k == "urlparamfiltermode") {
			$("input:radio[name='urlparamfiltermode']").filter('[value='+v+']').prop('checked', true);
			return;
		}
		
		if(k == "recursive"){
			if(parseInt(v) === 1){
				$("#recursive").prop('checked', true);
			} else{
				$("#recursive").prop('checked', false);
			}
			return;
		}

		if (k=="dateFormat") {
			$.each(v, function(key,vl) {
				$("[name='"+key+"']").val(vl);			
			});
		}

		// importantparams is an array of 3 elements, make it
		if (k == "importantURLParams") {
			
			$.each(v, function(key,vl) {
				//clone the empty one and fill in the details
				g = $(".dynpagegroup:first").clone(true);
				g.find("[name='paramid[]']").val(vl.paramid);
				g.find("[name='paramurl[]']").val(vl.filename);
				g.find("[name='paramnames[]']").val(vl.importantparams);
				//add it to the ui
				$(".form-group.dynpages").append(g);
			});
			// move the empty one to the last position
			$(".form-group.dynpages").append( $(".dynpagegroup:first") );
		}

		if (k == "visitoridentmethod") {				
			if (v==3 && $("[name='trackermode']").val() != 1) {			
				$(".copy_tracking_div2").show();
			}
			if (v==4) {
				$("[name='vidm_custom_cookie']").show();
			}
		}

		//if we have a form element with this name, set the value
		if ($("[name='"+k+"']").length > 0) {
			$("[name='"+k+"']").val(v);			
		}

	});
	
	/* If the profiles' tracker mode is not allowed by the user, display the correct one */
	if(!trackermode_displayed){
		tracker_modes = [0,1,2,3];
		$.each(tracker_modes, function(k,v){ 
			if(p.data.session.metadata['trackermode_' + v] != undefined && p.data.session.metadata['trackermode_' + v] == 1){
				$(".trackersub").hide();
				$(".trackermode"+v).show();
				if (v == 0 || v == 2) {
					$(".misc_lf_options").appendTo(".trackermode"+v);			
				}
				if (v == 3) {
					p.UploadFiles();
					$(".lf_basics").appendTo(".trackermode"+v);
					$(".misc_lf_options").appendTo(".trackermode"+v);
					$("#logfilefullpath").val(p.data.upload_dir);
					$("#logfilefullpath").prop('disabled', true);
					$("#recursive").prop('disabled', true);
					$(".loglist").fadeIn();	

				}

				trackermode_displayed = true;

			}
		});
	}

	/* If it is still not shown show the default 0 */
	if(!trackermode_displayed){
		$(".trackermode"+ p.data.profile.trackermode ).show(); 
		if (p.data.profile.trackermode == 0 || p.data.profile.trackermode == 2) {
			$(".misc_lf_options").appendTo(".trackermode" + p.data.profile.trackermode);
		}
		if (p.data.profile.trackermode == 3) {
			//console.log('hallo');
			//$.getScript("app/controller/Loghint.min.js")
			p.UploadFiles();
			$(".lf_basics").appendTo(".trackermode"+p.data.profile.trackermode);
			$(".misc_lf_options").appendTo(".trackermode"+p.data.profile.trackermode);
			$("#logfilefullpath").val(p.data.upload_dir);
			$("#logfilefullpath").prop('disabled', true);
			$("#recursive").prop('disabled', true);
			$(".loglist").fadeIn();	
			//showHint(p.data.upload_dir);		
		}
	}


	//populate the kpi picker
	tf = $("#targetfiles").val();
	
	if(tf != null && tf.length > 0) {
		var targetfiles = tf.split(",");
		targetfiles = p.CheckKPIlimit(targetfiles);
		$.each(targetfiles, function(k,v){
			$(".kpi-box .kpi-list").append("<li class='users-kpi bg-success'><span class='name'>"+ v.trim() +"</span><i class='fa fa-times'></i></li>");
		});
		$(".kpi-box .kpi-list").append($(".kpi-list .input"));
	}

}

p.noSpecialChars = function(e) {

	var keynum
	var iChars = " !@#$%^&*()+=-[]\\\';,/{}|\":<>?"; // Invalid characters.
	if	(window.event) { keynum = e.keyCode; } // IE
	else if (e.which) { keynum = e.which; } // Netscape/Firefox/Opera
	str = String.fromCharCode(keynum);
	return (iChars.indexOf(str) == -1);
}
// if we have a kpi limit, enforce it
p.CheckKPIlimit = function (targetfiles) {
	//return targetfiles;
	if (p.data.kpilimit.length > 0) {
		if(targetfiles.length > p.data.kpilimit) {
			$(".callout-danger-template").hide();
			$(".callout-success-template").hide();
			mes = ui.data.languages['_KPI_LIMIT_ERROR'];
			mes = mes.replace("%X%", p.data.kpilimit);
			$(".callout-danger-template h4").html(mes);
			$(".callout-danger-template").fadeIn();			
			
			//shorten the list to the kpi limit
			newtargets = [];
			i = 0;
			while (i < p.data.kpilimit) {
				newtargets.push(targetfiles[i].trim());					
				i++;
			}
			
			return newtargets;
		}
	}
	return targetfiles;
}

p.ProfileInfo = function() {
	p.ShowView("_PROFILE_INFO");

	$("#newconfname").on("keyup", function() {
		if ($("#newconfname").val().substr(0,1) == ".") {
			//filter with dots only if it's the first char
			$("#newconfname").val( $("#newconfname").val().substr(1) );
		}
		
	});	

	$("#confdomain").on("keyup", function() {		
    	var re = /^(?=.{1,254}$)((?=[a-z0-9-]{1,63}\.)(xn--+)?[a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,63}$/i;
    	if (re.test($(this).val())===false) {
    		$(this).closest(".form-group").switchClass("has-success", "has-error");
    		$(this).closest(".form-group").find("i").switchClass("fa-check", "fa-exclamation-triangle");
    		
    	} else {
    		$(this).closest(".form-group").switchClass("has-error", "has-success");
    		$(this).closest(".form-group").find("i").switchClass("fa-exclamation-triangle", "fa-check");
    		
    	}
	});

}

p.DataCollection = function() {
	$.getScript("app/controller/Loghint.min.js");
	p.ShowView("_DATA_COLLECTION");	
	
	// update the log file hint
	if (p.DataCollection.loaded==undefined) {

		$("#logfilefullpath, #ftpfullpath").on("click", function(e) {					
			$("#txtHint").show();
			$(".loglist").fadeIn();
			showHint(this.value);		
		});
		
		$("#logfilefullpath, #ftpfullpath").on("keyup", function(e) {		
			showHint(this.value);
		});
		$("#splitfilter, #splitfilternegative").on("keyup", function(e) {		
			showHint();
		});
		$("#ftpserver, #ftpuser, #ftppasswd, #ftpport, #ftpmode").on("focus blur", function(e) {
			$("#txtHint").show();	
			$(".loglist").fadeIn();				
			showHint();
		});

		$("#txtHint").on("click", ".loghint_file", function() {
			if ($("#trackermode").val() == 2) {
				$("#ftpfullpath").val($(this).attr("data-fullfile"));
			} else {
				$("#logfilefullpath").val($(this).attr("data-fullfile"));
			}
			showHint($(this).attr("data-fullfile"));			
		});
		
		// when trackermode changes, we need to  change the view
		$("#trackermode").on("change", function(e) {

			$(".trackersub").hide();

			//first put everything back where it belongs
			$("#logfilefullpath").prop('disabled', false);
			$("#recursive").prop('disabled', false);
			$(".lf_basics").appendTo(".trackermode0");
			$(".misc_lf_options").appendTo(".trackermode0");

			//now move it to the selected position
			if (this.value == 1) {
				$(".loglist").fadeOut();

				if(p.data.new == 1){
					var c = confirm(ui.data.languages['_SAVE_BEFORE_TRACKER']);
					if(c){
						p.SaveForm();
					}
				}
			}
			if (this.value == 2) {
				$(".misc_lf_options").appendTo(".trackermode"+this.value);	

			}
			if (this.value == 3) {
				p.UploadFiles();
				$(".lf_basics").appendTo(".trackermode"+this.value);
				$(".misc_lf_options").appendTo(".trackermode"+this.value);
				$("#logfilefullpath").val(p.data.upload_dir);
				$("#logfilefullpath").prop('disabled', true);
				$("#recursive").prop('disabled', true);
				$(".loglist").fadeIn();
				showHint(p.data.upload_dir);
			}			
			$(".trackermode"+this.value).fadeIn('fast');
				
		});

		
		if(p.data.new == 1) {
			$("#trackermode").val($("#trackermode option:first").val());
			p.data.new = 0; // overrule so we avoid the alert
			$( "#trackermode").trigger("change");
			p.data.new = 1; // set it back
			
			Intercom("update");
		}		

		p.DataCollection.loaded = true;		
	}

	
}

p.UploadFiles = function() {
	$.ajax({
		url: "app/model/Upload.php?conf="+p.data.profile.profilename,
		
		success: function(result) {
		    //display the html output and attach listners
		    $(".trackermode3 .uploadarea").html(result);
		    
		    $(".helptxt .box-body").html("");
			$(".helptxt .box-body").html($(".trackermode3 .uploadarea .help"));
		}
	});
}

p.DataFilters = function() {
	
	p.ShowView("_DATA_FILTERS");

	if (p.DataFilters.loaded==undefined) {

		//validate the ipnumbers input
		var skipiptimeout;
		$("textarea[name='skipips']").keyup(function(){
			var skipip_field = $(this);
			if(skipiptimeout !== undefined){
				clearTimeout(skipiptimeout);
			}
			skipiptimeout = setTimeout(function(){
				$.ajax({
					type: 'POST',
					url: "includes/check_skipipnumbers.php",
					data: {
					"q" : skipip_field.val()
					},
					success: function(result) {
						if(parseInt(result) != 1){
							$(".skip_ipnumbers_errors").html(result);
						} else {
							$(".skip_ipnumbers_errors").html('');
						}
					}
				});
			},1000); 

		});

		p.DataFilters.loaded = true;
	}
}

p.VisitorID = function() {
	p.ShowView("_VISITOR_IDENTIFICATION");
	
	if (p.VisitorID.loaded == undefined) {

		// change the view if Cookie tracking is selected
		$("[name='visitoridentmethod']").on("change", function(e) {		
			if (this.value == 3) {
				$("[name='vidm_custom_cookie']").hide();
				$(".copy_tracking_div2").fadeIn('fast');
			} else if (this.value == 4) {
				$(".copy_tracking_div2").hide();
				$("[name='vidm_custom_cookie']").fadeIn('fast');
			} else {
				$(".copy_tracking_div2").hide();
				$("[name='vidm_custom_cookie']").hide();
			}
		});

		p.VisitorID.loaded = true;
	}
}

p.KPIs = function() {

	p.ShowView("_KPI");


	if (p.KPIs.loaded==undefined) {

		$(".kpi-box .search").autocomplete({ source: function( request, response ) {
				$.get("app/model/EditProfile.php?conf="+p.data.profile.profilename, {
		            qurl: request.term
		        }, function (data) {
		        	data = ui.ParseJSON(data);
		        	if(data.Status != undefined && data.Status == "Success"){       	
		            	response(data.Data);
		            } else {
		            	$(".kpi-box .search").val('');
		            }
		        });
			},
			minLength : 0
		}).bind('click', function(){ $(this).autocomplete("search"); } );

		$(".kpi-box .search").on("autocompleteclose", function(){
			
			var v = $(".kpi-box .search").val();
			if(v == ""){
				return;
			}
			$(".kpi-box .kpi-list").append("<li class='users-kpi bg-success'><span class='name'>"+ v +"</span><i class='fa fa-times'></i></li>");
			$(".kpi-box .kpi-list").append($(".kpi-list .input"));

			$(".kpi-box .search").attr("value","").focus();			
			$(".kpi-box .search").val('');
			
			UpdateField();
		});

		$(".kpi-list").on("click", ".users-kpi i", function(){
			var item = $(this).parent("li");		
			item.fadeOut(300, function() {
				item.remove();
				UpdateField();
			});
			//make sure to show the save button
			$(".saveprofile").fadeIn();
		});

		p.KPIs.loaded = true;
	}

	// regenerate the comma seperated list when anything changes
	function UpdateField() {
		targets = [];
		$(".users-kpi").each( function(){
			targets.push( $(this).find(".name").html() );
		});
		targets = p.CheckKPIlimit(targets);
		targets = targets.join(",");
		$("#targetfiles").val(targets);
	}

		
}

p.Feeds = function() {
	p.ShowView("_FEEDS");
}

p.DynamicPages = function() {
	p.ShowView("_DYNAMIC_PAGES");

	if (p.DynamicPages.loaded==undefined) {
		
		$(".adddynp").on("click", function(e) {
			e.preventDefault();						
			c = $(this).closest(".dynpagegroup").clone(true);
			c.find("[name='paramid[]']").val("");
			c.find("[name='paramurl[]']").val("");
			c.find("[name='paramnames[]']").val("");
			$(".form-group.dynpages").append(c);

		});

		$(".removedynp").on("click", function(e) {
			e.preventDefault();
			// remove or reset the div if it's the only one
			if ($(".dynpagegroup").length > 1) {
				$(this).closest(".dynpagegroup").remove();
			} else {
				c = $(this).closest(".dynpagegroup");
				c.find("[name='paramid[]']").val("");
				c.find("[name='paramurl[]']").val("");
				c.find("[name='paramnames[]']").val("");
			}
		});

		p.DynamicPages.loaded = true;
	}
}

p.ExitClicks = function() {

	p.ShowView("_EXIT_CLICKS");
}

p.CustomEvents =function () {
	p.ShowView("_CUSTOM_EVENTS");	
}

p.DateTime = function () {
	p.ShowView("_DATE_TIME");

	function UpdatePreview() {    	
        $.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(result);
			}
       });             
   	}	
   	UpdatePreview();

   	if (p.DateTime.loaded==undefined) {

	   	$(".datetime select").change( function() {
	    	UpdatePreview();
	    });

	    $(".restore-default-date-format-settings").on("click", function(e){    	
			e.preventDefault();			
	        $(".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();        
	    });

	    p.DateTime.loaded = true;
	}
}

p.EmailAlerts = function() {
	$(".response .callout").hide();
	p.ShowView("_EMAIL_ALERTS");

	$.ajax({
		url: "app/model/EditProfile.php?conf="+p.data.profile.profilename,
		type: 'POST', data: {emailalerts : 1},
		success: function(result) {
		    //display the html output and attach listners
		    HandlePage(result);

		}
	});

	function HandlePage(result) {
		
		//add the content and update the view
	   	$(".emailalerts_managealert .box-body").empty();
		$(".emailalerts_managealert .box-body").html(result);
		$(".emailalerts_managealert .box-body h3").remove();
	    $(".helptxt .box-body").empty();
		$(".helptxt .box-body").html($(".warning.ui-state-highlight.ui-corner-all"));
		$(".emailalerts.createalert .box-body").html($("#emailalerts"));
		
		if($(".emailalerts_managealert .box-body").html().trim()!="") {			
			$(".emailalerts_managealert").show();
		}

		//add submit handling
	    $(".submitbut").on("click", function(e) {
			e.preventDefault();
			e.stopPropagation();

			if (ui.data.hl == false) {
				ui.LicenseUpgrade();
				return false;
			}

			SubmitForm();			
		});

		// delete button
		$("#alerttable a").on("click", function(e) {
			e.preventDefault();
			e.stopPropagation();
			params = $(this).attr("href");
			DeleteAlert(params);
		});

		$(".btn.send-alerts-now").on("click", function(e) {
			e.preventDefault();
			$.ajax({
				url: "app/model/EditProfile.php?conf="+p.data.profile.profilename,
				type: 'POST', data: {emailalerts : 1, testalerts : 1},
				success: function(result) {
				   	// display the html output and attach listners
		   			HandlePage(result);
				}
			});
		});

	    
	}

	function SubmitForm() { 

		if (validate('emailalerts','email')==false) {
			return false;
		}

		$("html, body").animate({ scrollTop: 0 }, "fast");

	    var fd = new FormData(document.getElementById("emailalerts"));

        $.ajax({
			url: "app/model/EditProfile.php?conf="+p.data.profile.profilename+"&emailalerts=1",
			type: 'POST',
			data: fd,
			processData: false,  // tell jQuery not to process the data
            contentType: false,   // tell jQuery not to set contentType
			success: function(result) {
			    HandlePage(result);
			    ui.Callout({ "Status" : "Success", "Message" : ui.data.languages['_ALERT_ADDED']} );

			}
       });             
   	}

	function DeleteAlert(params) { 
	    
        $.ajax({
			url: "app/model/EditProfile.php"+params+"&emailalerts=1",						
			success: function(result) {
			    HandlePage(result);
			    ui.Callout({ "Status" : "Error", "Message" : ui.data.languages['_ALERT_REMOVED'] } );
			}
       });             
   	}
   	  		    
}

p.InpageAnalytics = function() {
	p.ShowView("_INPAGE_ANALYTICS");

	if (p.InpageAnalytics.loaded==undefined) {

		$(".inpageanalytics .btn.activated").on("click", function(e){
			e.preventDefault();

			if (ui.data.hl == false) {
				ui.LicenseUpgrade();
				return false;
			}		
			
			window.open("https://"+p.data.profile.confdomain+"?activateinpage=1", "_blank");
		});
		$(".inpageanalytics .btn.deactivated").on("click", function(e){
			e.preventDefault();		
			window.open("https://"+p.data.profile.confdomain+"?activateinpage=0", "_blank");
		});

		p.InpageAnalytics.loaded = true;
	}
}

p.CustomReports = function() {
	p.ShowView("_CUSTOM_REPORTS");
}

p.Dashboards =function () {
	p.ShowView("_DASHBOARDS");

	if (p.Dashboards.loaded==undefined) {

		$(".dashboards .btn-primary").on("click", function(e){
			e.preventDefault();
			$.ajax({
				url: 'app/model/EditProfile.php',
				data: { 'conf' : p.data.profile.profilename, 'restoredefaultdashboard' : 1 },
				success: function(result) {
					result = ui.ParseJSON(result);
					ui.Callout(result);
				    
				}
	       });
		});

		$(".dashboards .btn-danger").on("click", function(e) {
			e.preventDefault();
			$.ajax({
				url: 'app/model/EditProfile.php',
				data: { 'conf' : p.data.profile.profilename, 'deletedashboards' : 1 },
				success: function(result) {
					result = ui.ParseJSON(result);
					ui.Callout(result);
				    
				}
	       });
		});

		p.Dashboards.loaded = true;
	}
}

p.DataManager = function() {
	p.ShowView("_DATAMANAGER_SETTINGS");

	if(p.DataManager.loaded == undefined){
		$.getScript("app/controller/DataManager.min.js");
		p.DataManager.loaded = true;	
	}

}

p.DatabaseInfo = function() {

	p.ShowView("_DATABASE_INFO");


	$.ajax({
		url: 'app/model/EditProfile.php',
		data: { 'conf' : p.data.profile.profilename, 'databaseinfo' : 1 },
		success: function(result) {
			result = ui.ParseJSON(result);
			if (result.Status == "Success") {
				$(".databaseinfo .dbinfotxt").html(result.info);					
				
				if (p.DatabaseInfo.loaded == true) {
					var table = $('#database_info_table').DataTable();
					table.clear().draw();
					table.rows.add(result.data).draw();
				} else {
					$('#database_info_table').dataTable( {
						"aaSorting": [],
						"filter": false,
						"paging": false,
				        "data": result.data,
				        "columns": [
				            { "title": "Table name" },
				            { "title": "Records" },
				            { "title": "Size in MB" }		            
				        ]
				    } );
				    p.DatabaseInfo.loaded = true;
				}

		    }
		}
   	});
}


p.DeleteData = function() {
	p.ShowView("_DELETE_DATA");
	
	if (p.DeleteData.loaded==undefined) {

		$('.deletedata .btn').on("click", function(e) { e.preventDefault();})
		
		$(".deletedata .delbutton").on("click", function() {

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

			var fd = new FormData(document.getElementById("delete_form"));

	        $.ajax({
				url: "app/model/EditProfile.php?conf="+p.data.profile.profilename+"&deletedatarange=1",
				type: 'POST',
				data: fd,
				processData: false,  // tell jQuery not to process the data
	            contentType: false,   // tell jQuery not to set contentType
				success: function(result) {
					btn.button('reset');
				    result = ui.ParseJSON(result);
				    ui.Callout(result);
				}
	       	}); 
		});


		$(".deletedata .deldatabasebut").on("click", function() {
			
			var btn = $(this);
    		btn.button('loading');

			$.ajax({
				url: "app/model/EditProfile.php?conf="+p.data.profile.profilename+"&deletedatabase=1",
				success: function(result) {
					btn.button('reset');
				    result = ui.ParseJSON(result);
				    ui.Callout(result);
				}
	       	}); 	
		});

		$(".deletedata .delprofilebut").on("click", function() {
			
			var btn = $(this);
    		btn.button('loading');

			$.ajax({
				url: "app/model/EditProfile.php?conf="+p.data.profile.profilename+"&deleteprofile=1",
				success: function(result) {
					btn.button('reset');
				    result = ui.ParseJSON(result);				    
				    if (result.Status == "Success") {
						$(".sidebar-form").toggle("explode", 1000);
						$(".sidebar-menu").toggle("explode", 1500);
						$(".navbar-right").toggle("explode", 2000);
						$(".content-header").toggle("explode", 1500);
						$("#the_grid").toggle("explode", 2500);
						$(".curprofile").remove();
						ui.Callout(result);
						
					}
				}
	       	}); 	
		});

		p.DeleteData.loaded = true;
	}
}

p.ExportProfile = function(){
	p.ShowView("_EXPORT_PROFILE_SETTINGS");
	if (p.ExportProfile.loaded==undefined) {
		$(".exportprofilesettings [name='conf']").val(p.data.profile.profilename);
		p.ExportProfile.loaded = true;
	}
}

p.ExportData = function() {
	p.ShowView("_EXPORT_DATA");

	if (p.ExportData.loaded==undefined) {
		$(".exportdata .exportbutton").on("click", function(e) {
			e.preventDefault();

			if (ui.data.hl == false) {
				ui.LicenseUpgrade();				
				return false;
			}

			$(".exportedfiles").show();
			$(".exportedfiles .fa-folder-open-o").switchClass("fa-folder-open-o", "fa-cog fa-spin");

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

    		if ( $.fn.dataTable.isDataTable( '#exportedfiles_table' ) ) {
    			$('#exportedfiles_table').DataTable().clear().draw();
    		} else {
				$('#exportedfiles_table').dataTable( {
					"aaSorting": [],
					"filter": false,
					"paging": false,
			        "data": [],
			        "columns": [
			            { "title": "File" },
			            { "title": "Size" }				            
			        ]
			    } );
			}			
		    ProgressStream( ui.data.languages['_EXPORTING_FILES'] ,btn);
		});

		$(".delete-exportedfiles").on("click", function(){
			var btn = $(this);
    		btn.button('loading');

			$.ajax({
				url: "app/model/EditProfile.php?conf="+p.data.profile.profilename+"&deleteexport=1",
				success: function(result) {
					btn.button('reset');
				    result = ui.ParseJSON(result);
				    ui.Callout(result);
				    $('#exportedfiles_table').DataTable().clear().draw();
				}
	       	}); 
		});

		p.ExportData.loaded = true;
	}


	function ProgressStream(header, btn){
		var from  = $(".exportform select[name='fday']").val() + "-" + 
			$(".exportform select[name='fmonth']").val() + "-" + 
			$(".exportform select[name='fyear']").val();

		var to  = $(".exportform select[name='tday']").val() + "-" + 
			$(".exportform select[name='tmonth']").val() + "-" + 
			$(".exportform select[name='tyear']").val();

		var mode = $(".exportform select[name='mode']").val();

		var url = "app/model/EditProfile.php?conf="+p.data.profile.profilename+"&export=1" + "&fromDate="+ from +"&toDate=" + to + "&mode=" + mode;
		
		var source = new EventSource(url);

		source.addEventListener('message', function (e) {
			
			d = ui.ParseJSON(e.data);
			
			if (d.Status != undefined) {
				ui.Callout(d);
				return;
			}

			// if we dont have a status, we are updating the table with files
			$('#exportedfiles_table').DataTable().row.add(d).draw();

			$(".exportedfiles .box-body").scrollTop($(".exportedfiles .box-body")[0].scrollHeight);

		}, false);

		source.addEventListener('error', function (e) {
		    source.close();
		    $('.active_update_country .progress').removeClass("progress-striped");
		    btn.button('reset');
		    $(".exportedfiles .fa-cog").removeClass("fa-spin");
		    $(".exportedfiles .fa-cog").switchClass("fa-cog", "fa-folder-open-o");
		}, false);
	}
}

p.Automation = function() {
	p.ShowView("_AUTOMATION");
	$(".pname").html(p.data.profile.profilename);
}


p.UpdateOptions = function() {
	p.ShowView("_UPDATE_OPTIONS");

	if (p.UpdateOptions.loaded==undefined) {

		$(".updateoptions .update_regular").on("click", function() {
			window.location.href = "update.php?conf=" + p.data.profile.profilename;
		});

		$(".updateoptions .update_force").on("click", function() {
			window.location.href = "update.php?conf=" + p.data.profile.profilename + "&force=true";
		});
		$(".updateoptions .read_progress_log").on("click", function() {
			window.location.href = "readupdateprogresslog.php?conf=" + p.data.profile.profilename;
		});

		$(".updateoptions .update_move").on("click", function() {
			var confirmation = confirm(ui.data.languages['_MOVE_TO_DONE_ASSURANCE']);
			if(confirmation == true) {
				window.location.href = "update.php?conf=" + p.data.profile.profilename + "&force=true&movedone=true";
			}
		});

		$(".updateoptions .update_country").on("click", function(e) {
			e.preventDefault();

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

			var fd = new FormData(document.getElementById("update_countries_form"));

			ProgressStream(ui.data.languages['_UPDATING_COUNTRIES'] + "...", btn);
		});

	}
	p.UpdateOptions.loaded = true;

	function ProgressStream(header, btn){

		$(".default_update_country").hide();
		$(".active_update_country").show();

		var from  = $("#update_countries_form select[name='fday']").val() + "-" + 
			$("#update_countries_form select[name='fmonth']").val() + "-" + 
			$("#update_countries_form select[name='fyear']").val();

		var to  = $("#update_countries_form select[name='tday']").val() + "-" + 
			$("#update_countries_form select[name='tmonth']").val() + "-" + 
			$("#update_countries_form select[name='tyear']").val();

		var url = "app/model/EditProfile.php?conf="+p.data.profile.profilename+"&update_country=1" + "&fromDate="+ from +"&toDate=" + to;
		

		var source = new EventSource(url);

		source.addEventListener('message', function (e) {
			if (isNaN(e.data)) {
				$(".update_country_message").html(e.data);
				return;
			}			
			$('.active_update_country .progress-bar').css('width', e.data+'%').attr('aria-valuenow', e.data);
			$('.active_update_country .complete_txt').html(e.data+ "% "+ ui.data.languages["_COMPLETE"]);	    

		}, false);

		source.addEventListener('error', function (e) {
		    source.close();
		    $('.active_update_country .progress').removeClass("progress-striped");
		    btn.button('reset');
		}, false);
	}

}