﻿// <reference name="MicrosoftAjax.js" />
// <reference path="http://localhost:23305/records.asmx" />

function LoginControlPositie(toonTReDS) {
	var logincontrol = document.getElementById("logincontrol");
	if (logincontrol && toonTReDS)
		logincontrol.style.top = logincontrol.offsetTop + 121;
}

function Huidigepagina() {
	return huidigepagina;
}

var huidigepagina;
function StuurAjaxRequest(requestwaarde) {
	var ajaxManager = $find(_ajaxManager);
	if (ajaxManager != null) {
		var ganaarpagina = requestwaarde.indexOf("ganaarpagina:");
		if (ganaarpagina != -1) {
			var requestPaginaId = requestwaarde.substr(requestwaarde.indexOf(":") + 1);
			if (huidigepagina != requestPaginaId)
				huidigepagina = requestPaginaId;
		}
		ajaxManager.ajaxRequest(requestwaarde);
		var hoofdmenu = $find(_hoofdmenu);
		if (hoofdmenu != undefined) {
			var items = hoofdmenu.get_items();
			for (var i = 0; i < items.get_count(); i++) {
				if (items.getItem(i).get_value() == parseInt(huidigepagina)) {
					items.getItem(i).set_selected(true);
					break;
				}
			}
		}
		//Sluit openstaande dialoogvensters van de SerVision-downloadsmodule
		$("div[id*=DownloadsVideospeler").each(function(index) { $(this).dialog("close"); });
		return false;
	}
	return true;
}

function MainMenuItemClicking(sender, args) {
	args.set_cancel(true);
	var paginaID = args.get_item().get_value();
	if (paginaID == null || paginaID == "") {
		var url = args.get_item().get_navigateUrl();
		if (url != null && url != "") {
			if (url[0] == "+")
				window.open(url.substr(1));
			else window.location.assign(url);
		}
	}
	else {
		if (typeof _contextmenubeheer != "undefined") {
			var contextmenubeheer = $find(_contextmenubeheer);
			if (contextmenubeheer != undefined)
				contextmenubeheer.hide();
		}
		StuurAjaxRequest(String.format("ganaarpagina:{0}", paginaID));
	}
}

function MainMenuLoad(sender, args) {
	var hoofdmenu = $find(_hoofdmenu);
	if (hoofdmenu != undefined) {
		var mainMenuItem = hoofdmenu.findItemByValue(_huidigePagina);
		if (mainMenuItem != undefined)
			mainMenuItem.set_selected(true);
	}
}

function RadAjaxLoadingPanelMasterShowing(sender, args) {
	$telerik.$(args.get_loadingElement()).show("slow");
}

function RadAjaxLoadingPanelMasterHiding(sender, args) {
	$telerik.$(args.get_loadingElement()).hide("slow");
}

//Wordt aangeroepen vanuit Silverlight
var alarmmoduleinfo;
function OpenAlarmpaneel(alarmmodule) {
	alarmmoduleinfo = alarmmodule;
	var videocontent = document.getElementById(alarmmodule.VideoContentClientID);
	//Toon de module als er alarmmeldingen zijn en video alleen dan weegegeven mag worden
	if (alarmmodule.VideoBijAlarm && videocontent != null)
		$("#" + alarmmodule.VideoContentClientID).slideDown("fast").attr("display", "block");
	var dockpanel = $find(alarmmodule.DockpanelClientID);
	if (dockpanel != null)
		dockpanel.set_collapsed(false);
	PortalWebService.HaalModuleAlarminfo(alarmmodule.ModuleID, toonAlarmInfo);
}

function ZetAutoSliderBereik() {
	ZetTijdschaalmenu(0);
	var maxtijd = voorlooptijd > nalooptijd ? voorlooptijd : nalooptijd;
	sliderbereik = (Math.abs(maxtijd / 10) * 10) + 120;
	ZetSliderbereik(sliderbereik);
}

