--
-- JD7RSeries
-- Specialization class for JD7RSeries
-- @Authors of original scripts used: Manuel Leithner (SFM-Modding),Modelleicher (www.schwabenmodding.bplaced.net),Templaer, JoXXer, Knagsted, Mofa-Killer, Face, Heady, other do not remember!!
-- @author  Ago-Systemtech
-- 
-- @DATE  01/08/13 ADD FIX FOR USE JD 7R SERIES, Ago-Systemtech: https://www.facebook.com/ago.systemtech (Modhoster Team)
------ free for non commercial-usage -------------

JD7RSeries = {};
function JD7RSeries.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations);
end;
function JD7RSeries:load(xmlFile)
	
	---------------------CAM INTERNA MOBILE---------------------
	self.internalCamera = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.internalCamera#index"));
	self.camPositionX = 0;
	self.camPositionZ = 0;
	self.camPositionY = 0;
		
	self.FrizioneFrenoRotation = SpecializationUtil.callSpecializationsFunction("FrizioneFrenoRotation");
	
	self.updateFuelIndicators = SpecializationUtil.callSpecializationsFunction("updateFuelIndicators");
	self.ledriserva = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.ledriserva#index"));
	self.ledriservaActive = false;
	self.riserva = 60;
	------------REALISTIC INDOOR CAM------------
	self.ric = {};
	self.ric.directionPart = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.realisticIndoorCam#directionPart"));
    ------------------ALLRAD V.4---------------------------
	self.allradState = SpecializationUtil.callSpecializationsFunction("allradState");
    self.AllradV41Active = true;
	self.wellenCount = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.Allradwellen.Wellen#count"), 0);
	self.Wellen = {}
	if self.wellenCount ~= 0 and self.wellenCount ~= nil then
	    for i=1, self.wellenCount do
	        local Welle = string.format("vehicle.Allradwellen.Welle%d", i)
		    self.Wellen[i] = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, Welle .. "#index"));
	    end;
	end;
    self.hudAllradPosX = 0.491;
    self.hudAllradPosY = 0.0910;
    self.hudAllradWidth = 0.267;
    self.hudAllradHeight = 0.038;
	self.infoPanelAllradONPath = Utils.getFilename("textur/allrad_symb_yes.png", self.baseDirectory);
	self.hudAllradONOverlay = Overlay:new("textur/allrad_symb_yes", self.infoPanelAllradONPath, self.hudAllradPosX, self.hudAllradPosY, self.hudAllradWidth, self.hudAllradHeight);
	self.infoPanelAllradOFFPath = Utils.getFilename("textur/allrad_symb_no.png", self.baseDirectory);
	self.hudAllradOFFOverlay = Overlay:new("textur/allrad_symb_no", self.infoPanelAllradOFFPath, self.hudAllradPosX, self.hudAllradPosY, self.hudAllradWidth, self.hudAllradHeight);
	self.showhudAllrad = false;
	---------------------HANDBRAKE---------------------
	self.handbrakelight = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.handbrakelight#index"));
	self.setHandBrakeState = SpecializationUtil.callSpecializationsFunction("setHandBrakeState");
	self.handBrakeHud = Overlay:new("HandbrakeOverlay", Utils.getFilename("Textur/handbrake.dds", self.baseDirectory), 0.860, 0.184, 0.1726, 0.039525); -- 0.080, 0.085
	self.handbrake = true;
	handbrakeSoundFile = Utils.getFilename("sound/handbrake.ogg", self.baseDirectory);
    self.handbrakeSoundId = createSample("handbrakeSound");
    loadSample(self.handbrakeSoundId, handbrakeSoundFile, false);
    self.handbrakePlaying = false;
	brakeSoundFile = Utils.getFilename("sound/compressedAir.ogg", self.baseDirectory);
    self.brakeSoundId = createSample("brakeSound");
    loadSample(self.brakeSoundId, brakeSoundFile, false);
    self.brakePlaying = false;
	brakereleaseSoundFile = Utils.getFilename("sound/brake.ogg", self.baseDirectory);
    self.brakereleaseSoundId = createSample("brakereleaseSound");
    loadSample(self.brakereleaseSoundId, brakereleaseSoundFile, false);
	self.brakereleasePlaying = false;
    self.BreakForceVal = 10000/self.motor.brakeForce;
    self.HandBrakeTurnOff = false;
	
	--------------------Sound Inversore-------------------
	InversoreDirectionSoundFile = Utils.getFilename("sound/gearShift.wav", self.baseDirectory);
	self.InversoreDirectionSoundId = createSample("InversoreDirectionSound");
    loadSample(self.InversoreDirectionSoundId, InversoreDirectionSoundFile, false);
    self.InversoreDirectionPlaying = false;
	-------------------------HYDRAULIC-----------------------
	self.frontAttacherJoint = {};
	self.frontAttacherJoint.node = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.trailerAttacherJoints#front"));
	self.moveDownIntervall = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.moveDownIntervall#ms"), 1000);
	self.updateJoint = false;
	self.doLowering = false;
	self.loweringDone = false;
	self.nextAction = false;
	self.delay = 0;
	self.implementCount = 0;
	----------------------- FRONT WIPER ANIMATION---------------------
	local wiperFrontAnimRootNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.wiperFront#rootNode"));
	self.wiperFrontAnimCharSet = 0;
	if wiperFrontAnimRootNode ~= nil and wiperFrontAnimRootNode ~= 0 then
		self.wiperFrontAnimCharSet = getAnimCharacterSet(wiperFrontAnimRootNode);
		if self.wiperFrontAnimCharSet ~= 0 then
			local clip = getAnimClipIndex(self.wiperFrontAnimCharSet, getXMLString(xmlFile, "vehicle.wiperFront#clip"));
			assignAnimTrackClip(self.wiperFrontAnimCharSet, 0, clip);
			setAnimTrackLoopState(self.wiperFrontAnimCharSet, 0, true);
			local wiperFrontAnimSpeedScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.wiperFront#speedScale"), 1);
			setAnimTrackSpeedScale(self.wiperFrontAnimCharSet, 0, wiperFrontAnimSpeedScale);
			self.wiperFrontAnimDuration = getAnimClipDuration(self.wiperFrontAnimCharSet, clip);
		end;
	end;
	self.iswiperFrontActive = false;
	self.finishwiperFront = true;
	--------------------------REAR WIPER ANIMATION----------------------
	local wiperBackAnimRootNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.wiperBack#rootNode"));
	self.wiperBackAnimCharSet = 0;
	if wiperBackAnimRootNode ~= nil and wiperBackAnimRootNode ~= 0 then
		self.wiperBackAnimCharSet = getAnimCharacterSet(wiperBackAnimRootNode);
		if self.wiperBackAnimCharSet ~= 0 then
			local clip = getAnimClipIndex(self.wiperBackAnimCharSet, getXMLString(xmlFile, "vehicle.wiperBack#clip"));
			assignAnimTrackClip(self.wiperBackAnimCharSet, 0, clip);
			setAnimTrackLoopState(self.wiperBackAnimCharSet, 0, true);
			local wiperBackAnimSpeedScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.wiperBack#speedScale"), 1);
			setAnimTrackSpeedScale(self.wiperBackAnimCharSet, 0, wiperBackAnimSpeedScale);
			self.wiperBackAnimDuration = getAnimClipDuration(self.wiperBackAnimCharSet, clip);
		end;
	end;
	self.iswiperBackActive = false;
	self.finishwiperBack = true;
	-------------------------PEDALI-------------------------
	local PedaleGasNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.PedaleGas#index"));
    if PedaleGasNode ~= nil then
        self.PedaleGas = {};
        self.PedaleGas.node = PedaleGasNode;
		self.PedaleGas.maxSpeed = getXMLInt(xmlFile, "vehicle.PedaleGas#maxSpeed");
		local x1,y1,z1 = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.PedaleGas#minRot"));
		local x2,y2,z2 = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.PedaleGas#maxRot"));
		self.PedaleGas.rotMin = {math.rad(Utils.getNoNil(x1,0)),math.rad(Utils.getNoNil(y1,0)),math.rad(Utils.getNoNil(z1,0))};
		self.PedaleGas.rotMax = {math.rad(Utils.getNoNil(x2,0)),math.rad(Utils.getNoNil(y2,0)),math.rad(Utils.getNoNil(z2,0))};
    end;
	
	self.PedaleFrizione = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.PedaleFrizione#index"));
	self.PedaleFreno = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.PedaleFreno#index"));
	
	-------------------------- LEVE ----------------------
	self.levaindicatori = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.levaindicatori#index"));
	self.LevaHandbrake = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.LevaHandbrake#index"));
	self.handThrottle = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.handThrottle#index"));
  
	--------------------------LED-------------------------
	self.batteriaicona = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.batteriaicona#index"));
	self.olioicona = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.olioicona#index"));
	self.tachiicona = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.tachiicona#index"));
	self.oilGropuicona = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.oilGropuicona#index"));
    self.LedHazard = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.LedHazard#index"));
    self.ledLampeggiante = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.ledLampeggiante#index"));
	self.LedStart = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.LedStart#index"));
	self.Hire = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.Hire#index"));
	self.Green = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.Green#index"));
	self.quadroOFF = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.quadroOFF#index"));
	self.quadroOFF2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.quadroOFF2#index"));
	self.ledFrontwork = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.ledFrontwork#index"));
	self.ledRearwork = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.ledRearwork#index"));
    self.led4WDon = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.Led4WDon#index"));
    self.led4WDoff = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.Led4WDoff#index"));
	self.led4WDoff2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.Led4WDoff2#index"));
	self.LedBraccio = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.LedBraccio#index"));
	self.PTOLed = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.PTOLed#index"));
	
	self.frontled = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.frontled#index"));
	self.reverseled = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.reverseled#index"));
	------------------ SWITCHES---------------
	self.numSwitches = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.switches#count"),0);
	self.switch = {};
	for i=1, self.numSwitches do
		local objname = string.format("vehicle.switches.switch" .. "%d", i);
		self.switch[i] = {};
		self.switch[i] = Utils.indexToObject(self.components, getXMLString(xmlFile, objname .. "#index"));
	end;
	----------------- GASOLIO INDICATORI----------
	self.fuelIndicatorsGroup = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.fuelIndicators#index"));
	self.numFuelIndicators = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.fuelIndicators#count"), 0);
	self.fuelIndicators = {};
    for i=1, self.numFuelIndicators do
        local objname = string.format("vehicle.fuelIndicators.fuelIndicator" .. "%d", i);
		self.fuelIndicators[i] = {};
        self.fuelIndicators[i].rotNode = Utils.indexToObject(self.components, getXMLString(xmlFile, objname .. "#rotNode"));
		setVisibility(self.fuelIndicators[i].rotNode,true);
    end;
	----------------- ROTORE LAMPEGGIANTE----------
	self.RotoreLampe1 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.RotoreLampe1#index"));
	self.RotoreLampe2 = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.RotoreLampe2#index"));
	--------------------PARAFANGHI------------------
	self.fender = {};
	self.fender.leftNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.fender#leftIndex"));
	self.fender.rightNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.fender#rightIndex"));
	self.fender.leftRotMax = getXMLInt(xmlFile, "vehicle.fender#leftRotMax");
	self.fender.rightRotMax = getXMLInt(xmlFile, "vehicle.fender#rightRotMax");   

   --------------------  hide fender------------
	self.setFenderVisibility = SpecializationUtil.callSpecializationsFunction("setFenderVisibility");
	self.fenders = {};
	self.fenders.rear = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.fenders#index"));
	
	---------------------WHEELSTERING----------------
	self.updateInterval = 0;
	self.steeringWheels = {};
	if table.getn(self.wheels) > 0 then
		local numSteeringWheels = Utils.getNoNil(getXMLInt(xmlFile, "vehicle.steeringWheels#count"), 0);
		for i=1, numSteeringWheels do
			local wheelnamei = string.format("vehicle.steeringWheels.wheel" .. "%d", i);
			local wheelNumber = getXMLInt(xmlFile, wheelnamei.."#wheelNumber");
			if wheelNumber ~= 0 and wheelNumber ~= nil and self.wheels[wheelNumber] ~= nil then
				local entry = {};
				entry.wheelNumber = wheelNumber;
				local maxFallRotation = unpack(Utils.getRadiansFromString(getXMLString(xmlFile, wheelnamei.."#maxFallRotation"), 1));
				entry.factor = maxFallRotation/self.wheels[wheelNumber].rotMax;
				self.steeringWheels[i] = entry;
			end;
		end;
	end;
	 --------------------------GIUNTI ASSALE------------------------
	self.giuntoDestro = {};
	self.giuntoDestro.node = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.giuntoDestro#index"));
	self.giuntoDestro.speedFactor = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.giuntoDestro#speedFactor"), 2);
	self.giuntoSinistro = {};
	self.giuntoSinistro.node = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.giuntoSinistro#index"));
	self.giuntoSinistro.speedFactor = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.giuntoSinistro#speedFactor"), 2);
	-----------------SOUND RISERVA------------------
    fuelwarningSoundFile = Utils.getFilename("sound/fuelwarning.wav", self.baseDirectory);
    self.fuelwarningSoundId = createSample("fuelwarningSound");
    loadSample(self.fuelwarningSoundId, fuelwarningSoundFile, false);
    self.fuelwarningPlaying = false;
	self.playedSound = false;

	
