﻿/// <reference name="MicrosoftAjax.js" />
/// <reference path="../PortalWebService.asmx" />

var PTZ_Up = 1;
var PTZ_Left = 2;
var PTZ_Home = 3
var PTZ_Right = 4;
var PTZ_Down = 5;
var PTZ_ZoomIn = 6;
var PTZ_ZoomOut = 7;
var PTZ_FocusAuto = 11;
var PTZ_FocusFar = 12;
var PTZ_FocusNear = 13;

function parseVersieString(versie) {
	if (typeof (versie) != 'string') { return false; }
	var x = versie.split('.');
	var _major = parseInt(x[0]) || 0;
	var _minor = parseInt(x[1]) || 0;
	var _patch1 = parseInt(x[2]) || 0;
	var _patch2 = parseInt(x[3]) || 0;
	return { major: _major, minor: _minor, patch1: _patch1, patch2: _patch2 }
}

function ClientSDKVersieGelijkOfHogerServerversie(client, server) {
	var clientversie = parseVersieString(client);
	var serverversie = parseVersieString(server);
	if (clientversie.major < serverversie.major)
		return false;
	else if (clientversie.minor < serverversie.minor)
		return false;
	else if (clientversie.patch1 < serverversie.patch1)
		return false;
	else if (clientversie.patch2 < serverversie.patch2)
		return false;
	else
		return true;
}

function setInstalledImageState(controlimg, state) {
	controlimg.src = state ? "images/accept.png" : "images/exclamation.png";
	controlimg.title = controlimg.alt = state ? "beschikbaar" : "niet beschikbaar";
}

function ClientSDKChecker(PrimarySessionImage, StreamSessionImage, VideoWindowImage, StreamInfoImage, SoundOutSessionImage, ConnectionInfoImage, InstallSDKFrame, InstallBoodschap) {
	if (typeof (ActiveXObject) == "undefined")
		return;
	var state = ClientSDKCheck();
	setInstalledImageState(PrimarySessionImage, state.havePrimarySession);
	setInstalledImageState(StreamSessionImage, state.haveStreamSession);
	setInstalledImageState(VideoWindowImage, state.haveVideoWindow);
	setInstalledImageState(StreamInfoImage, state.haveStreamInfo);
	setInstalledImageState(SoundOutSessionImage, state.haveSoundOutSession);
	setInstalledImageState(ConnectionInfoImage, state.haveConnectionInfo);
	if (state.isSDKInstalled || state.isSDKInstalling) {
		InstallSDKFrame.style.display = "none";
		InstallBoodschap.innerHTML = "<br/>Alle SerVision ActiveX-componenten zijn correct geïnstalleerd.";
	}
	else {
		InstallSDKFrame.style.display = "block";
		InstallBoodschap.innerHTML = "Klik de onderstaande knop om 'SVClientSDK' ";
		InstallBoodschap.innerHTML += "van uitgever 'SerVision Ltd.' te installeren en volg de instructies op uw scherm.";
		setTimeout(function() { ClientSDKChecker(PrimarySessionImage, StreamSessionImage, VideoWindowImage, StreamInfoImage, SoundOutSessionImage, ConnectionInfoImage, InstallSDKFrame, InstallBoodschap) }, 5000);
	}
}

function ClientSDKCheck() {
	var PrimarySession;
	var StreamSession;
	var VideoWindow;
	var StreamInfo;
	var SoundOutSession;
	var connectionInfo;
	try {
		PrimarySession = new ActiveXObject("SVActiveX.PrimarySession");
		StreamSession = new ActiveXObject("SVActivex.StreamSession");
		VideoWindow = new ActiveXObject("SVActiveX.VideoWindow");
		StreamInfo = new ActiveXObject("SVActiveX.StreamInfoEx");
		SoundOutSession = new ActiveXObject("SVActiveX.SoundOutSession");
		connectionInfo = new ActiveXObject("SVActiveX.ConnectionInfo");
	} catch (err) { }
	var havePrimarySession = PrimarySession != null;
	var haveStreamSession = StreamSession != null;
	var haveVideoWindow = VideoWindow != null;
	var haveStreamInfo = StreamInfo != null;
	var haveSoundOutSession = SoundOutSession != null;
	var haveConnectionInfo = connectionInfo != null;
	var isSDKInstalled = havePrimarySession && haveStreamSession && haveVideoWindow && haveStreamInfo && haveSoundOutSession && haveConnectionInfo;
	var isSDKInstalling = !isSDKInstalled && (havePrimarySession || haveStreamSession || haveVideoWindow || haveStreamInfo || haveSoundOutSession || haveConnectionInfo);

	return {
		havePrimarySession: havePrimarySession,
		haveStreamSession: haveStreamSession,
		haveVideoWindow: haveVideoWindow,
		haveStreamInfo: haveStreamInfo,
		haveSoundOutSession: haveSoundOutSession,
		haveConnectionInfo: haveConnectionInfo,
		isSDKInstalled: isSDKInstalled,
		isSDKInstalling: isSDKInstalling
	}
}

