--
-- Fendt 936 series
-- Specialization class for Fendt 900 series
--
-- @author  Ago-Systemtech
-- @date  17/11/2011
-- Copyright (C) Ago-Systemtech, All Rights Reserved.

Fendt936serie = {};

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

function Fendt936serie:load(xmlFile)
		
	self.LucePorta = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.LucePorta#index"));
	self.doorIObject = nil;
	self.internalCamera = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.internalCamera#index"));
	self.camPositionX = 0;
	self.camPositionZ = 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;
    self.handbrake = true;
	self.cos = 20000;
	self.druckLevel = 10000; 
	self.is4wdActive = true;
	--HandBrake
	self.handbrakelight = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.handbrakelight#index"));
    self.brakelight = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.brakelight#index"));
	self.reverselight = Utils.indexToObject(self.rootNode, getXMLString(xmlFile, "vehicle.reverselight#index"));
	self.change4wdState = SpecializationUtil.callSpecializationsFunction("change4wdState");
	      
	--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"));
	
	handbrakeSoundFile = Utils.getFilename("sound/handbrake.ogg", self.baseDirectory);
    self.handbrakeSoundId = createSample("sound/handbrakeSound");
    loadSample(self.handbrakeSoundId, handbrakeSoundFile, false);
    self.handbrakePlaying = false;
	
	brakeSoundFile = Utils.getFilename("sound/compressedAir.ogg", self.baseDirectory);
    self.brakeSoundId = createSample("sound/brakeSound");
    loadSample(self.brakeSoundId, brakeSoundFile, false);
    self.brakePlaying = false;
	
	brakereleaseSoundFile = Utils.getFilename("sound/brake.ogg", self.baseDirectory);
    self.brakereleaseSoundId = createSample("sound/brakereleaseSound");
    loadSample(self.brakereleaseSoundId, brakereleaseSoundFile, false);
    self.brakereleasePlaying = false;
		
	compressorSoundFile = Utils.getFilename("sound/compressor.ogg", self.baseDirectory);
    self.compressorSoundId = createSample("sound/compressorSound");
    loadSample(self.compressorSoundId, compressorSoundFile, false);
    self.compressorPlaying = false;
	
	compressorstopSoundFile = Utils.getFilename("sound/compressorstop.ogg", self.baseDirectory);
    self.compressorstopSoundId = createSample("sound/compressorstopSound");
    loadSample(self.compressorstopSoundId, compressorstopSoundFile, false);
    self.compressorstopPlaying = 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");
 
   	
	   --BGA silos--
     self.bunkerSiloCompactingScale = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.bunkerSiloCompacter#compactingScale"), 1);
     self.bunkerSiloCompactingRefNode = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.bunkerSiloCompacter#refNode"));

        --Power Shaft--
	local i=0;
    while true do
        local baseName = string.format("vehicle.attacherJoints.attacherJoint(%d)", i);
        local index = getXMLString(xmlFile, baseName.. "#index");
        if index == nil then
            break;
        end;		
		local joint = self.attacherJoints[i+1];
		local shaftAttacher = Utils.indexToObject(self.components, getXMLString(xmlFile, baseName .. "#shaft"));
		if shaftAttacher ~= nil then
			joint.powerShaftAttacher = shaftAttacher;
		end;
		i = i + 1;
	end;

	local attacherJointCount = i;
	i = 0;
    while true do
        local baseName = string.format("vehicle.trailerAttacherJoints.trailerAttacherJoint(%d)", i);
        local index = getXMLString(xmlFile, baseName.. "#index");
        if index == nil then
            break;
        end;
		
		local joint = self.attacherJoints[attacherJointCount + 1 + i];
		local shaftAttacher = Utils.indexToObject(self.components, getXMLString(xmlFile, baseName .. "#shaft"));
		if shaftAttacher ~= nil then
			joint.powerShaftAttacher = shaftAttacher;
		end;
        i = i+1;
    end;
	
		
	      -- 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 Fendt936serie:stopMotor()
 self.motor.minRpm = 200;   
end;

function Fendt936serie:delete()

end;

function Fendt936serie:readStream(streamId, connection)
	self.is4wdActive = streamReadBool(streamId);
end;

