--
-- HorschSW3500S
-- Specialization for HorschSW3500S
--
-- @author Felix "Outlaw" Sorge
-- @date  13/08/09
-- @web www.ls-modsource.de - www.ls-mods.de
--
-- Copyright (C) Outlaw, All Rights Reserved.
-- Edit for LS 11 AlesK
-- Multiplayer Ready Hummel - modhoster.de
-- Edit for LS 13 upsidedown
-- added external control, clear up of controls: upsidedown

HorschSW3500S = {};

function HorschSW3500S.prerequisitesPresent(specializations)
    return SpecializationUtil.hasSpecialization(Trailer, specializations);
end;

function HorschSW3500S:readStream(streamId, connection)  
	self.turnOn = streamReadBool(streamId);
	
 	self.Speed.down = streamReadFloat32(streamId);
	self.Go.down = streamReadBool(streamId);
	self.Done.down = streamReadBool(streamId);
	
	self.Speed.trsp = streamReadFloat32(streamId);
	self.Go.trsp = streamReadBool(streamId);
	self.Done.trsp = streamReadBool(streamId);
	
	self.Go.tank = streamReadBool(streamId);
	self.Done.tank = streamReadBool(streamId);
	
	
end;

function HorschSW3500S:writeStream(streamId, connection)
	streamWriteBool(streamId, self.turnOn);
	streamWriteFloat32(streamId, self.Speed.down)
	streamWriteBool(streamId, self.Go.down);   
	streamWriteBool(streamId, self.Done.down);
	
	streamWriteFloat32(streamId, self.Speed.trsp)
	streamWriteBool(streamId, self.Go.trsp);   
	streamWriteBool(streamId, self.Done.trsp);
	
	streamWriteBool(streamId, self.Go.tank);   
	streamWriteBool(streamId, self.Done.tank);
end;

function HorschSW3500S:load(xmlFile)
	self.setStateEvent= SpecializationUtil.callSpecializationsFunction("setStateEvent");
	self.cultivatorMode = true;
	--self.safeMode = false;

	self.horschImplementInRange = SpecializationUtil.callSpecializationsFunction("horschImplementInRange");
		
	self.horschAttacher = Utils.indexToObject(self.components, getXMLString(xmlFile, "vehicle.horschAttacher#index"));
	self.horschImplement = {}; 
	
--    self.aiTerrainDetailChannel1 = g_currentMission.cultivatorChannel;
--    self.aiTerrainDetailChannel2 = g_currentMission.sowingChannel;
	self.aiTerrainDetailChannel1 = g_currentMission.cultivatorChannel;
	self.aiTerrainDetailChannel2 = g_currentMission.ploughChannel;
	self.aiTerrainDetailChannel3 = g_currentMission.sowingChannel;
	
	

	self.ParticleSystem = {};
    local i = 0;
    while true do
        local namei = string.format("vehicle.ParticleSystem.ParticleSystem(%d)", i);
		local nodei = Utils.indexToObject(self.components, getXMLString(xmlFile, namei .. "#index"));
		if nodei == nil then
			break;
		end; 
        Utils.loadParticleSystem(xmlFile, self.ParticleSystem, namei, nodei, false, nil, self.baseDirectory)		
		i = i +1;		
    end;
	
	local pneuSound = getXMLString(xmlFile, "vehicle.pneuSound#file");
    if pneuSound ~= nil and pneuSound ~= "" then
       pneuSound = Utils.getFilename(pneuSound, self.baseDirectory);
       self.pneuSound = createSample("pneuSound");
       self.pneuSoundEnabled = false;
       loadSample(self.pneuSound, pneuSound, false);
       self.pneuSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.pneuSound#pitchOffset"), 1);
       self.pneuSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.pneuSound#volume"), 1);
    
	end;
	local workSound = getXMLString(xmlFile, "vehicle.workSound#file");
    if workSound ~= nil and workSound ~= "" then
       workSound = Utils.getFilename(workSound, self.baseDirectory);
       self.workSound = createSample("workSound");
       self.workSoundEnabled = false;
       loadSample(self.workSound, workSound, false);
       self.workSoundPitchOffset = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.workSound#pitchOffset"), 1);
       self.workSoundVolume = Utils.getNoNil(getXMLFloat(xmlFile, "vehicle.workSound#volume"), 1);
    end;
	
	self.currentFillType = FruitUtil.FRUITTYPE_UNKNOWN;
	self.fillLevel = 0;
	
	-- self.AIon = false;
	
	-- self.saveAILM = self.aiLeftMarker;
	--self.aiLeftMarker = nil; 	
	
    self.attacherBackup = nil;
    self.TurnRadiusBackup = 0;	
	
	self.Go.pillar = not self.Go.pillar; 
	self.Done.pillar = true; 
	
	self.turnOn = false;
	
	
	self.Done = {};
	self.Go = {};
	self.Speed = {};
	self.CheckDone = {};
	
	self.turnOn = false;
	self.Go.tank = false;
	self.Go.down = false;
	self.Go.trsp = false;
	
	self.Done.tank = false;
	self.Done.down = false;
	self.Done.trsp = false;
	
	self.CheckDone.trsp = false;
	self.CheckDone.tank = false;
	self.CheckDone.down = false;
	
	self.cultivatorMode  = false;
	
	self.firstTimeHorschRun = true;
	
	self.realToolHasGroundContact = false;