function installClientSDK(targetlocation, sourcepath, installindicator) {
	document.location.hash = installindicator;
	targetlocation.innerHTML = "<object classid=\"clsid:AF23B3EC-8C2C-4425-93AE-587CE18955DD\" type=\"application/oleobject\" codebase=\"" + sourcepath + "\"></object>";
}

var svmonitorstateimg = {
	Connecting: {
		title: "verbinden...",
		img: "images/monitorconnecting.gif",
		imgtitle: "Bezig met verbinden...",
		custSize: { width: 32, height: 32 }
	},
	SessionFailed: {
		title: "Sessiefout",
		img: "images/sessionfailed.png",
		imgtitle: "De sessieverbinding is mislukt of onderbroken"
	},
	VideoLost: {
		title: "Geen signaal",
		img: "images/videolost.png",
		imgtitle: "De camera staat op dit moment niet aan, of er is geen camera"
	},
	NotCamera: {
		title: "Camera niet gevonden",
		img: "images/notfound.png",
		imgtitle: "Deze camera is niet gevonden op de verbonden unit"
	},
	NoCameras: {
		title: "Geen camera's beschikbaar",
		img: "images/nocameras.png"
	}
}

var svstatemsg = {
	noActiveX: {
		message: "Helaas is videoweergave niet mogelijk omdat uw browser geen ActiveX ondersteunt. Gebruik bij voorkeur Microsoft Internet Explorer om gebruik te maken van deze functionaliteit.",
		className: "GeenVideoActiveX"
	},
	noServisionSDK: {
		message: "",
		className: "ServisionSDKNietGeinstalleerd"
	},
	getlogin: {
		message: "Unit-informatie wordt opgehaald...",
		className: ""
	},
	connectunit: {
		message: "Verbinding met unit wordt opgebouwd...",
		className: ""
	},
	connectfailed: {
		message: "Verbinding met unit mislukt...",
		className: ""
	},
	getmonitors: {
		message: "Monitor-informatie wordt opgehaald...",
		className: ""
	}
};