end;
function JD7RSeries:delete()
    if self.hudAllradONOverlay ~= nil or self.hudAllradOFFOverlay ~= nil then
		self.hudAllradONOverlay:delete();
		self.hudAllradOFFOverlay:delete();
	end;
end;
function JD7RSeries:readStream(streamId, connection)
		self:allradState(streamReadBool(streamId), true);
end;
function JD7RSeries:writeStream(streamId, connection)
	streamWriteBool(streamId, self.AllradV41Active);
end;
function JD7RSeries:readUpdateStream(streamId, timestamp, connection)
	if connection:getIsServer() then
		if streamReadBool(streamId) then
		end;
	end;
end;
function JD7RSeries:writeUpdateStream(streamId, connection, dirtyMask)
	if not connection:getIsServer() then
		if streamWriteBool(streamId, bitAND(dirtyMask, self.vehicleDirtyFlag) ~= 0) then
        end;
    end;
end;
function JD7RSeries:mouseEvent(posX, posY, isDown, isUp, button)
end;

function JD7RSeries:setFenderVisibility(isVisible)
	setVisibility(self.fenders.rear, isVisible);
end;
function JD7RSeries:keyEvent(unicode, sym, modifier, isDown)
	-------------------------HANDBRAKE---------------------------
   if isDown and sym == Input.KEY_y then
        self:setHandBrakeState(not self.handbrake);
		if self.handbrake and self:getIsActiveForSound() then
			playSample(self.handbrakeSoundId,1,1,0);
		end;
	end;
	
	