end;


function HorschSW3500S:update(dt)

	-- if self.firstTimeHorschRun then
		-- if not self.horschImplement.attached then
			-- self:horschImplementInRange(); 
		-- end;
		-- self.firstTimeHorschRun = false;
	-- end;
	
	if self.isClient then
		if g_currentMission.isRunning and g_gui.currentGui == nil then
			if g_currentMission.controlPlayer then
				if g_currentMission.player ~= nil then
				--if g_currentMission.controlledVehicle == nil then --player on foot
					local pvx, pvy, pvz = getWorldTranslation(g_currentMission.player.rootNode);
					local x, y, z = getWorldTranslation(self.rootNode);
					local farmerDistance = Utils.vector3Length(pvx-x, pvy-y, pvz-z);
					
					if farmerDistance < 4.0 then
						
						if self.Go.tank and self.horschImplement.attached then
							g_currentMission:addHelpButtonText(g_i18n:getText("HorschSW3500S_7"), InputBinding.HorschSW3500S_tank); 
						elseif self.horschImplement.attached then
							g_currentMission:addHelpButtonText(g_i18n:getText("HorschSW3500S_6"), InputBinding.HorschSW3500S_tank); 
						end; 
						
						if self.fillLevel ~= 0 then
							g_currentMission:addHelpButtonText(g_i18n:getText("HorschSW3500S_10"), InputBinding.HorschSW3500S_emptytank); 
						end; 
					
						if InputBinding.hasEvent(InputBinding.HorschSW3500S_tank)  and self.horschImplement.attached then			
							self:setStateEvent("Go", "tank", not self.Go.tank)
							self:setStateEvent("Done", "tank", true)			
						end; 
						
						if InputBinding.hasEvent(InputBinding.HorschSW3500S_emptytank)   and self.fillLevel ~= 0 then
							self:setStateEvent("fillLevel", false, 0)
							self:setFillLevel(self.fillLevel, FruitUtil.FRUITTYPE_UNKNOWN);
						end;
					end;
				end;
			end;
		end;
	end;
	
	self.realToolHasGroundContact = false;
	if self:getIsActive() and self.attacherVehicle ~= nil then
		
		if self.firstTimeHorschRun then
			if not self.horschImplement.attached then
				self:horschImplementInRange(); 
			end;
			self.firstTimeHorschRun = false;
		end;
		
		
		if self.fillLevel <= 25 then			
			self.attacherVehicle:stopAITractor();
		end;
		
		local prozent = self.fillLevel/self.capacity*100;
		if self.attacherVehicle.isAITractorActivated then
			Utils.setEmittingState(self.ParticleSystem, true);
			if prozent > 0 then
				renderText(0.77, 0.82, 0.023,""..string.format("HorschSW3500S: %.0f (%d%%)", self.fillLevel, prozent).."");
			end;
			if prozent < 20 then 
				renderText(0.77, 0.82, 0.023,""..string.format("HorschSW3500S: %.0f (%d%%)", self.fillLevel, prozent).."", setTextColor(1, 0, 0, 1)); 
			end;
			setTextColor(1, 1, 1, 1)
			
		end;
		
		local supressCultivator = self:getIsActiveForInput(true) and Input.isKeyPressed(Input.KEY_lshift);
		
		--if InputBinding.hasEvent(InputBinding.HorschSW3500S_safeMode) and self:getIsActiveForInput() then
		--	self.safeMode = not self.safeMode
		--end;

		if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA) and self:getIsActiveForInput() then		
         --self.cultivatorMode = not self.cultivatorMode;
		 self:setStateEvent("cultivatorMode", false, not self.cultivatorMode)
		end;
		
		-- if self.attacherVehicle.isAITractorActivated ~= nil then
			-- self.AIon = self.attacherVehicle.isAITractorActivated;
		-- end; 
		
		-- if  self.attacherVehicle.isAITractorActivated ~= nil then 
			-- self.aiLeftMarker = self.saveAILM; 
			-- AITractor.updateToolsInfo(self.attacherVehicle)
		-- end; 			
		
		-- if self.AIon then
		-- self.attacherVehicle.steeringAxleAngle = 0;
		-- end;
		
		if self.attacherBackup == nil and self.attacherVehicle ~= nil then
            self.attacherBackup = self.attacherVehicle;
        end;

		if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA)  and self:getIsActiveForInput() and  self.horschImplement.attached and self.CheckDone.trsp and self.Go.trsp and not self.Done.trsp  then
			--self.turnOn = not self.turnOn;
			self:setStateEvent("turnOn", false, not self.turnOn)
		end; 
		
		--self.cultivatorMode = self.turnOn; --force sync.. no point in seperate control
		self.cultivatorMode = true; --self.turnOn and not supressCultivator;
		-- if InputBinding.hasEvent(InputBinding.HorschSW3500S_tank)  and self:getIsActiveForInput()  and self.horschImplement.attached then			
			-- self:setStateEvent("Go", "tank", not self.Go.tank)
			-- self:setStateEvent("Done", "tank", true)			
		-- end; 
		
		-- if InputBinding.hasEvent(InputBinding.HorschSW3500S_emptytank)  and self:getIsActiveForInput() and self.fillLevel ~= 0 then
			-- self:setStateEvent("fillLevel", false, 0)
			-- self:setFillLevel(self.fillLevel, FruitUtil.FRUITTYPE_UNKNOWN);
		-- end;
		
		if InputBinding.hasEvent(InputBinding.IMPLEMENT_EXTRA2)  and self:getIsActiveForInput() and self.horschImplement.attached and not self.Go.down and not self.CheckDone.down and not self.Done.down and not self.turnOn then
			--self.Speed.trsp = 1.0; 
			self:setStateEvent("Speed", "trsp", 1.0)
			--self.Go.trsp = not self.Go.trsp;
			self:setStateEvent("Go", "trsp", not self.Go.trsp)
			--self.Done.trsp = true; 
			self:setStateEvent("Done", "trsp", true)
		end; 
		
		if InputBinding.hasEvent(InputBinding.LOWER_IMPLEMENT) and self:getIsActiveForInput() then
			--self.Speed.down = 1.0; 
			--self.Go.down = not self.Go.down;
			--self.Done.down = true; 
			self:setStateEvent("Speed", "down", 1.0)
			self:setStateEvent("Go", "down", not self.Go.down)
			self:setStateEvent("Done", "down", true)
		end; 
		
		if InputBinding.hasEvent(InputBinding.HorschSW3500S_attach)  and self:getIsActiveForInput() and not self.blockDetach and (self.inRange or self.horschImplement.attached) and self.Go.down and not self.Done.down and self.CheckDone.down then
			--self.horschImplement.attach = not self.horschImplement.attach;
			self:setStateEvent("horschImplement", "attach", not self.horschImplement.attach)
		end; 
		
		if not self.attacherVehicleJointChanged then	
			for i=1, table.getn(self.attacherVehicle.attachedImplements) do
				if self.attacherVehicle.attachedImplements[i].object == self then			
					local index = self.attacherVehicle.attachedImplements[i].jointDescIndex;
					self.attacherVehicleJointChanged = self.attacherVehicle.attacherJoints[index];	
					break;				
				end;
			end;
		end; 	
		
		
		if self.turnOn then
			if not self.pneuSoundEnabled and self:getIsActiveForSound() then
	            playSample(self.pneuSound, 0, self.pneuSoundVolume, 0);
	            setSamplePitch(self.pneuSound, self.pneuSoundPitchOffset);
	            self.pneuSoundEnabled = true;
	        end;
		else
			if self.pneuSoundEnabled then
		        stopSample(self.pneuSound);
		        self.pneuSoundEnabled = false;
			end;
		end; 
		
		
		
		if self.horschImplement.attached then
			self.fillTypes = self.horschImplement.Object.fillTypes; 	
			if self.Go.tank and not self.Done.tank and self.CheckDone.tank then
				self.allowFillFromAir = true; 
			elseif not self.Go.tank then	
				self.allowFillFromAir = false; 
			end; 
		else
			self.allowFillFromAir = false; 
		end; 
		
		-- if self.attacherVehicleJointChanged == nil then--fix for whatever mod vca
			-- self.attacherVehicleJointChanged = {};
		-- end;
		if self.attacherVehicleJointChanged ~= nil then
			if not self.Go.down then			
				self.attacherVehicleJointChanged.moveDown = false;
			else
				self.attacherVehicleJointChanged.moveDown = true;
			end; 
		end;
		
		if self.horschImplement.attached then
			setJointFrame(self.horschImplement.ObjectIndex,0,self.horschAttacher);
		end;
		
					
		if not self.inRage and self.horschImplement.attached and not self.horschImplement.attach then
			setMass(self.horschImplement.node, self.horschImplement.oldmass);
			removeJoint(self.horschImplement.ObjectIndex); 
			self.horschImplement.Object:onDetach(self);
			self.horschImplement.Object = nil;
			self.horschImplement.ObjectIndex = 0; 
			self.horschImplement.rootNode = false; 
			self.horschImplement.attached = false;
			self.horschImplement.attach = false;
			self.horschImplement.name = false; 
		end; 
		
		
		if self.cultivatorMode == true then
			if self.Go.down and not self.Done.down and self.CheckDone.down and self.CheckDone.trsp and self.Go.trsp and not self.Done.trsp then
			
				--insert angle
				local dx,dy,dz = localDirectionToWorld(self.rootNode, 0, 0, 1);

				local angleRad = Utils.getYRotationFromDirection(dx, dz)
				local desc = FruitUtil.fruitIndexToDesc[seedsFruitType];
				if desc ~= nil and desc.directionSnapAngle ~= 0 then
					angleRad = math.floor(angleRad / desc.directionSnapAngle + 0.5) * desc.directionSnapAngle;
				end

				local angle = Utils.convertToDensityMapAngle(angleRad, g_currentMission.terrainDetailAngleMaxValue);
				--end angle
			
				for v,cuttingArea in pairs(self.cuttingAreas) do
					local x,y,z = getWorldTranslation(cuttingArea.start);
					local x1,y1,z1 = getWorldTranslation(cuttingArea.width);
					local x2,y2,z2 = getWorldTranslation(cuttingArea.height);
					if self.cultivatorMode then
						Utils.updateCultivatorArea(x, z, x1, z1, x2, z2,false,false,angle);						
					end;
				end;
				self.realToolHasGroundContact = true;
			end;
		end; 
		
		
		if self.movingDirection ~= 0 then
			if not self.workSoundEnabled and self:getIsActiveForSound() and self.Go.down and not self.Done.down and self.CheckDone.down and self.CheckDone.trsp and self.Go.trsp and not self.Done.trsp then
				playSample(self.workSound, 0, self.workSoundVolume, 0);
				setSamplePitch(self.workSound, self.workSoundPitchOffset);
				Utils.setEmittingState(self.ParticleSystem, not supressCultivator); 
				self.workSoundEnabled = true;
			end;
		end;
		
		if self.movingDirection == 0 or not self.CheckDone.down then
			if self.workSoundEnabled then
				stopSample(self.workSound);
				self.workSoundEnabled = false;
			end;
			Utils.setEmittingState(self.ParticleSystem, false); 
		end; 
			
							
		
		if not self.horschImplement.attached then
			self:horschImplementInRange(); 
		end; 
	else


		if self.pneuSoundEnabled then
			stopSample(self.pneuSound);
			self.pneuSoundEnabled = false;
		end;

		if self.workSoundEnabled then
			stopSample(self.workSound);
			self.workSoundEnabled = false;
		end;
	
	end; 
	if not self:getIsActiveForInput() then
		if self.pneuSoundEnabled then
		        stopSample(self.pneuSound);
		        self.pneuSoundEnabled = false;
		end;
		if self.workSoundEnabled then
				stopSample(self.workSound);
				self.workSoundEnabled = false;
		end;
	end;		
	
	
	
	if self.Done.down then
		local joint = self.componentJoints[3];
		setJointFrame(joint.jointIndex, 0,joint.jointNode);
	end; 

	if self.Go.down ~= nil and self.Done.down ~= false then
		self:anim("down", false); 
	end; 
	
	if self.Go.tank ~= nil and self.Done.tank ~= false then
		self:anim("tank", false); 
	end; 
	
	if self.Go.pillar ~= nil and self.Done.pillar ~= false then
		self:anim("pillar", false); 
	end; 
		
	if self.Go.trsp ~= nil and self.Done.trsp ~= false then
		self:anim("trsp", false); 
	end; 
		
	if self.attacherVehicle then
		for k, implement in pairs(self.attacherVehicle.attachedImplements) do
			if implement.object == self then
				local index = implement.jointDescIndex;
				self.attacherVehicleJointChanged = self.attacherVehicle.attacherJoints[index];
				if self.attacherVehicleJointChanged ~= nil then
					setJointRotationLimit(self.attacherVehicleJointChanged.jointIndex, 2, true, Utils.degToRad(-20), Utils.degToRad(20));
				end;
			end;
		end;
	end;  	
		
	
	
