--
-- Fendt vario 700 series
-- Specialization class for Fendt 700 series
-- @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  20/09/2012
-- Copyright (C) Ago-Systemtech, All Rights Reserved.

Vario700serieV2 = {};
function Vario700serieV2.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations);
end;
function Vario700serieV2:load(xmlFile)
	self.LucePorta = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.LucePorta#index"));
	self.doorIObject = nil;
	---------------------CAM INTERNA MOBILE---------------------
	self.internalCamera = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.internalCamera#index"));
	self.camPositionX = 0;
	self.camPositionZ = 0;
	self.camPositionY = 0;
	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"));
    -------------------------ALLRADV4-----------------
	self.allradState = SpecializationUtil.callSpecializationsFunction("allradState");
    self.AllradV41Active = false;
	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;
	-------------------------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;
    local PedaleFrenoNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.PedaleFreno#index"));
    if PedaleFrenoNode ~= nil then
        self.PedaleFreno = {};
        self.PedaleFreno.node = PedaleFrenoNode;
		local x1,y1,z1 = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.PedaleGas#minRot"));
		local x2,y2,z2 = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.PedaleGas#maxRot"));
		self.PedaleFreno.rotMin = {math.rad(Utils.getNoNil(x1,0)),math.rad(Utils.getNoNil(y1,0)),math.rad(Utils.getNoNil(z1,0))};
		self.PedaleFreno.rotMax = {math.rad(Utils.getNoNil(x2,0)),math.rad(Utils.getNoNil(y2,0)),math.rad(Utils.getNoNil(z2,0))};
        self.PedaleFreno.rotTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.PedaleFreno#rotTime"), 1)*1000;
        self.PedaleFrenoIsActive = false;
    end;
	-------------------------- LEVE ----------------------
	self.levaindicatori = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.levaindicatori#index"));
	self.LevaHandbrake = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.LevaHandbrake#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.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"));
	------------------ 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");
	---------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;
	
	self.helpPanel = false;
	
end;
function Vario700serieV2:delete()
    if self.hudAllradONOverlay ~= nil or self.hudAllradOFFOverlay ~= nil then
		self.hudAllradONOverlay:delete();
		self.hudAllradOFFOverlay:delete();
	end;
end;
function Vario700serieV2:readStream(streamId, connection)
		self:allradState(streamReadBool(streamId), true);
end;
function Vario700serieV2:writeStream(streamId, connection)
	streamWriteBool(streamId, self.AllradV41Active);
end;
function Vario700serieV2:readUpdateStream(streamId, timestamp, connection)
	if connection:getIsServer() then
		if streamReadBool(streamId) then
		end;
	end;
end;
function Vario700serieV2:writeUpdateStream(streamId, connection, dirtyMask)
	if not connection:getIsServer() then
		if streamWriteBool(streamId, bitAND(dirtyMask, self.vehicleDirtyFlag) ~= 0) then
        end;
    end;
end;
function Vario700serieV2:mouseEvent(posX, posY, isDown, isUp, button)
end;
function Vario700serieV2: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 Vario700serieV2:allradState(state, noEventSend)
    AllradStateEvent.sendEvent(self, state, noEventSend);
    self.AllradV41Active = state;
end;
function Vario700serieV2: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);
	end;
	-------------------- PLAFONIERA -------------------
	if self.doorIObject == nil then
		for k,iObject in pairs(self.interactiveObjects) do
			if iObject.name == g_i18n:getText("leftDoor") then
				self.doorIObject = iObject;
		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.isMouseButtonPressed(Input.MOUSE_BUTTON_MIDDLE) 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:getIsActiveForInput() 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;
	---------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 Vario700serieV2:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)
    return BaseMission.VEHICLE_LOAD_OK;