end;
function JD7RSeries:allradState(state, noEventSend)
    AllradStateEvent.sendEvent(self, state, noEventSend);
    self.AllradV41Active = state;
end;

function JD7RSeries:FrizioneFrenoRotation(dt, acceleration)
	if self.PedaleFrizione ~= nil then
		local FrizioneActive = false;
		if acceleration > 0 then
			FrizioneActive = true;
		end;

		local FrizioneMax = {};
		FrizioneMax[1] = math.rad(-52);
		FrizioneMax[2] = math.rad(0);
		FrizioneMax[3] = math.rad(0);
		local FrizioneRotationTime = 200;

		local FrizioneMin = {};
		FrizioneMin[1] = math.rad(-30);
		FrizioneMin[2] = math.rad(0);
		FrizioneMin[3] = math.rad(0);

		local x, y, z = getRotation(self.PedaleFrizione);
		local rot = {x,y,z};
		local newRot = Utils.getMovedLimitedValues(rot, FrizioneMin, FrizioneMax, 3, FrizioneRotationTime, dt, FrizioneActive);
		setRotation(self.PedaleFrizione, unpack(newRot));
	end;

	if self.PedaleFreno ~= nil then
		local brakeActive = false;
		if acceleration > 0 then
			brakeActive = true;
		end;

		local brakeMax = {};
		brakeMax[1] = math.rad(-22);
		brakeMax[2] = math.rad(0);
		brakeMax[3] = math.rad(0);
		local brakeRotationTime = 500;

		local brakeMin = {};
		brakeMin[1] = math.rad(0);
		brakeMin[2] = math.rad(0);
		brakeMin[3] = math.rad(0);

		local x, y, z = getRotation(self.PedaleFreno);
		local rot = {x,y,z};
		local newRot = Utils.getMovedLimitedValues(rot, brakeMin, brakeMax, 3, brakeRotationTime, dt, brakeActive);
		setRotation(self.PedaleFreno, unpack(newRot));
	end;