end;


function HorschSW3500S:draw()	
	if self:getIsActiveForInput() then	
		
		
		if self.inRange and not self.blockDetach and self.Go.down and not self.Done.down and self.CheckDone.down then
			g_currentMission:addHelpButtonText(g_i18n:getText("HorschSW3500S_11"), InputBinding.HorschSW3500S_attach); 
		elseif self.horschImplement.attached and not self.blockDetach and self.Go.down and not self.Done.down and self.CheckDone.down then
			g_currentMission:addHelpButtonText(g_i18n:getText("HorschSW3500S_12"), InputBinding.HorschSW3500S_attach); 
		end; 
		
		if not self.blockDetach and not self.horschImplement.attached and not self.Go.down then
			g_currentMission:addHelpButtonText(g_i18n:getText("HorschSW3500S_1"), InputBinding.LOWER_IMPLEMENT);
		end;

		
		if self.turnOn and self.horschImplement.attached and self.CheckDone.trsp and self.Go.trsp and not self.Done.trsp then
			g_currentMission:addHelpButtonText(g_i18n:getText("HorschSW3500S_9"), InputBinding.IMPLEMENT_EXTRA); 
		elseif self.horschImplement.attached and self.CheckDone.trsp and self.Go.trsp and not self.Done.trsp then
			g_currentMission:addHelpButtonText(g_i18n:getText("HorschSW3500S_8"), InputBinding.IMPLEMENT_EXTRA); 
		end;
		
		if self.Go.trsp and self.horschImplement.attached and not self.Go.down and not self.CheckDone.down and not self.Done.down and not self.turnOn then
			g_currentMission:addHelpButtonText(g_i18n:getText("HorschSW3500S_3"), InputBinding.IMPLEMENT_EXTRA2); 
		elseif not self.Go.trsp and self.horschImplement.attached and not self.Go.down and not self.CheckDone.down and not self.Done.down and not self.turnOn then 
			g_currentMission:addHelpButtonText(g_i18n:getText("HorschSW3500S_2"), InputBinding.IMPLEMENT_EXTRA2); 
		end; 

		
	end
	
