

$(document).ready(function(){

	// load the data
	$.ajax({
		url: "app/model/Update.php?conf="+conf,
		success: function(result) {
			res = ui.ParseJSON(result);
			ui.Load( res );
			update.Load( res );
		}
	});


});

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

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

	/* -- Add the page name -- */				
	$(".pagename").html("Update Profile: <strong>"+data.profile.profilename+ "</strong> ("+data.profile.confdomain+")");
		
	
	$(".locationname").html("Update Profile");
	
	$("#profile-view").on("click", function(e){
		window.location.href = "dashboard.php?conf=" + data.profile.profilename;
	});

	/* -- create the menu -- */
	ui.populatemenu(data.menu_cat);

	/* -- 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");
		action = data.menu_items[i]['action'];
		eval(data.menu_items[i]['action']);			
		
	});
	
	/* If update is blocked by subscriptions then remove the spin and add text to the elements. */
	if(ui.BlockedBySubscription("Update")){
		$(".updateinfo .box-header i").removeClass("fa-spin");
		$(".updateinfo .box-body, .viewprogress .box-body").html(ui.data.languages['_NO_PERMISSION']);
		return false;
	}

	$(".helptxt .box-body").html(ui.data.languages['_UPDATE_RUNNING_INFO']);

	update.StartUpdate();

	$("#main-menu li:first a:first").click();
	update.startpos = 0;
	update.ViewProgress();

}

update.StartUpdate = function () {
	var update_url = "update.php?conf="+update.data.profile.profilename + GetAdditionalUrlParams();

	$.ajax({
		url: update_url,
		type: "GET",
		async: true,		
		success: function(result) {				
			res =  ui.ParseJSON(result);
			if (res.Status == "Error") {				
				ui.error_report += $(".viewprogress .box-body").html();
				if (res.ParseError!=true) {
					$(".updateinfo .box-body").html(res.Message);
					update.streamsource.close();
					console.log("stream stopped by json error");
				}

			}
			if (res.Status == "Success") {
				$(".updateinfo .box-body").html(res.Message);

				if (res.withErrors==true) {
					$(".updateinfo .box-body").append("<br>" + ui.data.languages["_UPDATE_FINISHED_W_ERRORS"]);
					ui.error_report += $(".viewprogress .box-body").html();
				}
				fb = "<br>&nbsp;<br>";
				if (res.email_feedback) {
					$.each(res.email_feedback, function (k,v) {
						fb += v + "<br>";
					});
					$(".updateinfo .box-body").append(fb);
				}

				update.CheckResults(res.Data);
			}
			$(".updateinfo .box-header i").removeClass("fa-spin");


		},
		error: function(result) {
			res = {};
			res.Status = "Error";
			res.Message = result.status + " " + result.statusText;
			ui.Callout(res);
			$(".updateinfo .box-header i").removeClass("fa-spin");
			$(".updateinfo .box-body").html("Could not start update");
			update.streamsource.close();
			console.log("stream stopped by error");

		}
	});

}

update.CheckResults = function(results){
	/* Collect some usefull numbers */
	var sessionC = parseInt(update.data.profile.sessioncounter);
	var trackM = parseInt(update.data.profile.trackermode);
	
	/* When we are using the javascript tracker and there is not data set before and not now */
	if(trackM === 1 && sessionC === 0 && results.SumT === 0){
		Intercom('trackEvent', 'no-jstracker-update-data');
		return false;
	}

	/* When we are using the FTP and there is no data yet and no files found */
	if(trackM === 2 && sessionC === 0 && results.TOTF === 0){
		Intercom('trackEvent', 'no-ftp-update-files');
		return false;
	}
}

update.ViewProgress_old = function() {
	//return;
	$.ajax({
		url: "app/model/UpdateStream.php?conf="+update.data.profile.profilename+"&startpos="+update.startpos,
		type: "GET",		
		success: function(result) {				
			res =  ui.ParseJSON(result);
			if (res.Status != "Warning") {
				if (res.clear_screen==true) {
					$(".viewprogress .box-body").html("");
				}
				$(".viewprogress .box-body").append(res.contents+ "<br>");
				$(".viewprogress .box-body").scrollTop($(".viewprogress .box-body")[0].scrollHeight);				
			}
			update.startpos = res.startpos;

			if (res.finished == false) {
				update.ViewProgress();
			}
		}
	});
}

update.streamsource;

update.ViewProgress = function() {

	var url = "app/model/UpdateStream.php?conf="+update.data.profile.profilename+"";
	console.log(url);		

	update.streamsource = new EventSource(url);

	update.streamsource.addEventListener('message', function (e) {		
		//console.log(e);
		$(".viewprogress .box-body").append(e.data+ "<br>");
		$(".viewprogress .box-body").scrollTop($(".viewprogress .box-body")[0].scrollHeight);
		if (e.data.indexOf("Finished]")!=-1) {
			console.log("closing stream");
			update.streamsource.close();
		}

	}, false);

	update.streamsource.addEventListener('error', function (e) {
	    update.streamsource.close();
	    console.log('stopped');
	    //console.log(e);
	}, false);
}

update.Stop = function() {
	$.ajax({
		url: "app/model/StopUpdate.php?conf="+update.data.profile.profilename,
		type: "GET",		
		success: function(result) {				
			res =  ui.ParseJSON(result);
			ui.Callout(res);
			$(".updateinfo .box-header i").removeClass("fa-spin");
			$(".updateinfo .box-body").html(ui.data.languages["_USER_STOPPED_UPDATE"]);

		}
	});
}