end;


function JD7RSeries:update(dt)
	-------------LIFT-HIDRO----------------
	if self:getIsActive() then
		----------------PARAFANGHI-------------------------
		local x1,y1,z1 = getRotation(self.wheels[1].repr);
		if y1 < math.rad(self.fender.rightRotMax) then
			setRotation(self.fender.rightNode, 0, math.rad(7), 0);
		else
			setRotation(self.fender.rightNode, 0, 0, 0);
		end;
		local x2,y2,z2 = getRotation(self.wheels[2].repr);
		if y2 > math.rad(self.fender.leftRotMax) then
			setRotation(self.fender.leftNode, 0, math.rad(-7), 0);
		else
			setRotation(self.fender.leftNode, 0, 0, 0);
		end;
   	
     ------------------LAMPEGGIANTI------------------
	    if self.beaconLightsActive then
			rotate(self.RotoreLampe1, 0, self.beaconLights[1].speed*dt, 0);
			rotate(self.RotoreLampe2, 0, self.beaconLights[2].speed*dt, 0);
		end;
		
	--------------------------GIUNTI ASSALE------------------------
		local x,y,z = getRotation(self.wheels[1].driveNode);
		setRotation(self.giuntoDestro.node, 0 ,0, x*self.giuntoDestro.speedFactor);
		local x,y,z = getRotation(self.wheels[1].driveNode);
		setRotation(self.giuntoSinistro.node, 0 ,0, x*self.giuntoSinistro.speedFactor);
		
		
		if self:getIsActive() then
		for _, part in pairs(self.movingParts) do
			Cylindered.setDirty(self, part);
		end;
	end;
	end;

	------------------LED RISERVA----------------------
	if self.isEntered then
		if self.fuelFillLevel < 60 then
			self.riserva = self.riserva - dt;
			if self.playedSound == false then
				playSample(self.fuelwarningSoundId,1,1,0);
				self.playedSound = true;
			end;
			self.ledriservaActive = true;
		else
			self.playedSound = false;
			self.ledriservaActive = false;
		end;
		setVisibility(self.ledriserva,self.ledriservaActive);
		self:updateFuelIndicators();
	end;
	 ----------------------HANDBRAKE--------------------
		if self:getIsActive() then
		if Input.isKeyPressed(Input.KEY_s) then
				if not self.braking then
					self.braking = true;
				end;
				if not self.brakePlaying and self:getIsActiveForSound() then
					playSample(self.brakeSoundId,1,1,0);
					self.brakePlaying = true;
				end;
				self.brakereleasePlaying = false;
		else
			self.brakePlaying = false;
			self.braking = false;
			if not self.brakereleasePlaying and self:getIsActiveForSound() then
				playSample(self.brakereleaseSoundId,1,1,0);
				self.brakereleasePlaying = true;
			end;
		end;
	end;
	
	
	---------------------CAM INTERNA MOBILE---------------------
     if self.camIndex == 1 then
	 if self:getIsActive() then
		if InputBinding.isPressed(InputBinding.MOVECAMLEFT2) then
			self.camPositionX = self.camPositionX + 0.03;
			if self.camPositionX >= 0.3 then
				self.camPositionX = 0.3;
			end;
		end;
		if InputBinding.isPressed(InputBinding.MOVECAMRIGHT2) then
			self.camPositionX = self.camPositionX - 0.03;
			if self.camPositionX <= -0.3 then
				self.camPositionX = -0.3;
			end;
		end;
		if InputBinding.isPressed(InputBinding.MOVECAMFORWARD2) then
			self.camPositionZ = self.camPositionZ + 0.03;
			if self.camPositionZ >= 0.3 then
				self.camPositionZ = 0.3;
			end;
		end;
				if InputBinding.isPressed(InputBinding.MOVECAMBACK2) then
			self.camPositionZ = self.camPositionZ - 0.03;
			if self.camPositionZ <= -0.22 then
				self.camPositionZ = -0.22;
			end;
		end;
		if Input.isMouseButtonPressed(Input.MOUSE_BUTTON_WHEEL_UP) then
			self.camPositionY = self.camPositionY + 0.02;
			if self.camPositionY >= 0.15 then
				self.camPositionY = 0.15;
			end;
		end;
		if Input.isMouseButtonPressed(Input.MOUSE_BUTTON_WHEEL_DOWN) then
			self.camPositionY = self.camPositionY - 0.02;
			if self.camPositionY <= -0.2 then
				self.camPositionY = -0.2;
			end;
		end;
		if Input.isKeyPressed(Input.KEY_z) then
			self.camPositionX = 0;
			self.camPositionZ = 0;
			self.camPositionY = 0;
		end;
		if self.internalCamera ~= nil then
			setTranslation(self.internalCamera, self.camPositionX, self.camPositionZ, self.camPositionY);
		end;
   	end;
	end;
	--------------REALISTIC INDOOR CAM------------------------
	if self:getIsActive() then
			local ax, ay, az = getWorldTranslation(self.ric.directionPart);
			local bx = 0;
			local by = 1100000;
			local bz = 0;
			x, y, z = worldDirectionToLocal(getParent(self.ric.directionPart), bx-ax, by-ay, bz-az);
			setDirection(self.ric.directionPart, x, y, z, 0, 0, 1);

	end;
	------------------ALLRAD V.4---------------------------
	 if self.isClient and self:getIsActiveForInput(false) and not self:hasInputConflictWithSelection() then
		if InputBinding.hasEvent(InputBinding.AllradV41) then
		  self:allradState(not self.AllradV41Active);
		end;
    end;
	if self:getIsActive() then
   		if self.AllradV41Active == true then
		    self.showhudAllrad = true;
			setVisibility(self.led4WDon, true);
            setVisibility(self.led4WDoff, false);
            setVisibility(self.led4WDoff2, false);
			self.wheels[1].driveMode =2
		 	self.wheels[2].driveMode =2
		 	self.wheels[3].driveMode =2
		 	self.wheels[4].driveMode =2
		else
			self.showhudAllrad = false;
			setVisibility(self.led4WDon, false);
			setVisibility(self.led4WDoff, true);
			setVisibility(self.led4WDoff2, true);
		 	self.wheels[1].driveMode =0
			self.wheels[2].driveMode =0
			self.wheels[3].driveMode =2
			self.wheels[4].driveMode =2
		end;
    end;
	if self:getIsActive() then
		if self.isHired == true then
			setVisibility(self.Hire, true);
			setVisibility(self.Green, false);
		else
			setVisibility(self.Hire, false);
			setVisibility(self.Green, true);
		end;
	end;
	---------WHEELSTERING----------------
	if not self.startedUpdating then
		self.updateInterval = self.time+10;
		self.startedUpdating = true;
	end;
	if self:getIsActive() and self.updateInterval <= self.time then
		for k, wheel in pairs(self.wheels) do
			for c, steeringWheel in pairs(self.steeringWheels) do
				if k == steeringWheel.wheelNumber then
					local steeringAngle = wheel.steeringAngle;
					local x,y,z = getRotation(wheel.repr);
					local xDrive,yDrive,zDrive;
					if wheel.repr == wheel.driveNode then
						xDrive,yDrive,zDrive = x,y,z;
					else
						xDrive,yDrive,zDrive = getRotation(wheel.driveNode);
					end;
					local zFallRotation = -(steeringAngle*steeringWheel.factor);
					if wheel.repr == wheel.driveNode then
						setRotation(wheel.repr, xDrive, steeringAngle, zFallRotation);
					else
						setRotation(wheel.repr, x, steeringAngle, zFallRotation);
						setRotation(wheel.driveNode, xDrive, yDrive, zDrive);
					end;
				end;
			end;
		end;
		self.updateInterval = self.time+10;
	end;

	