var alarmdatumtijd;
var voorlooptijd;
var nalooptijd;
var alarmID;
var cameras;
var verbergvideo;
var alarmID;
var sliderbereik;
function toonAlarmInfo(arg) {
	if (arg.Alarminfo != null) {
		alarmID = arg.Alarminfo.ID;
		alarmdatumtijd = arg.Alarminfo.TimeStamp;
		voorlooptijd = arg.Voorlooptijd;
		nalooptijd = arg.Nalooptijd;
		cameras = arg.Cameras;
		verbergvideo = arg.Verbergvideo;
		alarmID = arg.Alarminfo.ID;

		//Reageer alleen op de eerste alarmmelding om te voorkomen dat door de gebruiker aangepaste tijden
		//worden overschreven, de alarmmeldingen zullen wel worden gegeven (afhankelijk van de sensorinstellingen)
		if ($("#downloadinstellingenDiv").attr("display") != "block") {
			$("#downloadinstellingenDiv").slideDown("fast").attr("display", "block");
			$("#alarminfoDiv").html(String.format("<b>{0}</b> van <b>{1}</b> is {2} op {3}",
			arg.Alarminfo.Sensorwebnaam == null ? arg.Alarminfo.Sensornaam : arg.Alarminfo.Sensorwebnaam, arg.Alarmbron, arg.Alarminfo.StatusString.toLowerCase(), arg.Alarminfo.TimeStampString));

			ZetAutoSliderBereik();
			$(".RadSliderOpname").slider({
				min: -sliderbereik,
				max: sliderbereik,
				step: 10,
				range: true,
				values: [-arg.Voorlooptijd, arg.Nalooptijd],
				slide: OpnameSliderValueChange
			});
			ZetOpnametijden(-arg.Voorlooptijd, arg.Nalooptijd);
		}
	}
}

function VerwijderAlarmmelding() {
	if (confirm("Wilt u de alarmmelding verwijderen?"))
		PortalWebService.VerwijderAlarmmelding(alarmID, UpdateAlarmInfo);
}

function UpdateAlarmInfo() {
	if (verbergvideo)
		$(String.format("#{0}", alarmmoduleinfo.VideoContentClientID)).slideUp("fast").attr("display", "none");
	else $("#downloadinstellingenDiv").slideUp("fast").attr("display", "none");
}

var achtergrondkleur;
function BindOverzichtMouseHover(moduleID) {
	$(String.format(".SerVisionDownloadsoverzicht{0} tbody tr", moduleID)).hover(
		function() { achtergrondkleur = $(this).css("background-color"); $(this).css("background-color", "#CCF3FF"); },
		function() { $(this).css("background-color", achtergrondkleur); }
	);
}

function UnbindOverzichtMouseHover(moduleID) {
	$(String.format(".SerVisionDownloadsoverzicht{0} tbody tr", moduleID)).unbind('mouseenter mouseleave');
}

//Wordt aangeroepen vanuit Silverlight
function MarkeerVideoInforegel(recordingId) {
	$(String.format(".SerVisionDownloadsoverzicht [class^={0}]", recordingId)).css("background-color", "#5CFF21");
	alert("Er is al een videofragment beschikbaar voor de gevraagde starttijd, opnameduur en camera. Het fragment is gemarkeerd in het overzicht.");
}

function SluitDialoog() {
	$('object,embed', 'div[id=videospeler]').each(function() {
		try { this.controls.stop(); } catch (e) { setTimeout(SluitDialoog, 1000); }
		return false;
	});
}

function StartVideo() {
	$('object,embed', 'div[id=videospeler]').each(function() {
		try {
			this.attachEvent("playStateChange", VideoStatusVeranderd);
			$("#volschermweergaveoptie").attr("title", "volschermweergave").fadeIn("fast").click(function() {
				try { $('object,embed', 'div[id=videospeler]')[0].fullScreen = true; } catch (e) { } return false;
			}).hover(function() { $(this).css("cursor", "pointer"); }, function() { $(this).css("cursor", "auto"); });
		} catch (e) {
			setTimeout(StartVideo, 1000);
		}
		return false;
	});
}