function Fendt936serie:writeStream(streamId, connection)
	streamWriteBool(streamId, self.is4wdActive);
end;

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

function Fendt936serie:writeUpdateStream(streamId, connection, dirtyMask)
	if not connection:getIsServer() then
		if streamWriteBool(streamId, bitAND(dirtyMask, self.vehicleDirtyFlag) ~= 0) then
        end;
    end;
end;

function Fendt936serie:mouseEvent(posX, posY, isDown, isUp, button)

end;

function Fendt936serie:keyEvent(unicode, sym, modifier, isDown)
	
		
	   ---Help--
	if isDown and sym == Input.KEY_KP_0 then
		self.helpPanel = not self.helpPanel;
	end;

	  --HandBrake---
	if isDown and sym == Input.KEY_y then
		self.handbrake = not self.handbrake; 
		if self.handbrake then
			playSample(self.handbrakeSoundId,1,1,0);
			brakeTorque = 600;
			self.motor.brakeForce = brakeTorque;
		end;
	end;
	
	
	
end;

function Fendt936serie: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;
                  
		        ---internal cam--	
    if self.isMotorStarted then
		
		if InputBinding.isPressed(InputBinding.MOVECAMLEFT) then
			self.camPositionX = self.camPositionX + 0.02;
			if self.camPositionX >= 0.3 then
				self.camPositionX = 0.3;
			end;
		end;
		
		if InputBinding.isPressed(InputBinding.MOVECAMRIGHT) then
			self.camPositionX = self.camPositionX - 0.02;
			if self.camPositionX <= -0.3 then
				self.camPositionX = -0.3;
			end;
		end;
		
		if InputBinding.isPressed(InputBinding.MOVECAMFORWARD) then
			self.camPositionZ = self.camPositionZ + 0.02;
			if self.camPositionZ >= 0.4 then
				self.camPositionZ = 0.4;
			end;
		end;
		
		if InputBinding.isPressed(InputBinding.MOVECAMBACK) then
			self.camPositionZ = self.camPositionZ - 0.02;
			if self.camPositionZ <= -0.3 then
				self.camPositionZ = -0.3;
			end;
		end;
		
		if InputBinding.hasEvent(InputBinding.MOVECAMRESET) then
			self.camPositionX = 0;
			self.camPositionZ = 0;
		end;
		
		if self.internalCamera ~= nil then
			setTranslation(self.internalCamera, self.camPositionX, 0, self.camPositionZ);
		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.isEntered then

        
        if g_currentMission.allowSteerableMoving and not self.playMotorSound then
			
			if Input.isKeyPressed(Input.KEY_w) then
				self.motor:setSpeedLevel(0, true)
			end;
			if Input.isKeyPressed(Input.KEY_w) then
				self.motor:setSpeedLevel(0,true)
			end;
			
        if self.fuelFillLevel == 0 then
            acceleration = 0;
          end;
					
		end;
		
		if not self.handbrake then
		    brakeTorque = 20;
			self.motor.brakeForce = brakeTorque;
			setVisibility(self.handbrakelight, false);
		else
			if not Input.isKeyPressed(Input.KEY_s) then
				setVisibility(self.handbrakelight, true);
			end;
		end;		
		if Input.isKeyPressed(Input.KEY_s) then
			if not self.druckWarning then
				if not self.braking then
					if self.attachedTrailer then
						self.druckLevel = self.druckLevel -350;
					else
						self.druckLevel = self.druckLevel -250;
					end;
					self.braking = true;
				end;
				setVisibility(self.brakelight, true);
				if not self.brakePlaying then
					playSample(self.brakeSoundId,1,1,0);
					self.brakePlaying = true;
				end;
				self.brakereleasePlaying = false;				
			end;
		else
			self.brakePlaying = false;
			setVisibility(self.brakelight, false);
			self.braking = false;
			if not self.handbrake then
				brakeTorque = 20;
				self.motor.brakeForce = brakeTorque;
			end;
			if not self.brakereleasePlaying then
				playSample(self.brakereleaseSoundId,1,1,0);
				self.brakereleasePlaying = true;
			end;
		end;

		
				
		if self.druckLevel >= -1 and self.druckLevel <= 6100 then
			self.compressorStart = true;
		end;
		if self.druckLevel >= 9999 then
			self.compressorStart = false;
		end;
		if self.compressorStart == true then
			if not self.compressorSoundRunning then
				playSample(self.compressorSoundId, 0, 1, 0);
				self.compressorSoundRunning = true;
			end;
			self.compressorstopSoundRunning = false;
			if self.druckLevel <= 10000 then
				self.druckLevel = self.druckLevel +(dt/3);
			end;
		end;
		if self.compressorStart == false then
			stopSample(self.compressorSoundId, 0, 1, 0);
			self.compressorSoundRunning = false;
			if not self.compressorstopSoundRunning then
				playSample(self.compressorStopSoundId, 1, 1, 0);
				self.compressorstopSoundRunning = true;
			end;
			if self.druckLevel >= 6099 then
				self.druckLevel = self.druckLevel -(dt/40);
			end;
		end;
		if self.druckLevel <= 6000 then
			self.druckWarning = true;
			self.drucklightActive = true;
		else
			self.druckWarning = false;
			self.drucklightActive = false;
		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;
	
	  
	   
