
function onUpdateLight(updateLight) {
	for (var i = 0; i < lightArr.length; i++) {

		var light = lightArr[i];

		// search light from cache by mac address
		if (light.id === updateLight.id) {
			var updated = false;
			light.updateId = updateLight.updateId;
			light.available = updateLight.available;

			if (typeof(updateLight.name) !== undefined) {
				if (light.name !== updateLight.name) {
					light.name = updateLight.name;
					updated = true;
				}
			}

			if (typeof(updateLight.on) !== undefined) {
				if (light.on !== updateLight.on) {
					light.on = updateLight.on;
					updated = true;
				}
			}

			if (typeof(updateLight.level) !== undefined) {
				if (light.level !== updateLight.level) {
					light.level = updateLight.level;
					mapLevelToPercent(light);
					updated = true;
				}
			}					

			if (typeof(updateLight.hue) !== undefined) {
				if (light.hue !== updateLight.hue) {
					light.hue = updateLight.hue;
					updated = true;
				}
			}

			if (typeof(updateLight.sat) !== undefined) {
				if (light.sat !== updateLight.sat) {
					light.sat = updateLight.sat;
					mapSatToPercent(light);
					updated = true;
				}
			}

			if (light === curEdit.obj && updated) {
				curEdit.on = light.on;
				curEdit.hue = light.hue;
				curEdit.level = light.level;
				curEdit.levelPercent = light.levelPercent;
				curEdit.sat = light.sat;
				curEdit.satPercent = light.satPercent;
				lightEditSetHue(light.hue);

				// force render edit page
				devNameLabel.value = light.name;
				renderLevel();
				renderSat();
				renderHue();
				editNeedRender = true;
			}

			if (updated) {
				updateDeviceListUi();
			}
			return;
		}
	}
};

function listenToServerEvents() {
	if (typeof(EventSource) !== "undefined") {
		// listen for events
		var source = new EventSource("/api/0/ZLL/events");
		source.onmessage = function(event) {
	        var evObj = JSON.parse(event.data);

	        // update light event
	        if (evObj.updateLight) {
	            onUpdateLight(evObj.updateLight);
	        }
	   };
	}
	else {
	// Sorry! No server-sent events support..
	}
}