function SerVisionVideo(ContainerDiv, config) {
	if (!ContainerDiv)
		return;

	var notifydiv = document.createElement("div");
	notifydiv.style.display = "none";
	ContainerDiv.appendChild(notifydiv);
	this.notifydiv = notifydiv;

	if (typeof (ActiveXObject) == "undefined") {
		this.notifyStateMsg(svstatemsg.noActiveX);
		return;
	}

	if (!ClientSDKCheck().isSDKInstalled) {
		this.notify(config.InstallPageString, svstatemsg.noServisionSDK.className);
		return;
	}

	var This = this;
	this.moduleID = config.ModuleID;
	this.moduleIdInhoud = config.ModuleIdInhoud;
	this.containerDiv = ContainerDiv;
	var monitors = config.MonitorInfo.length;

	this.monitors = new Array();

	if (config.GeluidIn) {
		this.audioPlayer = new ActiveXObject("SVAudioPlayer.Player");
	}

	var fragment = document.createDocumentFragment();
	var rootdiv = document.createElement("div");
	rootdiv.style.width = "100%";
	fragment.appendChild(rootdiv);
	this.rootdiv = rootdiv;

	var soundLink = document.createElement("a");
	soundLink.href = "#";
	this.soundButtonLink = soundLink;
	soundLink.onmousedown = function() {
		This.startSoundOut();
		This.soundButtonLink.innerHTML = "Stop communicatie";
		return false;
	};
	soundLink.onmouseout = // NB: hier wordt dezelfde actie aan twee events gehangen, deze code klopt dus gewoon
    soundLink.onmouseup = function() {
    	This.stopSoundOut();
    	This.soundButtonLink.innerHTML = "Start communicatie";
    	return false;
    }
	soundLink.onclick = function() { return false; }

	if (config.GeluidUit) {
		this.soundButtonLink.innerHTML = "Start communicatie";
		this.soundButtonLink.className = "ServisionCommunicatie";
		this.soundButtonLink.style.width = "100%";
		this.soundButtonLink.style.display = "none";
		rootdiv.appendChild(soundLink);
	}

	if (config.GeluidIn) {
		var playLink = document.createElement("a");
		playLink.href = "#";
		playLink.state = false;
		playLink.setState = function(state) {
			this.state = state;
			this.innerHTML = this.state ? "Stop audioweergave" : "Start audioweergave";
			This.audioLinkStateChanged(state);
		};
		playLink.onclick = function() {
			this.setState(!this.state);
			return false;
		}
		playLink.className = "ServisionCommunicatie";
		playLink.style.width = "100%";
		playLink.style.display = "none";
		rootdiv.appendChild(playLink);
		this.soundPlayLink = playLink;
	}

	var primarySessionObj = document.createElement("object");
	primarySessionObj.setAttribute("classid", "clsid:AF23B3EC-8C2C-4425-93AE-587CE18955DD");
	primarySessionObj.setAttribute("type", "application/oleobject");
	primarySessionObj.style.display = "none";
	fragment.appendChild(primarySessionObj);
	this.primarySession = primarySessionObj;
	this.primarySession.attachEvent("LoggedIn", function() { This.ps_loggedIn(); });
	this.primarySession.attachEvent("LoginFailed", function() { This.ps_loginFailed(); });
	this.primarySession.attachEvent("SessionFailed", function() { This.ps_sessionFailed(); });
	this.primarySession.attachEvent("SocketError", function() { This.ps_SocketError(); });
	this.primarySession.attachEvent("CamerasReceived", function() { This.ps_camerasReceived(); });
	this.primarySession.attachEvent("ServiceAdded", function(serviceID) { This.ps_ServiceAdded(serviceID); });

	if (config.GeluidIn) {
		var audioStreamSessionObj = document.createElement("object");
		audioStreamSessionObj.kanaal = Kanaal;
		audioStreamSessionObj.setAttribute("classid", "clsid:FEDF63B9-E0EE-45CC-A5D2-5C019BF42D95");
		audioStreamSessionObj.setAttribute("type", "application/oleobject");
		audioStreamSessionObj.setAttribute("kanaal", Kanaal);
		audioStreamSessionObj.style.display = "none";
		fragment.appendChild(audioStreamSessionObj);
		audioStreamSessionObj.attachEvent("SoundArrived", function() { This.audio_SoundArrived(); });
		this.audioStreamSession = audioStreamSessionObj;
		primarySessionObj.Attach(audioStreamSessionObj.Handle);
		playLink.setState(false);
	}

	var groupMap = new Array();

	for (var i = 0; i < monitors; ++i) {
		var Kanaal = config.MonitorInfo[i].Kanaal;
		this.monitors[Kanaal] = new SerVisionVideoMonitor(this, config.MonitorInfo[i]);
		var group = this.monitors[Kanaal].groupID;
		if (!groupMap[group])
			groupMap[group] = new Array();
		groupMap[group].push(this.monitors[Kanaal]);
		//rootdiv.appendChild(this.monitors[Kanaal].monitorDomFragment);
	}
	var groupindices = new Array();
	for (groupID in groupMap)
		groupindices.push(groupID);
	groupindices.sort();
	groupindices.reverse();
	while (groupindices.length > 0) {
		groupID = groupindices.pop();
		var groupdiv = document.createElement("div");
		rootdiv.appendChild(groupdiv);
		groupdiv.style.width = "100%";
		//groupdiv.style.display = "block";
		//groupdiv.style.float = "left";
		groupMap[groupID].reverse();
		while (groupMap[groupID].length > 0)
			groupdiv.appendChild(groupMap[groupID].pop().monitorDomFragment);
		var closerdiv = document.createElement("div");
		groupdiv.appendChild(closerdiv);
		closerdiv.style.display = "block";
		closerdiv.style.clear = "both";
		closerdiv.style.width = "100%";
	}

	this.hideGui();
	this.containerDiv.appendChild(fragment);
	this.notifyStateMsg(svstatemsg.getlogin);

	if (!config.Wijzigmodus)
		PortalWebService.SVC(this.moduleIdInhoud, null, function(arg) { This.SVCSuccess(arg); }, null, null);

	this.wijzigmodus = config.Wijzigmodus;

	if (Sys) {
		this.aspAjaxUnloader = function() {
			This.unload();
			Sys.WebForms.PageRequestManager.getInstance().remove_pageLoading(This.aspAjaxUnloader);
		}
		Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(this.aspAjaxUnloader);
	}
}