end;

function Fendt936serie: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;
		
		if self.is4wdActive then
				setVisibility(self.led4WDon, true);
			else
				setVisibility(self.led4WDon, false);
		end;
		local mySpeed = self.lastSpeed*3600;
			if self.isBraking and mySpeed > 0 then
				if self.led4WDon ~= nil then
					setVisibility(self.led4WDon, true);
				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;
		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.led4WDoff ~= nil then
		 if self.is4wdActive then
		    setVisibility(self.led4WDoff, false);
			setVisibility(self.led4WDoff2, false);
		 else
		   setVisibility(self.led4WDoff, true);
		    setVisibility(self.led4WDoff2, true);
		end;
	end
            			
end;

function Fendt936serie: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 Fendt936serie: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.hudjohndeereOverlay ~= nil then
			self.hudjohndeereOverlay:render();
		end;
		if self.handbrake then
			setTextBold(true);
			setTextColor(1,0,0,1);
			if Input.isKeyPressed(Input.KEY_w) then
				setTextBold(true);
				setTextColor(1,0,0,1);
				renderText(0.74, 0.26, 0.02, "Handbremse loesen! z/y");
			end;
			renderText(0.74, 0.22, 0.02, "(!) Handbremse aktiv (!)");	
		end;
		
		if self.druckWarning then
			setTextBold(true);
			setTextColor(1,0,0,1);
			renderText(0.74, 0.40, 0.02, "   Systemdruck zu gering.");
			renderText(0.74, 0.37, 0.02, "   Eingeschraenkte Bremswirkung!");
		end;
	end;
	
	  if self.isMotorStarted then
	    --g_currentMission:addExtraPrintText(string.format(g_i18n:getText("GasLimiter_controls"), self.typeDesc) .. " " .. InputBinding.          getKeyNamesOfDigitalAction(InputBinding.mehrRPM) .. "/" .. InputBinding.getKeyNamesOfDigitalAction(InputBinding.wenigerRPM));	
   end;
	
end;
function Fendt936serie: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 Fendt936serie: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 Fendt936serie:validateAttacherJoint(implement, jointDesc, dt)
    if self.updateJoint then
        self.updateJoint = false;
        return true;
    end;
    return false;
end;
function Fendt936serie:change4wdState(current4wdState, noEventSend)
	Change4wdStateEvent.sendEvent(self,current4wdState,noEventSend);

	if current4wdState then
		self.wheels[1].driveMode = 0;
		self.wheels[2].driveMode = 0;
		self.is4wdActive = false;
		self.motor.forwardTorqueCurve = AnimCurve:new(linearInterpolator1);
 		self.motor.forwardTorqueCurve:addKeyframe({v = 14*3, time = 2400});
	else
		self.wheels[1].driveMode = 2;
		self.wheels[2].driveMode = 2;
		self.is4wdActive = true;
		self.motor.forwardTorqueCurve = AnimCurve:new(linearInterpolator1);
 		self.motor.forwardTorqueCurve:addKeyframe({v = 10*3, time = 2400});
	end;
end;

function Fendt936serie: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 Fendt936serie: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;

