--
-- Fendt 939 series
-- Specialization class for Fendt 900 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
-- @author  Ago-Systemtech
-- @date 25/07/2013
-- Copyright (C) Ago-Systemtech, All Rights Reserved.

Fendt939serie = {};

function Fendt939serie.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Motorized, specializations);
end;

function Fendt939serie: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 = 100;
	self.prevousFuelPercentage = 0;
 

---------------------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.backHydraulic = {};
	self.backHydraulic.rootArm = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.backHydraulic#rootArm"));
	self.backHydraulic.bottomArm = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.backHydraulic#bottomArm"));
	self.frontAttacherJoint = {};
	self.frontAttacherJoint.node = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.trailerAttacherJoints#front"));
	
	
    
	    -------------------------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;
	
	-- 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;
	self.wiperFrontOn = false;
	self.wiperBackOn = false;

	------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;	

	  ----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.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.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"));
	
	-- 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;
	
	
      -- Leve ---
	self.levaindicatori = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.levaindicatori#index"));
	-- 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");
 
  
	      -- Indicatori--
		
	
	local translationPartNode = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.translationPart#index"));
    if translationPartNode ~= nil then
        self.translationPart = {};
        self.translationPart.node = translationPartNode;
        local x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.translationPart#minTrans"));
        self.translationPart.minTrans = {};
        self.translationPart.minTrans[1] = Utils.getNoNil(x, 0);
        self.translationPart.minTrans[2] = Utils.getNoNil(y, 0);
        self.translationPart.minTrans[3] = Utils.getNoNil(z, 0);

        x, y, z = Utils.getVectorFromString(getXMLString(xmlFile, "vehicle.translationPart#maxTrans"));
        self.translationPart.maxTrans = {};
        self.translationPart.maxTrans[1] = Utils.getNoNil(x, 0);
        self.translationPart.maxTrans[2] = Utils.getNoNil(y, 0);
        self.translationPart.maxTrans[3] = Utils.getNoNil(z, 0);

        self.translationPart.transTime = Utils.getNoNil(getXMLString(xmlFile, "vehicle.translationPart#transTime"), 2)*1000;
        self.translationPart.touchTransLimit = Utils.getNoNil(getXMLString(xmlFile, "vehicle.translationPart#touchTransLimit"), 10);
    end;
	
	---sound riserva---
    fuelwarningSoundFile = Utils.getFilename("sound/fuelwarning.wav", self.baseDirectory);
    self.fuelwarningSoundId = createSample("fuelwarningSound");
    loadSample(self.fuelwarningSoundId, fuelwarningSoundFile, false);
    self.fuelwarningPlaying = false;


	self.helpPanel = false;
	self.helpPanel = false;
end;

function Fendt939serie:stopMotor()
 self.motor.minRpm = 200;   
end;

function Fendt939serie:delete()
   if self.hudAllradONOverlay ~= nil or self.hudAllradOFFOverlay ~= nil then
		self.hudAllradONOverlay:delete();
		self.hudAllradOFFOverlay:delete();
	end;
end;

function Fendt939serie:readStream(streamId, connection)
		self:allradState(streamReadBool(streamId), true);
end;

function Fendt939serie:writeStream(streamId, connection)
		streamWriteBool(streamId, self.AllradV41Active);
end;

function Fendt939serie:readUpdateStream(streamId, timestamp, connection)
	if connection:getIsServer() then
		if streamReadBool(streamId) then
		end;
	end;
end;

function Fendt939serie:writeUpdateStream(streamId, connection, dirtyMask)
	if not connection:getIsServer() then
		if streamWriteBool(streamId, bitAND(dirtyMask, self.vehicleDirtyFlag) ~= 0) then
        end;
    end;
end;
function Fendt939serie:allradState(state, noEventSend)
    AllradStateEvent.sendEvent(self, state, noEventSend);
    self.AllradV41Active = state;
end;
function Fendt939serie:mouseEvent(posX, posY, isDown, isUp, button)

end;