end;


function HorschSW3500S:delete()
	if self.horschImplement~= nil then
		if self.horschImplement.rootNode then
			setMass(self.horschImplement.node, self.horschImplement.oldmass);
			removeJoint(self.horschImplement.ObjectIndex); 
			self.horschImplement.Object:onDetach(self);
			self.horschImplement.Object = nil;
			self.horschImplement.ObjectIndex = 0; 
			self.horschImplement.rootNode = false; 
			self.horschImplement.attached = false;
			self.horschImplement.attach = false;
			self.horschImplement.name = false;
		end; 
	end
	
	if self.pneuSoundEnabled then
		stopSample(self.pneuSound);
		self.pneuSoundEnabled = false;
	end;
	
	if self.workSoundEnabled then
		stopSample(self.workSound);
		self.workSoundEnabled = false;
	end;
	Utils.setEmittingState(self.ParticleSystem, false); 
	Utils.deleteParticleSystem(self.ParticleSystem);
			
end;

function HorschSW3500S:horschImplementInRange()
	self.inRange = false; 
    local nearestDistance = 2.0;
	local nearestDistanceClose = 10.0;
	local minDistance = 100000;
	local minIndex;
	local px, py, pz = getWorldTranslation(self.horschAttacher);
	for i=1, table.getn(g_currentMission.attachables) do
		if g_currentMission.attachables[i].horschAttacher then
			local vx, vy, vz = getWorldTranslation(g_currentMission.attachables[i].rootNode);
			local distance = Utils.vector3Length(px-vx, py-vy, pz-vz);
			local attachable = g_currentMission.attachables[i];
			if distance < minDistance then
				minDistance = distance;
				if (distance < nearestDistance and not self.horschImplement.rootNode) or (distance < nearestDistanceClose and not self.horschImplement.rootNode and self.linkNow) then
					if attachable ~= self then
						if attachable.attacherVehicle == nil then
						
							self.horschImplement.name = attachable.name;
							self.inRange = true; 
							minIndex = i;
							-- if (self.horschImplement.attach and not self.horschImplement.rootNode) or (distance < nearestDistanceClose and not self.horschImplement.rootNode and self.linkNow) then		
								-- self.horschImplement.Object = attachable;
								-- self.horschImplement.Object:onAttach(self);
								-- local constr = JointConstructor:new();
								-- constr:setActors(self.rootNode, attachable.rootNode);
								-- constr:setJointTransforms(self.horschAttacher, attachable.horschAttacher);
								-- constr:setRotationLimit(0, Utils.degToRad(0), Utils.degToRad(0));
								-- constr:setRotationLimit(1, Utils.degToRad(0), Utils.degToRad(0));--0
								-- constr:setRotationLimit(2, Utils.degToRad(0), Utils.degToRad(0));
								-- self.horschImplement.ObjectIndex = constr:finalize();
								-- self.horschImplement.oldMass = getMass(attachable.rootNode); 
								-- setMass(attachable.rootNode, 0.2);
								-- self.inRange = false;
								-- self.linkNow = false; 
								-- self.horschImplement.attached = true;
								-- self.horschImplement.rootNode = attachable.rootNode;
								-- self.horschImplement.attach = true;
							-- end; 
							nearestDistance = distance;
						end;
					end;
				end; 
			end;
		end;
	end;
	
	if self.inRange then
		local attachable = g_currentMission.attachables[minIndex];
		if (self.horschImplement.attach and not self.horschImplement.rootNode) or (minDistance < nearestDistanceClose and not self.horschImplement.rootNode and self.linkNow) then		
			self.horschImplement.Object = attachable;
			self.horschImplement.Object:onAttach(self);
			local constr = JointConstructor:new();
			constr:setActors(self.rootNode, attachable.rootNode);
			constr:setJointTransforms(self.horschAttacher, attachable.horschAttacher);
			constr:setRotationLimit(0, Utils.degToRad(0), Utils.degToRad(0));
			constr:setRotationLimit(1, Utils.degToRad(0), Utils.degToRad(0));--0
			constr:setRotationLimit(2, Utils.degToRad(0), Utils.degToRad(0));
			self.horschImplement.ObjectIndex = constr:finalize();
			self.horschImplement.oldMass = getMass(attachable.rootNode); 
			setMass(attachable.rootNode, 0.2);
			self.inRange = false;
			self.linkNow = false; 
			self.horschImplement.attached = true;
			self.horschImplement.rootNode = attachable.rootNode;
			self.horschImplement.attach = true;
		end; 
	end;
	
	