function SerVisionVideoMonitor(Parent, config) {
	if (!Parent)
		return;
	if (!config)
		return;
	var This = this;

	this.channel = config.Kanaal;
	this.groupID = config.Groep;
	this.parent = Parent;

	var fragment = document.createDocumentFragment();
	this.monitorDomFragment = fragment;

	var mondiv = document.createElement("div");
	mondiv.className = "ServisionMonitor";

	if (config.Linkermarge != null)
		mondiv.style.cssText = "padding-left: " + config.Linkermarge.toString() + "px";

	if (config.Titel) {
		var titlediv = document.createElement("div");
		titlediv.className = "ServisionMonitorTitel";
	}

	var edgediv = document.createElement("div");
	edgediv.className = "ServisionMonitorKaderrand";

	var stateImg = document.createElement("img");
	stateImg.style.display = "none";

	var videoObject = document.createElement("object");
	videoObject.setAttribute("classid", "clsid:C9CD770C-E937-48EA-B198-9381B97F586C");
	videoObject.setAttribute("type", "application/oleobject");

	if (config.Titel)
		mondiv.appendChild(titlediv);
	mondiv.appendChild(edgediv);
	edgediv.appendChild(stateImg);
	edgediv.appendChild(videoObject);

	fragment.appendChild(mondiv);

	var ptzControls = null;
	var presetControls = null;

	var menuhostDiv = document.createElement("div");
	menuhostDiv.style.display = "none";
	menuhostDiv.className = "ServisionCameraKeuze";
	mondiv.appendChild(menuhostDiv);

	if (config.Besturing) {
		ptzControls = document.createElement("div");
		ptzControls.className = "ServisionCameraBesturing";
		var controls = [
			{ img: "images/arrow_left.png", Direction: PTZ_Left, Title: "Links" },
			{ img: "images/arrow_right.png", Direction: PTZ_Right, Title: "Rechts" },
			{ img: "images/arrow_up.png", Direction: PTZ_Up, Title: "Omhoog" },
			{ img: "images/arrow_down.png", Direction: PTZ_Down, Title: "Omlaag" },
			{ img: "images/add.png", Direction: PTZ_ZoomIn, Title: "Zoom in" },
			{ img: "images/delete.png", Direction: PTZ_ZoomOut, Title: "Zoom uit" }
		];
		var prepend = document.location.pathname.toLowerCase().match("desktopmodules") != null ? "../" : "";
		for (var j = 0; j < controls.length; ++j) {
			var img = document.createElement("img");
			img.className = "ServisionCamerabesturingsknop";
			img.src = prepend + controls[j].img;
			img.title = controls[j].Title;
			img.command = controls[j].Direction;
			img.onclick = function() {
				This.streamSession.CameraAction(this.command);
			};
			ptzControls.appendChild(img);
		}
		presetControls = document.createElement("div");
		presetControls.className = "ServisionCameraBesturing";
		for (var j = 1; j <= 10; ++j) {
			var img = document.createElement("img");
			img.className = "ServisionCamerapresetknop";
			img.src = prepend + "images/preset_" + j.toString() + ".jpg";
			img.presetnum = j;
			img.onclick = function() {
				This.streamSession.PresetGoTo(this.presetnum);
			};
			img.title = "Preset " + j.toString();
			presetControls.appendChild(img);
		}
		ptzControls.style.display = "none";
		presetControls.style.display = "none";
		mondiv.appendChild(presetControls);
		mondiv.appendChild(ptzControls);
	}

	var streamSessionObj = document.createElement("object");
	streamSessionObj.setAttribute("classid", "clsid:FEDF63B9-E0EE-45CC-A5D2-5C019BF42D95");
	streamSessionObj.setAttribute("type", "application/oleobject");
	streamSessionObj.style.display = "none";
	mondiv.appendChild(streamSessionObj);
	streamSessionObj.attachEvent("ProtocolError", function() {
		This.streamses_ProtocolError();
	});
	streamSessionObj.attachEvent("SocketError", function() {
		This.streamses_SocketError();
	});
	streamSessionObj.attachEvent("SessionFailed", function() {
		This.streamses_SessionFailed();
	});
	streamSessionObj.attachEvent("StreamPlaying", function() {
		This.streamses_StreamPlaying();
	});
	streamSessionObj.attachEvent("VideoRestored", function() {
		This.streamses_VideoRestored();
	});
	streamSessionObj.attachEvent("VideoLost", function() {
		This.streamses_VideoLost();
	});

	videoObject.WindowSize = config.Kwaliteit;
	videoObject.style.cssText = "";
	videoObject.attributes.removeNamedItem("height");
	videoObject.attributes.removeNamedItem("width");



	var clientVersionCheck = ClientSDKVersieGelijkOfHogerServerversie(Parent.primarySession.Version, "1.0.1.31");

	if (clientVersionCheck) {
		if (config.Breedte != null) {
			stateImg.realwidth = stateImg.style.width = config.Breedte;
			stateImg.realheight = stateImg.style.height = config.Breedte / 4 * 3;
			videoObject.SetWindowMetrics(config.Breedte, config.Breedte / 4 * 3);
			videoObject.style.cssText = "";
			videoObject.attributes.removeNamedItem("height");
			videoObject.attributes.removeNamedItem("width");
		}
	}
	if (!clientVersionCheck || !config.Breedte) {
		stateImg.realwidth = stateImg.style.width = 160 * Math.pow(2, config.Kwaliteit);
		stateImg.realheight = stateImg.style.height = 120 * Math.pow(2, config.Kwaliteit);
	}

	streamSessionObj.Attach(videoObject.ObjectHandle);
	Parent.primarySession.Attach(streamSessionObj.Handle);

	this.menuHost = menuhostDiv;
	this.streamSession = streamSessionObj;
	this.videoWindow = videoObject;
	this.stateImg = stateImg;
	if (config.Titel)
		this.titleElement = titlediv;
	else
		this.titleElement = null;

	this.ptzControl = ptzControls;
	this.presetControl = presetControls;
}