end;
function Vario700serieV2: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.camIndex == 1 then
			 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;
		------------------- CHECK FRENO----------------------------
			if self.PedaleFreno ~= nil then
				local x, y, z = getRotation(self.PedaleFreno.node);
				local rot = {x,y,z};
				local direction = -1;
				if self.invertedDrivingDirection then
				    direction = 1;
				else
				    direction = -1;
				end;
				local braking = math.abs(Utils.sign(self.lastAcceleration)+ (-self.movingDirection * direction)) == 2;
				local newRot = Utils.getMovedLimitedValues(rot, self.PedaleFreno.rotMax, self.PedaleFreno.rotMin, 3, self.PedaleFreno.rotTime, dt, braking);
				setRotation(self.PedaleFreno.node, unpack(newRot));
			end;
		end;
		if self.camIndex == 2 then
			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;
				if self.PedaleFreno ~= nil then
				local x, y, z = getRotation(self.PedaleFreno.node);
				local rot = {x,y,z};
				local direction = -1;
				if self.invertedDrivingDirection then
				    direction = 1;
				else
				    direction = -1;
				end;
				local braking = math.abs(Utils.sign(self.lastAcceleration)+ (-self.movingDirection * direction)) == 2;
				local newRot = Utils.getMovedLimitedValues(rot, self.PedaleFreno.rotMax, self.PedaleFreno.rotMin, 3, self.PedaleFreno.rotTime, dt, braking);
				setRotation(self.PedaleFreno.node, unpack(newRot));
			end;
		end;
	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[2] ~= nil then
		if self.isMotorStarted then
			setRotation(self.switch[2], math.rad(0), math.rad(-60), math.rad(0));
		else
			setRotation(self.switch[2], math.rad(0), math.rad(0), math.rad(0));
		end;
	end;
	if self.LevaHandbrake ~= nil then
		if self.handbrake then
			setRotation(self.LevaHandbrake, math.rad(0), math.rad(0), math.rad(0));
		else
			setRotation(self.LevaHandbrake, math.rad(90), 0, 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;
	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.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 Vario700serieV2: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 Vario700serieV2: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 Vario700serieV2:draw()
	if self.isEntered then
		if not self.helpPanel then
			--renderText(0.72, 0.25, 0.02, "Tasto 0: Info On");
		else
			--renderText(0.72, 0.25, 0.02, "Tasto 0: Info Off");
		end;
		if self.helpPanel then
			renderText(0.02, 0.56, 0.023, "      - Help -   ");
			renderText(0.02, 0.54, 0.021, "Prima di agganciare un rimorchio regolare l'altezza del gancio");
			renderText(0.02, 0.52, 0.021, "Before attaching a trailer to adjust the height of the hook");
			renderText(0.02, 0.50, 0.021, "Vor dem Anbringen eines Anhangers, die Hohe des Hakens.");
			renderText(0.02, 0.48, 0.021, "      ---------------------------------");
			renderText(0.02, 0.46, 0.021, "Il trattore lavabile e si sporca dopo circa 2 ore di gioco.");
			renderText(0.02, 0.44, 0.021, "Si puo lavare e si pulisce anche con la pioggia.");
			renderText(0.02, 0.42, 0.021, "The tractor is washable and it gets dirty after about 2 hours of play.");
			renderText(0.02, 0.40, 0.021, "You can wash and clean even with the rain.");
			renderText(0.02, 0.38, 0.021, "Der Traktor ist waschbar und es wird schmutzig nach etwa 2 Stunde zu spielen.");
			renderText(0.02, 0.36, 0.021, "Sie konnen waschen und zu reinigen, auch mit dem regen.");
			renderText(0.02, 0.34, 0.021, "      ---------------------------------");
			renderText(0.02, 0.32, 0.021, "Per usare il limitatore di giri ESLimiter, premere i tasti Pgup/Pgdown");
			renderText(0.02, 0.30, 0.021, "To use the rev limiter ESLimiter, press the PgUp / PgDown");
			renderText(0.02, 0.28, 0.021, "Zur Verwendung der Drehzahlbegrenzer ESLimiter, drucken Sie die Bild auf / Bild ab");
			renderText(0.02, 0.26, 0.021, "      ---------------------------------");
			renderText(0.02, 0.24, 0.021, "Grazie per aver scelto una mia mod-Thank you for my mod-Vielen Dank fur meine mod");
			renderText(0.02, 0.22, 0.021, "Support, TRACTOR ITALIA FORUM: http://forum.tractor-italia.net");
			renderText(0.02, 0.20, 0.021, "ATTENZIONE VIETATO FARE MODIFICHE-ATTENTION, FORBIDDEN TO DO CHANGES.");
			renderText(0.02, 0.18, 0.021, "Creative Commons license, by Ago-Systemtech");
		end;
	end;
	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;
	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 Vario700serieV2:attachImplement(implement)
	local jointType = implement.object.attacherJoint.jointType;
	local jointIndex = implement.jointDescIndex;
	if jointType == Vehicle.JOINTTYPE_IMPLEMENT then
		if jointIndex == 2 then
			setVisibility(self.attacherJoints[jointIndex].topArm.rotationNode, true);
		end;
	end;
	self.updateJoint = true;
end;
function Vario700serieV2:detachImplement(implementIndex)
	local implement = self.attachedImplements[implementIndex];
	local jointIndex = implement.jointDescIndex;
	if jointIndex == 2 then
		setVisibility(self.attacherJoints[jointIndex].topArm.rotationNode, false);
	end;
end;
function Vario700serieV2:validateAttacherJoint(implement, jointDesc, dt)
    if self.updateJoint then
        self.updateJoint = false;
        return true;
    end;
    return false;
end;

function Vario700serieV2: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;
end;
function Vario700serieV2: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;
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;