end;



function HorschSW3500S:onAttach()
	self.Go.pillar = false; 
	self.Done.pillar = true; 
	self.Speed.down = 1.0; 
	self.Go.down = false; 
	self.Done.down = true; 
    self.TurnRadiusBackup = self.attacherVehicle.aiTractorTurnRadius;
    self.attacherVehicle.aiTractorTurnRadius = 0;
end; 	

function HorschSW3500S:onDetach()
	if self.horschImplement ~= nil then
		if self.horschImplement.rootNode then
			self.horschImplement.Object.turnOn = false; 
		end; 
	end
	 -- self.attacherBackup.aiTractorTurnRadius = self.TurnRadiusBackup;
     -- self.attacherVehicle = self.attacherBackup;
     -- self.attacherVehicle = nil;
     -- self.attacherBackup = nil;
	self.Go.pillar = true; 
	self.Done.pillar = true; 
	self.Speed.down = 1.0; 
	self.Go.down = true; 
	self.Done.down = true; 
	if self.pneuSoundEnabled then
		stopSample(self.pneuSound);
		self.pneuSoundEnabled = false;
	end;

	if self.workSoundEnabled then
		stopSample(self.workSound);
		self.workSoundEnabled = false;
	end;
	Utils.setEmittingState(self.ParticleSystem, false); 
