
; Building unit/structure



; Vars

	_i = (_this select 0) - 1
	_type = (_this select 1)

	_item = ""
	_left = true
	if (_type=="Building") then {_item=BUILDINGS select _i} else {_item=UNITS select _i; _left=false}

	_idc = 105
	? !_left : _idc=112
	_idc = _idc + 14 * _i






; Status: ready, building, place

	_selector = _i
	? !_left : _selector=_i+4
	? (STATUS select _selector) == 0 : STATUS set [_selector,1]; goto "StartBuild"
	? (STATUS select _selector) == 1 : playSound "unablecomply"; exit
	? (STATUS select _selector) == 2 : if (PLACING) then {exit} else {[_i,_idc,_item,_selector] exec "Building\Place.sqs"}; exit
	player groupchat format ["error: unknown status %1", (STATUS select _selector)]
	exit






; Prepare credit and completion percentage count

	#StartBuild
	playSound "Building"
	_property = _item call findProperty
	_cost = _property select 1
	_timeToBuild = (_property select 2)*10

	_creditsSTART = CREDITS
	_creditsEaten = 0

	_creditsPER = _cost / _timeToBuild
	_creditsPER = _creditsPER - (_creditsPER  mod 1)
	? _creditsPER < 1 : _creditsPER=1

	_startTime = _time
	
	[_selector,_left,_idc] exec "SetStatus.sqs"






; Loop removing credits and increasing completion percentage

	#LowerCredits
	_percent = (_creditsEaten / _cost) * 100
	? _percent > 100 : _percent=100

	; Hurry UP
		? _time - _startTime > _timeToBuild/10 : _creditsPER=_creditsPER+2

	; Don't eat more credits than cost
		? _creditsEaten + _creditsPER > _cost : _creditsPER=_cost - _creditsEaten
	
	
	_rate = _creditsPER
	? CREDITS < _creditsPER : _rate=CREDITS
	CREDITS = CREDITS - _rate
	_creditsEaten = _creditsEaten + _rate
	
	? SIDEBAR : ctrlShow [_idc, true]
	ctrlSetText [_idc, format ["%1%2",_percent - (_percent mod 1),"%"]]
	~0.1
	? _creditsEaten >= _cost : goto "End"
	
	; Insufficient credits
		? CREDITS <= 0 : ctrlSetText [_idc, "Hold"]; playSound "onhold"
		@CREDITS > 0
		
	goto "LowerCredits"






; Finished, change title

	#End
;	player globalchat format ["%1",_time - _startTime]
	ctrlSetText [_idc, "100%"]
	? _left : playSound "ccomplete"
	? !_left : playSound "unitready"
	~0.5
	STATUS set [_selector,2]
	? _left : ctrlSetText [_idc, "Place"]; exit
	
	? !_left : ctrlSetText [_idc, "Ready"]
	_item exec "Unit\Create.sqs"
	~0.5
	MESSAGE = MYSIDE + " unit deployed"
	STATUS set [_selector,0]
	ctrlShow [_idc,false]