function Fendt939serie: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 Fendt939serie:update(dt)
	
	   --pistoni sollevatore--
    if self:getIsActive() then
		Cylindered.updateMovingPart(self, self.movingParts[1]);
        
        if self.backHydraulic ~= nil then
			local x, y, z = getRotation(self.backHydraulic.bottomArm);
			setRotation(self.backHydraulic.rootArm, x, y, z);
		end;
        
       for _, part in pairs(self.movingParts) do
		   part.isDirty = true;
	   end;
        
        local sx,sy,sz = getTranslation(self.sitz);
        local _,ry,_ = getTranslation(self.wheels[1].repr);
        setTranslation(self.sitz, sx, (ry+2.0895) /3, sz);  
		
        --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---
        for _, part in pairs(self.movingParts) do
			Cylindered.setDirty(self, part);
		end;

		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;		
			
	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 Input.isMouseButtonPressed(Input.MOUSE_BUTTON_WHEEL_UP) then
			self.camPositionZ = self.camPositionZ + 0.02;
			if self.camPositionZ >= 0.15 then
				self.camPositionZ = 0.15;
			end;
		end;
				if Input.isMouseButtonPressed(Input.MOUSE_BUTTON_WHEEL_DOWN) then
			self.camPositionZ = self.camPositionZ - 0.02;
			if self.camPositionZ <= -0.2 then
				self.camPositionZ = -0.2;
			end;
		end;
		if InputBinding.isPressed(InputBinding.MOVECAMFORWARD2) then
			self.camPositionY = self.camPositionY + 0.02;
			if self.camPositionY >= 0.3 then
				self.camPositionY = 0.3;
			end;
		end;
		if InputBinding.isPressed(InputBinding.MOVECAMBACK2) then
			self.camPositionY = self.camPositionY - 0.02;
			if self.camPositionY <= -0.22 then
				self.camPositionY = -0.22;
			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;	
	     			
		    --RPM-Gas control--
	if self:getIsActiveForInput() then
        if InputBinding.isPressed(InputBinding.aumentaRPM) then
		    self.motor.minRpm = self.motor.minRpm - 25;
		elseif InputBinding.isPressed(InputBinding.diminuisciRPM) then
		    self.motor.minRpm = self.motor.minRpm + 25;
	    end;
    end;

    if self.isEntered then
		if self.motor.minRpm < -1600 then
			self.motor.minRpm = -1600;
		elseif self.motor.minRpm > 200 then
			self.motor.minRpm = 200;
		end;
	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;
	
		
	 ----------------------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;
	----Led Riserva-----
	if self.isEntered then
		if self.fuelFillLevel < 120 then
			self.riserva = self.riserva - dt;
			if self.riserva <= 120 then
				playSample(self.fuelwarningSoundId,1,1,0);
				self.riserva = 30000;
			end;
			self.ledriservaActive = true;
		else
			self.riserva = 30000;
			self.ledriservaActive = false;
		end;
		setVisibility(self.ledriserva,self.ledriservaActive);
		self:updateFuelIndicators();
	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;
	  
	   
end;