end;

-- function Utils.destroyCompleteArea(startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ)
	-- local meadowId 		 = g_currentMission.meadowId;
	-- local cuttedMeadowId = g_currentMission.cuttedMeadowId;
	-- Utils.updateDensity(meadowId, startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ, 0, 0);
	-- Utils.updateDensity(cuttedMeadowId, startWorldX, startWorldZ, widthWorldX, widthWorldZ, heightWorldX, heightWorldZ, 0, 0);
-- end;

function HorschSW3500S:loadFromAttributesAndNodes(xmlFile, key, resetVehicles)	
	self.Go.down = true; 
	self.Done.down = false; 
	self.Speed.down = 10.0;	
	if not resetVehicles then
		self.linkNow = Utils.getNoNil(getXMLBool(xmlFile, key.."#link"),false);
		--self.linkName = Utils.getNoNil(getXMLString(xmlFile, key.."#linkName"),false);
		local trsp = getXMLBool(xmlFile, key.."#trsp");
		if trsp then
			self.Go.trsp = not self.Go.trsp; 
			self.Done.trsp = true; 
			self.Speed.trsp = 10.0;
		end; 
	end; 
    return BaseMission.VEHICLE_LOAD_OK;
end;

function HorschSW3500S:getSaveAttributesAndNodes(nodeIdent)
	local attributes = 'link="'..tostring(self.horschImplement.attached)..'" trsp="'..tostring(self.CheckDone.trsp)..'" linkName="'..tostring(self.horschImplement.name)..'"'; 
	return attributes, nil;