SerVisionVideoMonitor.prototype = {
	channel: -1,
	groupID: 0,
	parent: null,
	streamSession: null,
	videoWindow: null,
	stateImg: null,
	titleElement: null,
	monitorInfo: null,
	menuHost: null,
	menu: null,
	ptzControl: null,
	presetControl: null,
	monitorDomFragment: null,
	currentCamera: 0,
	title: "",
	hasMonitorInfo: false,

	setState: function(stateObj) {
		var prepend = document.location.pathname.toLowerCase().match("desktopmodules") != null ? "../" : "";
		if (this.titleElement)
			this.titleElement.innerHTML = stateObj.title;
		this.stateImg.src = prepend + stateObj.img;
		this.stateImg.title = stateObj.imgtitle;
		//this.stateImg.style.border = "none";
		if (stateObj.custSize) {
			this.stateImg.style.marginTop = this.stateImg.style.marginBottom = (this.stateImg.realheight - stateObj.custSize.height) / 2;
			this.stateImg.style.marginLeft = this.stateImg.style.marginRight = (this.stateImg.realwidth - stateObj.custSize.width) / 2;
			this.stateImg.style.height = stateObj.custSize.height;
			this.stateImg.style.width = stateObj.custSize.width;
		} else {
			this.stateImg.style.marginTop = this.stateImg.style.marginBottom = this.stateImg.style.marginLeft = this.stateImg.style.marginRight = 0;
			this.stateImg.style.height = this.stateImg.realheight;
			this.stateImg.style.width = this.stateImg.realwidth;
		}
		//this.stateImg.style.paddingTop = this.stateImg.style.paddingBottom = this.stateImg.style.paddingLeft = this.stateImg.style.paddingRight = 0;
		this.stateImg.style.display = "block";
		this.videoWindow.style.display = "none";
	},
	clearState: function() {
		this.stateImg.style.display = "none";
		this.videoWindow.style.display = "block";
		if (this.titleElement)
			this.titleElement.innerHTML = this.title;
	},

	streamses_ProtocolError: function() {
		this.setState(svmonitorstateimg.SessionFailed);
	},
	streamses_SocketError: function() {
		this.setState(svmonitorstateimg.SessionFailed);
	},
	streamses_SessionFailed: function() {
		this.setState(svmonitorstateimg.SessionFailed);
	},
	streamses_StreamPlaying: function() {
		this.toonBesturing(this.currentCamera);
		this.clearState();
	},
	streamses_VideoLost: function() {
		this.videoWindow.Clear();
		this.setState(svmonitorstateimg.VideoLost);
	},
	streamses_VideoRestored: function() {
		this.clearState();
	},

	toonBesturing: function(cameraID) {
		if (cameraID == 0) {
			if (this.ptzControl)
				this.ptzControl.style.display = "none";
			if (this.presetControl)
				this.presetControl.style.display = "none";
		} else {
			for (var i = 0; i < this.monitorInfo.Cameras.length; ++i) {
				if (this.monitorInfo.Cameras[i].CameraID == cameraID) {
					var cam = this.monitorInfo.Cameras[i];
					var camID = this.parent.primarySession.CameraIDFromOriginal(cam.CameraID);
					var bestuurbaar = this.parent.primarySession.CameraMovePossible(camID, 1);

					if (this.ptzControl)
						this.ptzControl.style.display = cam.Bestuurd && bestuurbaar ? "block" : "none";
					if (this.presetControl)
						this.presetControl.style.display = cam.Presets && bestuurbaar ? "block" : "none";
				}
			}
		}
	},
	viewVideo: function(cameraID, cameraNaam) {
		var cameraOnline = this.parent.cameraAvailable(cameraID);
		if (cameraOnline || cameraID == 0) {
			this.title = cameraNaam;
			this.currentCamera = cameraID;
			this.streamSession.Disconnect();
			this.videoWindow.Clear();
			if (cameraID != 0) {
				this.setState(svmonitorstateimg.Connecting);
				var streamInfo = new ActiveXObject("SVActiveX.StreamInfoEx");
				streamInfo.ID = this.parent.primarySession.CameraIDFromOriginal(cameraID);
				streamInfo.ProfileID = 0;
				streamInfo.StreamSize = this.videoWindow.WindowSize;
				this.streamSession.StartCameraSessionEx(streamInfo);
			}
			//  if (this.titleElement != null)
			//      this.titleElement.innerHTML = cameraNaam;
		}
		else if (this.titleElement != null)
			this.setState(svmonitorstateimg.NotCamera);
		//this.titleElement.innerHTML = "[Camera Offline]";
	},
	cameraMenuChange: function(cameraID) {
		if (cameraID == 0) {
			this.viewVideo(0, "[Geen Camera]")
		} else if (this.monitorInfo != null) {
			var Cameras = this.monitorInfo.Cameras;
			for (var i = 0; i < Cameras.length; ++i)
				if (Cameras[i].CameraID == cameraID) {
				var cam = Cameras[i];
				this.viewVideo(cam.CameraID, cam.Naam);
			}
		}
	},
	updateMonitorInfo: function(monitor) {
		var This = this;
		this.monitorInfo = monitor;
		if (monitor.Cameras.length > 1) {
			var camMenu = document.createElement("select");
			camMenu.onchange = function() {
				This.cameraMenuChange(this.options[this.selectedIndex].value);
			};
			if (this.wijzigmodus || monitor.DefaultCamera == 0) {
				var camEntry = new Option("[Geen Camera]", 0);
				//if(!
				camEntry.selected = monitor.DefaultCamera == 0;
				camMenu.options[camMenu.length] = camEntry;
			}
			for (var j = 0; j < monitor.Cameras.length; ++j) {
				var cam = monitor.Cameras[j];
				var camEntry = new Option(cam.Naam, cam.CameraID);
				camEntry.selected = cam.CameraID == monitor.DefaultCamera;
				camMenu.options[camMenu.length] = camEntry;
			}
			if (this.menu)
				this.menuHost.removeChild(this.menu);
			this.menuHost.appendChild(camMenu);
			this.menuHost.style.display = "block";
			this.menu = camMenu;
			if (monitor.DefaultCamera != 0) {
				var defaultfound = false;
				for (var j = 0; j < monitor.Cameras.length; ++j) {
					if (monitor.Cameras[j].CameraID == monitor.DefaultCamera) {
						var cam = monitor.Cameras[j];
						this.viewVideo(cam.CameraID, cam.Naam);
						defaultfound = true;
					}
				}
				if (!defaultfound)
					this.cameraMenuChange(camMenu.options[0].value);
			}
		}
		else if (monitor.Cameras.length == 1)
			this.viewVideo(monitor.Cameras[0].CameraID, monitor.Cameras[0].Naam);
		else
			this.setState(svmonitorstateimg.NoCameras);
		this.hasMonitorInfo = true;
	},
	unload: function() {
	}
}