end;
function JD7RSeries:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
    return BaseMission.VEHICLE_LOAD_OK;
end;
function JD7RSeries:updateTick(dt)
    if self:getIsActive() then
		if self.isMotorStarted then
			setVisibility(self.batteriaicona, false);
			setVisibility(self.olioicona, false);
			setVisibility(self.tachiicona, true);
		    setVisibility(self.oilGropuicona, true);
			setVisibility(self.LedStart, true);
			setVisibility(self.quadroOFF, true);
			setVisibility(self.quadroOFF2, false);
			setVisibility(self.fuelIndicatorsGroup, true);
			setVisibility(self.LedBraccio, true);
		else
			setVisibility(self.batteriaicona, true);
			setVisibility(self.olioicona, true);
			setVisibility(self.tachiicona, false);
			 setVisibility(self.oilGropuicona, false);
			setVisibility(self.LedStart, false);
		    setVisibility(self.quadroOFF, false);
			setVisibility(self.quadroOFF2, true);
			setVisibility(self.fuelIndicatorsGroup, false);
			setVisibility(self.LedBraccio, false);
		end;
		for k, implement in pairs(self.attachedImplements) do
				if implement.object ~= nil then
					if implement.object.isTurnedOn then
						setVisibility(self.PTOLed, true);
					else
						setVisibility(self.PTOLed, false);
					end;
				end;				
		end;
		---------------------PEDALI--------------------------------
		
			 if self.PedaleGas ~= nil then
				local percent = (self.lastSpeed*self.speedDisplayScale*3600) / self.PedaleGas.maxSpeed;
				local minRot = self.PedaleGas.rotMin;
				local maxRot = self.PedaleGas.rotMax;
				local x = minRot[1] + (maxRot[1] - minRot[1]) * percent;
				local y = minRot[2] + (maxRot[2] - minRot[2]) * percent;
				local z = minRot[3] + (maxRot[3] - minRot[3]) * percent;
				setRotation(self.PedaleGas.node, x, y, z);
	        end;
				
	self:FrizioneFrenoRotation(dt, acceleration);
	end;


	
	----------- WIPERS -----------------
	if self.isMotorStarted then
		if not self.finishwiperFront then
			if getAnimTrackTime(self.wiperFrontAnimCharSet, 0) % self.wiperFrontAnimDuration <= 100 then
				setAnimTrackTime(self.wiperFrontAnimCharSet, 0, 0.0);
				disableAnimTrack(self.wiperFrontAnimCharSet, 0);
				self.finishwiperFront = true;
			end;
		end;
		if g_currentMission.environment.lastRainScale > 0.1 and g_currentMission.environment.timeSinceLastRain < 30 then
			if not self.iswiperFrontActive then
				enableAnimTrack(self.wiperFrontAnimCharSet, 0);
				self.iswiperFrontActive = true;
			end;
		else
			if self.iswiperFrontActive then
				self.iswiperFrontActive = false;
				self.finishwiperFront = false;
			end;
		end;
		
		if not self.finishwiperBack then
			if getAnimTrackTime(self.wiperBackAnimCharSet, 0) % self.wiperBackAnimDuration <= 100 then
				setAnimTrackTime(self.wiperBackAnimCharSet, 0, 0.0);
				disableAnimTrack(self.wiperBackAnimCharSet, 0);
				self.finishwiperBack = true;
			end;
		end;
		if g_currentMission.environment.lastRainScale > 0.1 and g_currentMission.environment.timeSinceLastRain < 30 then
			if not self.iswiperBackActive then
				enableAnimTrack(self.wiperBackAnimCharSet, 0);
				self.iswiperBackActive = true;
			end;
		else
			if self.iswiperBackActive then
				self.iswiperBackActive = false;
				self.finishwiperBack = false;
			end;
		end;
		for _, part in pairs(self.movingParts) do
			part.isDirty = true;
		end;
	end;
	--------------------SWITCH------------------------------
	-- if self.switch[1] ~= nil then
		-- if self.B3.wl then
			-- setRotation(self.switch[1], math.rad(0), 0, 0);
			-- setVisibility(self.LedHazard, true);
		-- else
			-- setRotation(self.switch[1],math.rad(180), 0, 0);
			-- setVisibility(self.LedHazard, false);
		-- end;
	-- end;
	if self.switch[1] ~= nil then
		if self.isMotorStarted then
			setRotation(self.switch[1], math.rad(0), math.rad(0), math.rad(-60));
		else
			setRotation(self.switch[1], math.rad(0), math.rad(0), math.rad(0));
		end;
	end;
	if self.handbrakelight ~= nil then
		if self.handbrake then
			setVisibility(self.handbrakelight, true);
		else
			setVisibility(self.handbrakelight, false);
		end;
	end
	if self.ledFrontwork ~= nil then
		 local i = 1
		 if self.B3.work[i].a then
			setVisibility(self.ledFrontwork, true);
		else
			setVisibility(self.ledFrontwork, false);
		end;
	end;
	if self.ledRearwork ~= nil then
		 local i = 2
		 if self.B3.work[i].a then
			setVisibility(self.ledRearwork, true);
		else
			setVisibility(self.ledRearwork, false);
		end;
	end;
	    --------- Levers rotations--------------
	if self.levaindicatori ~= nil then
		if not self.B3.wl then
			if self.B3.dirRight[1].a then
				setRotation(self.levaindicatori, 0, math.rad(-20), math.rad(0));
			elseif self.B3.dirLeft[1].a then
				setRotation(self.levaindicatori, 0, math.rad(20), math.rad(0));
			else
				setRotation(self.levaindicatori, 0, 0, math.rad(0));
			end;
		else
			setRotation(self.levaindicatori, 0, 0, math.rad(0));
		end;
	end
	if self.LevaHandbrake ~= nil then
		if self.handbrake then
			setTranslation(self.LevaHandbrake, 0, 0.03159, math.abs(0));
		  else
			setTranslation(self.LevaHandbrake, 0, 0.03159,  math.abs(0.02743));
		    if self.InversoreDirection == 1 then		    
			setTranslation(self.LevaHandbrake, -0.01908, 0.03159,  math.abs(0.02834));
		else
			setTranslation(self.LevaHandbrake, -0.01908, 0.03159,  math.abs(0.00198));
			end;
		 end;	
	end;
 	if self.handThrottle ~= nil then
		setRotation(self.handThrottle,  Utils.degToRad(self.handThrottlePercentage * 65),0,0);
	end;

	
	if self.LucePorta ~= nil and self.doorIObject ~= nil then
		setVisibility(self.LucePorta, self.doorIObject.isOpen);
	end;
	if self.ledLampeggiante ~= nil then
		 if self.beaconLightsActive then
		    setVisibility(self.ledLampeggiante, true);
		 else
		   setVisibility(self.ledLampeggiante, false);
		end;
	end;
	-------------------HANDBRAKE-----------------
	 	if self.isServer then
        if self.handbrake then
            if self.isServer then
                for k,wheel in pairs(self.wheels) do
                    setWheelShapeProps(wheel.node, wheel.wheelShape, 0, 999, 0);
                end;
            end;
        elseif not self.handbrake and self.HandBrakeTurnOff then
            if self.isServer then
                for k,wheel in pairs(self.wheels) do
                    setWheelShapeProps(wheel.node, wheel.wheelShape, 0, 0, 0);
                end;
            end;
            self.HandBrakeTurnOff = false;
        end;
    end;