function VideoStatusVeranderd() {
	//1=gestopt, 2=gepauzeerd 3=video speelt
	var status = $('object,embed', 'div[id=videospeler]')[0].playstate;
	if (status == 1)
		$("#volschermweergaveoptie").fadeOut("fast");
	if (status == 2 || status == 3)
		$("#volschermweergaveoptie").fadeIn("fast");
}

//Wordt geïnstantieerd vanuit de servision- en de servisiondownloadsmodules aan de serverkant
function SerVisionAlarm(moduleID, TReDSdeviceID, alarmdockpanelClientID, TReDSAlarmdeviceID, videoBijAlarm, videoContentClientID, isOverzichtsmodule, gridClientID) {
	var This = this;

	var maakAlarmmodule = function() {
		if (This.maakAlarmmodule(moduleID, TReDSdeviceID, alarmdockpanelClientID, TReDSAlarmdeviceID, videoBijAlarm, videoContentClientID, isOverzichtsmodule, gridClientID))
			return;
		setTimeout(maakAlarmmodule, 500);
	};
	maakAlarmmodule(moduleID, TReDSdeviceID, alarmdockpanelClientID, TReDSAlarmdeviceID, videoBijAlarm, videoContentClientID, isOverzichtsmodule, gridClientID);

	if (Sys) {
		this.aspAjaxUnloader = function() {
			This.unload();
			Sys.WebForms.PageRequestManager.getInstance().remove_pageLoading(This.aspAjaxUnloader);
		}
		Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(this.aspAjaxUnloader);
	}
}

var downloadsgriddata;