end;

function HorschSW3500S:aiLower()
			self.Speed.down = 1.0; 
			self.Go.down = not self.Go.down;
			self.Done.down = true; 
	
end; 


function HorschSW3500S:aiRaise()
			self.Speed.down = 1.0; 
			self.Go.down = not self.Go.down;
			self.Done.down = true; 
end; 	

function HorschSW3500S:mouseEvent(posX, posY, isDown, isUp, button)
end;

function HorschSW3500S:keyEvent(unicode, sym, modifier, isDown)
end;



function HorschSW3500S:setStateEvent(level1, level2, value, noEventSend)
	
    if value== true then
      value = "true"
    elseif value==false then
      value = "false"
    elseif value ~= "true" and value ~= "false" then
      value = string.format("%f", value)
    end
	
	if level2== true then
      level2 = "true"
    elseif level2==false then
      level2 = "false"
    end
	
	HorschSW3500SEvent.sendEvent(self, level1, level2, value, noEventSend);
    	
	if value== "true" then
      value = true
    elseif value=="false" then
      value = false
    elseif value ~= true and value ~= false then
      value = value * 1.0
    end
	
	if level2 == "false" then
	  self[level1] = value;
	else
      self[level1][level2] = value;
	end
end;


HorschSW3500SEvent = {};
HorschSW3500SEvent_mt = Class(HorschSW3500SEvent, Event);