end;


function JD7RSeries:setHandBrakeState(state, noEventSend)
HandbrakeEvent.sendEvent(self, state, noEventSend); -- MP Fix by modelleicher, addet Event
    self.handbrake = state;
    self.HandBrakeTurnOff = state;
    setVisibility(self.handbrakelight, state);
end;
function JD7RSeries:updateFuelIndicators()
	local amountOfFuelPerIndicator = self.fuelCapacity/11;
	local timesToIterate = self.fuelFillLevel/amountOfFuelPerIndicator;
	timesToIterate = math.floor(timesToIterate);
	if self.oldTimesToIterate ~= timesToIterate then
		for i=1, self.numFuelIndicators do
			setVisibility(self.fuelIndicators[i].rotNode, false);
		end;
		for i=1, timesToIterate do
			setVisibility(self.fuelIndicators[i].rotNode, true);
		end;
	end;
	self.oldTimesToIterate = timesToIterate;
end;
function JD7RSeries:draw()

	if self.isEntered then
		if self.handbrake then
			if Input.isKeyPressed(Input.KEY_w) then
				self.handBrakeHud:render();
			end;
		self.handBrakeHud:render();
		end;
	end;
	if self.isEntered then
		if self.handbrake then
			if Input.isKeyPressed(Input.KEY_w) then
				g_currentMission:addWarning(g_i18n:getText("handbrakeRELEASE"), 0.015, 0.030);
			end;
		end;
	end;
	if self.isEntered then
		if self.handbrake then
			if Input.isKeyPressed(Input.KEY_s) then
				g_currentMission:addWarning(g_i18n:getText("handbrakeRELEASE"), 0.015, 0.030);
			end;
		end;
	end;
	------------------ALLRAD V.4---------------------------
	if self.showhudAllrad == true then
      	self.hudAllradONOverlay:render();
		g_currentMission:addHelpButtonText(g_i18n:getText("AllradOFF"), InputBinding.AllradV41);
	else
		g_currentMission:addHelpButtonText(g_i18n:getText("AllradON"), InputBinding.AllradV41);
	    self.hudAllradOFFOverlay:render();
   end;