SerVisionVideo.prototype = {
	wijzigmodus: false,
	moduleID: 0,
	moduleIdInhoud: 0,
	containerDiv: null,
	soundButtonLink: null,
	soundPlayLink: null,
	primarySession: null,
	monitors: null,
	rootdiv: null,
	notifydiv: null,
	soundOut: null,
	soundOutID: 0,
	audioStreamSession: null,
	audioPlayer: null,
	deviceID: 0,
	aspAjaxUnloader: null,
	kanaal0: 0,

	notifyStateMsg: function(stateMsg) {
		this.notify(stateMsg.message, stateMsg.className);
	},
	notify: function(notification, className) {
		this.notifydiv.innerHTML = notification;
		this.notifydiv.className = className;
		this.notifydiv.style.display = "block";
	},
	clearNotify: function() {
		this.notify("", "");
	},
	hideNotify: function() {
		this.notifydiv.style.display = "none";
	},
	setGui: function(Toggle) {
		this.rootdiv.style.display = Toggle ? "block" : "none";
	},
	hideGui: function() {
		this.setGui(false);
	},
	showGui: function() {
		this.setGui(true);
	},

	changeDevice: function(devID) {
		var This = this;
		this.deviceID = devID;
		for (kanaal in this.videoWindows)
			this.viewVideo(0, "", kanaal);
		this.primarySession.Disconnect();
		PortalWebService.SVC(this.moduleIdInhoud, devID, function(arg) { This.SVCSuccess(arg); }, null, null);
	},
	SVCSuccess: function(arg) {
		this.primarySession.Disconnect();
		if (arg != null) {
			this.notifyStateMsg(svstatemsg.connectunit);
			this.connectToGateway(arg);
		}
	},
	startSoundOut: function() {
		if (this.soundOut != null)
			return;
		this.soundOut = new ActiveXObject("SVActiveX.SoundOutSession");
		this.primarySession.AttachSoundOut(this.soundOut.Handle);
		this.soundOut.Muted = false;
		this.soundOut.Start(this.soundOutID);
	},
	stopSoundOut: function() {
		if (this.soundOut == null)
			return;
		this.soundOut.Muted = true;
		this.soundOut.Disconnect();
		this.soundOut = null;
	},
	haalMonitorSuccess: function(arg) {
		try {
			this.clearNotify();
			this.hideNotify();
			this.showGui();
			if (arg.length > 0)
				this.kanaal0 = arg[0].Kanaal;
			for (var i = 0; i < arg.length; ++i)
				this.monitors[arg[i].Kanaal].updateMonitorInfo(arg[i]);

			for (var i = 0; i < arg.length; ++i) {
				var monitor = arg[i];
				for (var j = 0; j < monitor.Cameras.length; ++j) {
					var cam = monitor.Cameras[j];
					if (cam.SoundID != 0) {
						this.audioinfo = cam;
						if (this.soundPlayLink != null)
							this.soundPlayLink.style.display = "block";
					}
				}
			}
		}
		catch (err) { }
	},
	audiolinkInited: false,
	audioLinkStateChanged: function(state) {
		if (!this.audiolinkInited) {
			this.audiolinkInited = true;
			return;
		}
		if (state) {
			if (this.audioinfo.CameraID != 0) {
				var streamInfo = new ActiveXObject("SVActiveX.StreamInfoEx");
				streamInfo.ID = this.primarySession.CameraIDFromOriginal(this.audioinfo.CameraID);
				streamInfo.ProfileID = 0;
				streamInfo.StreamSize = 0;
				this.audioStreamSession.StartCameraSessionEx(streamInfo);
			}
			if (this.audioinfo.soundID != 0) {
				if (this.audioPlayer != null) {
					this.audioPlayer.Create(this.monitors[this.kanaal0].videoWindow.WindowHandle, 44100);
					this.audioStreamSession.StartSoundEx(this.audioinfo.SoundID, 0, 0, 0);
				}
			}
		} else {
			this.audioStreamSession.Disconnect();
			this.audioPlayer.Reset();
		}
	},
	ps_loggedIn: function() {

	},
	ps_loginFailed: function() {
		this.notifyStateMsg(svstatemsg.connectfailed);
	},
	ps_sessionFailed: function() {
		this.notifyStateMsg(svstatemsg.connectfailed);
	},
	ps_SocketError: function() {
		this.notifyStateMsg(svstatemsg.connectfailed);
	},
	ps_ServiceAdded: function(serviceID) {
		var service = this.primarySession.GetServiceInfo(serviceID);
		if (service.ServiceType == 3) {
			this.soundOutID = service.ID;
			if (this.soundButtonLink != null)
				this.soundButtonLink.style.display = "block";
		}
	},
	ps_camerasReceived: function() {
		this.notifyStateMsg(svstatemsg.getmonitors);
		var tmpresult = "camerainfos";
		for (var i = 1; i <= this.primarySession.Cameras.Count; i++) {
			var cam = this.primarySession.Cameras(i);
			tmpresult += "|" + this.primarySession.CameraIDToOriginal(cam.ID) + "|" + cam.Description + "|" + cam.SoundID;
		}
		var This = this;
		PortalWebService.HaalMonitors(this.moduleIdInhoud, tmpresult, this.deviceID, function(arg) { This.haalMonitorSuccess(arg) }, null, null);
	},
	audio_SoundArrived: function(kanaal) {
		try {
			var soundData = this.audioStreamSession.GetSoundData();
			if (!this.soundPlayLink.state) return;
			this.audioPlayer.Play(soundData);
		} catch (err) { }
	},
	connectToGateway: function(connectie) {
		this.soundServiceID = null;
		var connectInfo = new ActiveXObject("SVActiveX.ConnectionInfo");
		connectInfo.Username = connectie.Gebruikersnaam;
		connectInfo.Password = connectie.Wachtwoord;
		connectInfo.PrimaryPort = connectie.Poort;
		connectInfo.PrimaryIP = connectie.Adres;
		if (connectie.GebruikProxy) {
			connectInfo.UseProxy = 1;
			connectInfo.ProxyIP = connectie.ProxyAdres;
			connectInfo.ProxyPort = connectie.ProxyPoort;
		}

		if (this.primarySession != null)
			this.primarySession.ConnectionInfo = connectInfo;
	},
	cameraAvailable: function(cameraID) {
		if (this.primarySession != null) {
			for (var i = 1; i <= this.primarySession.Cameras.Count; ++i) {
				try {
					if (this.primarySession.Cameras(i).ID == this.primarySession.CameraIdFromOriginal(cameraID))
						return true;
				} catch (err) { }
			}
		}
		return false;
	},
	toonBesturing: function(cameraID, kanaal) {
		if (!this.monitors[kanaal])
			return;
		this.monitors[kanaal].toonBesturing(cameraID);
	},
	viewVideo: function(cameraID, titel, kanaal) {
		this.monitors[kanaal].viewVideo(cameraID, titel);
	},
	unload: function() {
		for (var kanalen in this.monitors) {
			this.monitors[kanalen].unload();
		}
		this.primarySession.Disconnect();
	}
}