InitEventClass(HorschSW3500SEvent, "HorschSW3500SEvent");

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

function HorschSW3500SEvent:new(object, level1, level2, value) 
    self.object = object;
    self.level1 = level1;
    self.level2 = level2;
    self.value = value;

    return self;
end;

function HorschSW3500SEvent:readStream(streamId, connection)
    local id = streamReadInt32(streamId);
    self.level1 = streamReadString(streamId);
    self.level2 = streamReadString(streamId);
    self.value = streamReadString(streamId);
    self.object = networkGetObject(id);
    self:run(connection);
end;

function HorschSW3500SEvent:writeStream(streamId, connection)
    streamWriteInt32(streamId, networkGetObjectId(self.object));
    streamWriteString(streamId, self.level1 );
    streamWriteString(streamId, self.level2 );
    streamWriteString(streamId, self.value );
end;

function HorschSW3500SEvent:run(connection)
    self.object:setStateEvent(self.level1, self.level2, self.value, true);
    if not connection:getIsServer() then  
      g_server:broadcastEvent(HorschSW3500SEvent:new(self.object, self.level1, self.level2, self.value), nil, connection, self.object);
    end;
end;

function HorschSW3500SEvent.sendEvent(object, level1, level2, value, noEventSend)
	if noEventSend == nil or noEventSend == false then
		if g_server ~= nil then 
			g_server:broadcastEvent(HorschSW3500SEvent:new(object, level1, level2, value), nil, nil, object);
		else
			g_client:getServerConnection():sendEvent(HorschSW3500SEvent:new(object, level1, level2, value));
		end;
	end;
end;