end;


function JD7RSeries:onEnter()
        if self.isMotorStarted then
			setVisibility(self.batteriaicona, false);
			setVisibility(self.olioicona, false);
			setVisibility(self.tachiicona, true);
			 setVisibility(self.oilGropuicona, true);
			setVisibility(self.LedStart, true);
			setVisibility(self.LedBraccio, true);
			setVisibility(self.quadroOFF, true);
			setVisibility(self.quadroOFF2, false);
		else
			setVisibility(self.batteriaicona, true);
			setVisibility(self.olioicona, true);
			setVisibility(self.tachiicona, false);
			 setVisibility(self.oilGropuicona, false);
			setVisibility(self.LedStart, false);
			setVisibility(self.LedBraccio, false);
		    setVisibility(self.quadroOFF, false);
			 setVisibility(self.quadroOFF2, true);
		end
	if self.iswiperFrontActive then
		enableAnimTrack(self.wiperFrontAnimCharSet, 0);
	end;
		if self.iswiperBackActive then
		enableAnimTrack(self.wiperBackAnimCharSet, 0);
	end;
	if self.interactiveObjects[4].animation.animCharSet ~= 0 then
		if getAnimTrackTime(self.interactiveObjects[4].animation.animCharSet, 0) < 0.0 then
		setAnimTrackTime(self.interactiveObjects[4].animation.animCharSet, 0, 0.0);
		end;
		setAnimTrackSpeedScale(self.interactiveObjects[4].animation.animCharSet, 0, self.interactiveObjects[4].animation.animSpeedScale);
		enableAnimTrack(self.interactiveObjects[4].animation.animCharSet, 0);
	end;
	