function Fendt939serie: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 Fendt939serie:updateTick(dt)

    if self:getIsActive() then	
					
			
		if self.isMotorStarted then
			setVisibility(self.batteriaicona, false);
			setVisibility(self.olioicona, false);
			setVisibility(self.tachiicona, true);
			setVisibility(self.LedStart, true);
			setVisibility(self.quadroOFF, true);
			setVisibility(self.fuelIndicatorsGroup, true);
			setVisibility(self.LedBraccio, true);
		else			
			setVisibility(self.batteriaicona, true);
			setVisibility(self.olioicona, true);
			setVisibility(self.tachiicona, false);
			setVisibility(self.LedStart, false);
		    setVisibility(self.quadroOFF, false);
			setVisibility(self.fuelIndicatorsGroup, false);
			setVisibility(self.LedBraccio, false);
				
		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;
		end;
	
		
	end;
	
	-- Stop wipers in correct position
	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 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;

	-- Start front wiper g_currentMission.environment.lastRainScale > 0.1 and g_currentMission.environment.timeSinceLastRain < 30 or
	if self.wiperFrontOn then
		if not self.isWiperFrontActive then
			enableAnimTrack(self.wiperFrontAnimCharSet, 0);
			enableAnimTrack(self.wiperBackAnimCharSet, 0);
			self.isWiperFrontActive = true;
			self.isWiperBackActive = true;
		end;
		setRotation(self.wiperLever, 0, math.rad(-18), 0);
	else
		if self.isWiperFrontActive then
			self.isWiperFrontActive = false;
			self.finishWiperFront = false;
		end;
		setRotation(self.wiperLever, 0, 0, 0);
	end;

	-- Start rear wiper g_currentMission.environment.lastRainScale > 0.1 and g_currentMission.environment.timeSinceLastRain < 30 or
	if self.wiperBackOn 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;
	
	-- switch
	if self.switch[1] ~= nil then
		if self.beaconLightsActive then
			setRotation(self.switch[1], math.rad(0), math.rad(0), math.rad(0));
		
		else
			setRotation(self.switch[1], math.rad(-90), math.rad(0), math.rad(0));
		
		end;
	end;
	if self.switch[2] ~= nil then
		if self.beaconLightsActive then
			setRotation(self.switch[2], math.rad(0), math.rad(0), math.rad(0));
		
		else
			setRotation(self.switch[2], math.rad(-90), math.rad(0), math.rad(0));
		
		end;
	end;
	if self.switch[3] ~= nil then
		if self.isMotorStarted then
			setRotation(self.switch[3], math.rad(0), math.rad(45), math.rad(0));
		
		else
			setRotation(self.switch[3], math.rad(0), math.rad(100), math.rad(0));
	
		end;
	end;
    if self.switch[4] ~= nil then
		if self.B3.wl then
			setRotation(self.switch[4], math.rad(-31.15735), 0, 0);
			setVisibility(self.LedHazard, true);
		else
			setRotation(self.switch[4],math.rad(150), 0, 0);
			setVisibility(self.LedHazard, false);
		end;
	end;
	if self.switch[5] ~= nil then
		if self.wiperBackOn then
			setRotation(self.switch[5], math.rad(0), math.rad(0), math.rad(0));
		else
			setRotation(self.switch[5], math.rad(180), 0, 0);
		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;
		if self.handbrakelight ~= nil then
		if self.handbrake then
			setVisibility(self.handbrakelight, true);
		else
			setVisibility(self.handbrakelight, 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 Fendt939serie: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 Fendt939serie:draw()
   
	if self.isEntered then
		if not self.helpPanel then
			--renderText(0.72, 0.25, 0.02, "Tasto m: Info On");
		else
			--renderText(0.72, 0.25, 0.02, "Tasto m: 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 Fendt939serie: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;
	
	if jointIndex == 3 then
	   setVisibility(self.konsole, true);
	end;
	
	self.updateJoint = true;
end;
function Fendt939serie:detachImplement(implementIndex)

	local implement = self.attachedImplements[implementIndex];
	local jointIndex = implement.jointDescIndex;

	if jointIndex == 2 then
		setVisibility(self.attacherJoints[jointIndex].topArm.rotationNode, false);
	end;
	
	if jointIndex == 3 then
		setVisibility(self.konsole, false);
	end;
end;
function Fendt939serie:validateAttacherJoint(implement, jointDesc, dt)
    if self.updateJoint then
        self.updateJoint = false;
        return true;
    end;
    return false;
end;

function Fendt939serie:onEnter()
        if self.isMotorStarted then
			setVisibility(self.batteriaicona, false);
			setVisibility(self.olioicona, false);
			setVisibility(self.tachiicona, true);
			setVisibility(self.LedStart, true);
			setVisibility(self.LedBraccio, true);
			setVisibility(self.quadroOFF, true);
		else			
			setVisibility(self.batteriaicona, true);
			setVisibility(self.olioicona, true);
			setVisibility(self.tachiicona, false);
			setVisibility(self.LedStart, false);
			setVisibility(self.LedBraccio, false);
		    setVisibility(self.quadroOFF, false);
		end
	if self.isWiperFrontActive then
		enableAnimTrack(self.wiperFrontAnimCharSet, 0);
	end;
	if self.isWiperBackActive then
		enableAnimTrack(self.wiperBackAnimCharSet, 0);
	end
	
end;

function Fendt939serie:onLeave()
      self.motor.minRpm = 200;   
		 
	    if self.isMotorStarted then
			setVisibility(self.batteriaicona, false);
			setVisibility(self.olioicona, false);
			setVisibility(self.tachiicona, true);
			setVisibility(self.LedStart, true);
			setVisibility(self.quadroOFF, true);
			setVisibility(self.LedBraccio, true);
		else			
			setVisibility(self.batteriaicona, true);
			setVisibility(self.olioicona, true);
			setVisibility(self.tachiicona, false);
			setVisibility(self.LedStart, false);
			setVisibility(self.quadroOFF, false);
			setVisibility(self.LedBraccio, false);
	     end
		if self.isWiperFrontActive then
		disableAnimTrack(self.wiperFrontAnimCharSet, 0);
	     end;
		if self.isWiperBackActive then
		disableAnimTrack(self.wiperBackAnimCharSet, 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;