SerVisionAlarm.prototype = {
	alarmmodule: null,
	unload: function() {
		if (window.TReDS && this.alarmmodule) {
			window.TReDS.VerwijderSerVisionAlarmModule(this.alarmmodule);
			this.alarmmodule = null;
		}
	},
	SpeelVideofragment: function(videoinfo) {
		var This = this;
		$('#servisionvideodiv').slideUp(1);
		var overzicht = String.format(".SerVisionDownloadsoverzicht{0}", This.alarmmodule.ModuleID);
		var videospeler = String.format("#DownloadsVideospeler{0}", This.alarmmodule.ModuleID);

		//Toon de live camerabeelden opnieuw na sluiten van het dialoogvenster
		$(videospeler).dialog({ open: setTimeout(StartVideo, 2000), beforeclose: SluitDialoog, close: function(event, ui) { $("#servisionvideodiv").slideDown("fast"); } });

		//Titel en video-informatie
		$(videospeler).dialog({ title: String.format("Videobron: {0}, camera: {1}", videoinfo.devicenaam.toLowerCase(), videoinfo.cameranaam.toLowerCase()) });
		$(videospeler + ' td[id=recordinfoDevicenaam]').html(videoinfo.devicenaam);
		$(videospeler + ' td[id=recordinfoCameranaam]').html(videoinfo.cameranaam);
		$(videospeler + ' td[id=recordinfoAanvraagdatum]').html(videoinfo.aanmaakdatum);
		$(videospeler + ' td[id=recordinfoStart]').html(videoinfo.start);
		$(videospeler + ' td[id=recordinfoLengte]').html(String.format("{0} (uu:mm:ss)", videoinfo.lengte));
		$(videospeler + ' td[id=unitklokafwijking]').html(videoinfo.unitklokafwijking);
		$(videospeler + ' td[id=recordinfoOpmerking]').html(videoinfo.opmerking);
		//Tabel-stijl
		$(videospeler + ' table[id=videoinfotabel]').css("width", "408px");
		$(videospeler + ' table[id=videoinfotabel]').css("margin-left", "10px");
		$(videospeler + ' table[id=videoinfotabel]').css("border", "1px solid silver");
		$(videospeler + ' table[id=videoinfotabel]').css("border-bottom", "0px solid silver");
		//Tabelkolommen - eerste kolom
		$(videospeler + ' table[id=videoinfotabel] td:even').css("border-right", "1px solid silver");
		$(videospeler + ' table[id=videoinfotabel] td:even').css("background-color", "#D6F0FF");
		$(videospeler + ' table[id=videoinfotabel] td:even').css("width", "110px");
		//Tabelkolommen - tweede kolom
		$(videospeler + ' table[id=videoinfotabel] td:odd').css("background-color", "#EAEAEA");
		//Tabelkolommen - eerste en tweede kolom
		$(videospeler + ' table[id=videoinfotabel] td').css("border-bottom", "1px solid silver");
		$(videospeler + ' table[id=videoinfotabel] td').css("padding", "2px");
		//Div - videospeler
		$(videospeler + ' div:first').css("border", "1px solid silver");
		$(videospeler + ' div:first').css("margin-top", "5px");
		//De videospeler
		$(videospeler + ' div[id=videospeler]').media({
			width: 320,
			height: 310,
			autoplay: true,
			src: videoinfo.videobestand,
			caption: false,
			id: "SerVisionMediaPlayer" + This.alarmmodule.ModuleID
		});
		$(videospeler).dialog("open");
	},
	startSerVisionDownload: function(opmerking, start, eind) {
		if (this.alarmmodule)
			this.alarmmodule.StartSerVisionDownload(opmerking, start, eind);
	},
	herstartSerVisionDownload: function(recordingID) {
		if (this.alarmmodule)
			this.alarmmodule.HerstartSerVisionDownload(recordingID);
	},
	verwijderSerVisionDownload: function(recordingID) {
		if (this.alarmmodule)
			this.alarmmodule.VerwijderSerVisionDownload(recordingID);
	},
	annuleerSerVisionDownload: function(recordingID) {
		if (this.alarmmodule)
			this.alarmmodule.AnnuleerSerVisionDownload(recordingID);
	},
	maakAlarmmodule: function(moduleID, TReDSdeviceID, alarmdockpanelClientID, TReDSAlarmdeviceID, videoBijAlarm, videoContentClientID, isOverzichtsmodule, gridClientID) {
		if (window && window.TReDS) {
			if (this.alarmmodule != null)
				return true;
			var This = this;
			this.alarmmodule = window.createNewAlarmmodule();
			this.alarmmodule.ModuleID = moduleID;
			this.alarmmodule.DockpanelClientID = alarmdockpanelClientID;
			this.alarmmodule.TReDSAlarmdeviceID = TReDSAlarmdeviceID;
			this.alarmmodule.TReDSdeviceID = TReDSdeviceID;
			this.alarmmodule.VideoBijAlarm = videoBijAlarm;
			this.alarmmodule.VideoContentClientID = videoContentClientID;
			this.alarmmodule.IsOverzichtsmodule = isOverzichtsmodule;
			this.alarmmodule.GridClientID = gridClientID;
			this.alarmmodule.InfoEvent = function(source, args) { This.InfoReceived(args); };

			window.TReDS.RegistreerSerVisionAlarmModule(this.alarmmodule);
		}
	},
	InfoReceived: function(arg) {
		var This = this;
		if (This.alarmmodule == null) return;
		var overzicht = String.format(".SerVisionDownloadsoverzicht{0}", This.alarmmodule.ModuleID);
		if (This.alarmmodule.IsOverzichtsmodule) {

			if (window && window.TReDS) {
				var downloadsgrid = $find(This.alarmmodule.GridClientID);
				if (downloadsgrid) {
					downloadsgrid.set_visible(true);
					var tableView = downloadsgrid.get_masterTableView();
					tableView.set_virtualItemCount(arg.Aantaldownloads);
					var data = window.TReDS.HaalDownloads("","", "", tableView.get_currentPageIndex(), tableView.get_pageSize());
					data = data.substr(data.indexOf("["));
					if (tableView && data != "") {
						tableView.set_dataSource(jQuery.parseJSON(data));
						tableView.dataBind();
					}
				}
			}

			if ($(overzicht).html() != arg.Infohistorie) {
				//Toon de witruimte van de module als er een div gebruikt wordt (moduleinhoud in dockpanel)
				$(String.format("div[id*=_witruimte_{0}", This.alarmmodule.ModuleID)).css("display", "block");
				//Toon de witruimte als de moduleinhoud zich niet in een dock bevindt, gebruik hiervoor de waarde onhouden in het class-attribuut
				$(String.format("div[class^=witruimte_")).each(function(index) { $(this).css("paddingTop", $(this).attr("class").substr(10)); });
				$(overzicht).html(arg.Infohistorie);
				var magVerwijderen = $(overzicht).attr("magverwijderen");
				if (magVerwijderen == undefined || magVerwijderen.toLowerCase() == "false")
					$(overzicht + " td[id=verwijder],th[id=verwijder]").remove();
				BindOverzichtMouseHover(This.alarmmodule.ModuleID);
				$(overzicht + " span a[onclick*=annuleer]").parent("span").css("display", "none");
				var magHerstarten = $(overzicht).attr("magherstarten");
				if (magHerstarten == undefined || magHerstarten.toLowerCase() == "false")
					$(overzicht + " a[onclick*=herstart]").parent().html("Mislukt");
				$(overzicht + " div[id=voortgang").each(function() { $(this).progressbar({ value: parseInt($(this).attr("class")) }); });
				$(overzicht + " tr").each(function(index) {
					//Downloads van vandaag mogen niet worden verwijderd
					$(this).children("td[id=vandaag]").siblings("td[id=verwijder]").html("");
					var downloadinfo = $(this).children("td[id=download]").html();
					//Clickhandler voor het afspelen van het videofragment
					$(this).children("td[id=download]").children("a[id=bekijkvideo]").click(function() { eval("serVisionAlarm" + This.alarmmodule.ModuleID + ".SpeelVideofragment(" + $(this).attr("class") + ");"); return false; });
					if (downloadinfo) {
						var bestand = downloadinfo.substring(downloadinfo.indexOf("videobestand:") + 14);
						var bestand = bestand.substring(0, bestand.indexOf("'"));
						var downloadnaam = $(this).children("td[id=camera]").attr("class");
						if (downloadnaam != "") {
							var bestand = bestand.substring(0, bestand.lastIndexOf("/") + 1) + "dl/" + downloadnaam + bestand.substring(bestand.lastIndexOf("/"));
							var camera = $(this).children("td[id=camera]").text();
							$(this).children("td[id=camera]").html(String.format("<a href=\"{0}\" title=\"Download het videofragment voor camera '{1}'\">{1}</a>", bestand, camera));
						}
					}
				});
			}
		} else {
			//Voor SerVisionmodules
			if (arg.Infovandaag == "")
				$(overzicht).hide();
			else if ($(overzicht).html() != arg.Infovandaag) {
				$(overzicht).show().html(arg.Infovandaag);
				$(overzicht + " td[id=verwijder],th[id=verwijder]").remove();
				$(overzicht + " div[id=voortgang").each(function() { $(this).progressbar({ value: parseInt($(this).attr("class")) }); });
				if ($(overzicht + " tr").length == 1) {
					var melding = "<div style='border:1px solid #9CB6C5;padding:2px;background-color:#C2DCF0'>Geen videofragmenten aanwezig voor vandaag</div>";
					$(overzicht).html(melding);
				} else {
					//Clickhandler voor het afspelen van het videofragment
					$(overzicht + " tr").each(function(index) { $(this).children("td[id=download]").children("a[id=bekijkvideo]").click(function() { eval("serVisionAlarm" + This.alarmmodule.ModuleID + ".SpeelVideofragment(" + $(this).attr("class") + ");"); }); });
				}
			}
		}
	}
}