end;
function JD7RSeries:onLeave()
	    if self.isMotorStarted then
			setVisibility(self.batteriaicona, false);
			setVisibility(self.olioicona, false);
			setVisibility(self.tachiicona, true);
			 setVisibility(self.oilGropuicona, true);
			setVisibility(self.LedStart, true);
			setVisibility(self.quadroOFF, true);
			setVisibility(self.quadroOFF2, false);
			setVisibility(self.LedBraccio, true);
		else
			setVisibility(self.batteriaicona, true);
			setVisibility(self.olioicona, true);
			setVisibility(self.tachiicona, false);
			 setVisibility(self.oilGropuicona, false);
			setVisibility(self.LedStart, false);
			setVisibility(self.quadroOFF, false);
			setVisibility(self.quadroOFF2, true);
			setVisibility(self.LedBraccio, false);
	     end
	if self.iswiperBackActive then
		disableAnimTrack(self.wiperBackAnimCharSet, 0);
	end;
	    if self.iswiperFrontActive then
		disableAnimTrack(self.wiperFrontAnimCharSet, 0);
	end;
	if self.interactiveObjects[4].animation.animCharSet ~= 0 then
		if getAnimTrackTime(self.interactiveObjects[4].animation.animCharSet, 0) > self.interactiveObjects[4].animation.animDuration then
		setAnimTrackTime(self.interactiveObjects[4].animation.animCharSet, 0, self.interactiveObjects[4].animation.animSpeedScale);
		end;
	    setAnimTrackSpeedScale(self.interactiveObjects[4].animation.animCharSet, 0, -self.interactiveObjects[4].animation.animSpeedScale);
		enableAnimTrack(self.interactiveObjects[4].animation.animCharSet, 0);
	end
end;

-- HANDBRAKE EVENT --
-- MP Fix by modelleicher
HandbrakeEvent = {};
HandbrakeEvent_mt = Class(HandbrakeEvent, Event);

InitEventClass(HandbrakeEvent, "HandbrakeEvent");

function HandbrakeEvent:emptyNew()
    local self = Event:new(HandbrakeEvent_mt);
    self.className = "HandbrakeEvent";
    return self;
end;

function HandbrakeEvent:new(object, state)
    local self = HandbrakeEvent:emptyNew()
    self.object = object;
	self.state = state;
    return self;
end;

function HandbrakeEvent:readStream(streamId, connection)
    local id = streamReadInt32(streamId);
	self.state = streamReadBool(streamId);
    self.object = networkGetObject(id);
    self:run(connection);
end;

function HandbrakeEvent:writeStream(streamId, connection)
    streamWriteInt32(streamId, networkGetObjectId(self.object));
	streamWriteBool(streamId, self.state);
end;

function HandbrakeEvent:run(connection)
    self.object:setHandBrakeState(self.state, true);
    if not connection:getIsServer() then
        g_server:broadcastEvent(HandbrakeEvent:new(self.object, self.state), nil, connection, self.object);
    end;
end;

function HandbrakeEvent.sendEvent(vehicle, state, noEventSend)
    if state ~= vehicle.handbrake then
        if noEventSend == nil or noEventSend == false then
            if g_server ~= nil then
                g_server:broadcastEvent(HandbrakeEvent:new(vehicle, state), nil, nil, vehicle);
            else
                g_client:getServerConnection():sendEvent(HandbrakeEvent:new(vehicle, state));
            end;
        end;
    end;
end;