وحدة:ملعب/Mr. Ibrahem/cy

من أرابيكا، الموسوعة الحرة

هذه هي النسخة الحالية من هذه الصفحة، وقام بتعديلها عبود السكاف (نقاش | مساهمات) في 23:54، 25 سبتمبر 2022. العنوان الحالي (URL) هو وصلة دائمة لهذه النسخة.

(فرق) → نسخة أقدم | نسخة حالية (فرق) | نسخة أحدث ← (فرق)
اذهب إلى التنقل اذهب إلى البحث

local p = {}
--local mw, fooA, foo3, fooC, foo1, fooB
local wiki, onwikidata
wiki = string.match(mw.site.server, "%a+")
if wiki == "www" then
	wiki = "fr"
	onwikidata = true
else
end

local available, translations = pcall(require, "Module:Cycling race/lang")
local available_list = available and type(translations.list) == "function"
local available_lang_priority = available == true and type(translations.lang_priority) == "table"


function flag(x, date)
	local year,m,d
	if date==nil then date = '+'..os.date('%Y-%m-%d') end 	
	local flag1 = { -- Q..a current flag, Q..b, Q..c older flag. date: "+2016", "+2016-01-30", ..
	Q29a={"{{رمز علم|ESP}}","+1982",""},
	Q29b={"{{رمز علم|ESP|1977}}","+1977","+1981"},
	Q30= "{{رمز علم|USA}}",
	Q31= "{{رمز علم|BEL}}",
	Q38a={"{{رمز علم|ITA}}","+1947",""},
	Q38b={"{{رمز علم|ITA|1861}}","+1861","+1946"},
	Q39="{{رمز علم|SUI}}",
	Q55= "{{رمز علم|NED}}",
	Q142="{{رمز علم|FRA}}",
	Q145="{{رمز علم|GBR}}",
	Q183a={"{{رمز علم|GER}}","+1949-05-23",""},
	Q183b={"{{رمز علم|GER|1935}}","+1935","+1945"},
	Q183c={"{{رمز علم|ألمانيا النازية|1933n}}","+1933","+1935"},
	Q183d={"[[File:Flag of Germany (3-2 aspect ratio).svg|border|20px|GER]]","+1919","+1933"},
	Q183e={"{{صورة علم|الإمبراطورية الألمانية}}","+1866","+1918"},
	Q218a={"{{رمز علم|ROU}}","+1989-12-27",""},
	Q218b={"{{رمز علم|ROU|1965}}","+1965","+1989-12-26"},
	Q218c={"{{رمز علم|ROU|1952}}","+1952","+1965"},
	Q218d={"{{رمز علم|ROU|1948}}","+1948","+1952"},
	Q218e={"{{رمز علم|ROU}}","+1867-07-01","+1948"},
	Q224a={"{{رمز علم|CRO}}","+1990-12-21",""},
	Q224b={"{{رمز علم|CRO|1990}}","+1990-06-27","+1990-12-21"}
	}

	if flag1[x..'a']~=nil and date>=flag1[x..'a'][2] and flag1[x..'a'][3]=='' then return flag1[x..'a'][1] end
	if flag1[x..'b']~=nil and date>=flag1[x..'b'][2] and date<=flag1[x..'b'][3] then return flag1[x..'b'][1] end
	if flag1[x..'c']~=nil and date>=flag1[x..'c'][2] and date<=flag1[x..'c'][3] then return flag1[x..'c'][1] end
	if flag1[x..'d']~=nil and date>=flag1[x..'d'][2] and date<=flag1[x..'d'][3] then return flag1[x..'d'][1] end
	if flag1[x..'e']~=nil and date>=flag1[x..'e'][2] and date<=flag1[x..'e'][3] then return flag1[x..'e'][1] end	
	if flag1[x]~=nil then return flag1[x] end	

	local flag2 = { Q16={'Q80110','CAN'}, Q17={'Q43175','JPN'}, Q20={'Q83149','NOR'}, Q27={'Q82205','IRL'}, Q32={'Q133022','LUX'}, Q33={'Q47891','FIN'},
	Q34={'Q81286','SWE'}, Q35={'Q60149','DEN'}, Q36={'Q42436','POL'}, Q37={'Q81477','LTU'}, Q39={'Q124020','SUI'}, Q77={'Q171103','URU'},  
	Q96={'Q122462','MEX'}, Q145={'Q83278','GBR'}, Q159={'Q16611','RUS'}, Q191={'Q81471','EST'}, Q211={'Q130449','LAT'}, Q212={'Q127974','UKR'}, 
	Q213={'Q127155','CZE'}, Q214={'Q160861','SVK'}, Q232={'Q131650','KAZ'}, Q262={'Q83392','DZA'}, Q408={'Q81676','AUS'}, Q414={'Q130774','ARG'}, 
	Q664={'Q160260','NZL'}, Q717={'Q165538','VEN'}, Q739={'Q160425','COL'} }  	

	local xx
	if flag1[x] ~= nil then return flag1[x] end

	if flag2[x]~=nil then xx = x x = flag2[x] end -- transform x to new x 
	if type(x)=='table' and pcall(foo1,x[1]) then -- for transformed x
		local entity=mw.wikibase.getEntity(x[1])
		local a,b=pcall(fooA,'value',entity,'P18',1) -- P18 (image)
		if a==true then 
			flag1[xx] = "{{صورة رمز علم|"..b.."|size=20px|alt="..x[2].."}}" 		
			return "{{صورة رمز علم|"..b.."|size=20px|alt="..x[2].."}}" 
		end 
	end
	if type(x)=='string' and pcall(foo1,x) then -- reading the flag data from untransformed items, e.g. Q29 
		local entity = mw.wikibase.getEntity( x ) 
		local flags = entity.claims["P41"]
		local possible_flag = {}
		local num = 1
		if pcall(fooA, 'numeric-id', entity, 'P41', 1) then
		local v
		for _, v in pairs(flags) do
			if v.qualifiers then
				if (not v.qualifiers["P580"] or v.qualifiers["P580"][1].datavalue.value.time <= date)
					and (not v.qualifiers["P582"] or v.qualifiers["P582"][1].datavalue.value.time >= date)
				then possible_flag[num]=v.mainsnak.datavalue.value num=num+1 end
			else possible_flag[num]=v.mainsnak.datavalue.value num=num+1 end
		end	
		local file="{{صورة رمز علم|"..possible_flag[1].."|size=20px" 
		local a2,b2=pcall(fooA,'value',entity,'P984',1) -- P984 (country code by the International Olympic Committee)				
		if a2==true then file=file.."|alt="..b2.."}}" else file=file.."}}" end 
		flag1[x] = file		
		return file
		end	
	end 
	return " "
end 


function references(entity, property, var1)
	local ref1, ref2, ref2b, ref3, ref4 = "", " ", "", "", ""
	local url, ref
	local lang = mw.language.getContentLanguage()
	local a, b

	if onwikidata then lang = mw.getLanguage('fr') end

	a, b = pcall(fooB, 'value', entity, property, var1, 1, 'P854', 1) -- url
	if a == true then ref1 = b end
	a, b = pcall(fooB, 'text', entity, property, var1, 1, 'P1476', 1) -- Originaltitel der webpage, "language": "fr"
	if a == true then 
		ref2 = b 
		ref2b= entity.claims[property][var1].references[1].snaks['P1476'][1].datavalue.value.language or ''
		if ref2b == wiki then ref2b = '' else ref2b = '(' .. ref2b .. ') ' end
	end
	a, b = pcall(fooB, 'time', entity, property, var1, 1, 'P577', 1) -- publication date
	if a == true then
		local _, _, year, m, d = string.find(b,"(%d+)-(%d+)-(%d+)")
		if d ~= '00' and m ~= '00' then
			if wiki == "de" then ref3 = ', ' .. lang:formatDate( "j. F Y", b) 
			elseif wiki == "ar" then ref3 = ', ' .. lang:formatDate( "j F Y", b) .. '.' 
			elseif wiki == "en" then ref3 = ', ' .. lang:formatDate( "Y F, j", b) .. '.' 
			elseif wiki == "fr" then ref3 = ', ' .. lang:formatDate( "j F Y", b)
			else ref3 = ', ' .. func_date (b, 'long') .. '.'  --lang:formatDate( "j n Y", b) .. '.' 
			end
		elseif d == '00' and m ~= '00' then
			d = '01'
			if wiki == "de" then ref3 = ', ' .. lang:formatDate( "F Y", year..'-'..m..'-'..d ) 
			elseif wiki == "ar" then ref3 =', ' .. lang:formatDate( "F Y", year..'-'..m..'-'..d )..'.'
			elseif wiki == "en" then ref3 =', ' .. lang:formatDate( "Y F", year..'-'..m..'-'..d )..'.'
			elseif wiki == "fr" then ref3 =', ' .. lang:formatDate( "F Y", year..'-'..m..'-'..d )				
			else ref3 = ', ' .. lang:formatDate( "F Y", year..'-'..m..'-'..d )..'.'
			end
		else ref3 = year 
		end
	end
	a, b = pcall(fooB, 'time', entity, property, var1, 1, 'P813', 1) -- Retrieved
	if a == true then 
		if wiki == "de" then ref4 = ", (abgerufen am " .. lang:formatDate( "j. F Y", b).. ')'
		elseif wiki == "ar" then ref4 = " Retrieved " .. lang:formatDate( "j F Y", b) .. '.'
		elseif wiki == "en" then ref4 = " Retrieved " .. lang:formatDate( "Y F, j", b) .. '.'
		elseif wiki == "fr" then ref4 = " (consulté le " .. lang:formatDate( "j F Y", b) .. ')'
		else ref4 = " Retrieved " .. func_date (b, 'long').. '.' --lang:formatDate( "j n Y", b) .. '.'
		end
	end

	if ref1~='' then --and ref2~='' then
		local _, start = string.find( ref1, '//' ) 
		local ende, _ = string.find( ref1, '/', start + 1 )
		local s = string.sub(ref1, start + 1, ende - 1) 
		local s2 = string.gsub(s, "www.", "")
		if wiki == "fr" then 
		-- fr: "(en) « Lloyd Mondory ... EPO », sur velonews.competitor.com (consulté le 30 april 2016), 30 octobre 2015." 
			if ref2~=' ' then url= ', sur <span style="font-style:italic;">' .. s2 .. '</span>' else url='' end
			ref = ref2b .. '« ['.. ref1.. ' '.. ref2.. '] »' .. url .. ref4 .. ref3 ..'.'
		elseif wiki == "en" then 
		-- en: "Inflation ... recession", Pittsburgh Post-Gazette, October 16, 2009. Retrieved 2010-01-21.
			if ref2~=' ' then url= ', <span style="font-style:italic;">' .. s2 .. '</span>' else url='' end
			ref = '"['.. ref1.. ' '.. ref2.. '"]'.. ref2b .. url .. ref3 .. ref4			
		elseif wiki == "de" then 
			if ref2~=' ' then url= ' In: <span style="font-style:italic;">' .. s2 .. '</span>' else url='' end			
			ref = '<span style="font-style:italic;">['.. ref1.. ' '.. ref2.. '.]</span> '.. url.. ref3 .. ref4 ..'.'
		else 
			if ref2~=' ' then url= ' <span style="font-style:italic;">' .. s2 .. '</span>' else url='' end			
			ref = ref2b .. '['.. ref1.. ' '.. ref2.. '] ' .. url.. ref3 .. ref4 
		end
	return ref or ''
	else return ''
	end 
end


function black_list(wiki, Label)
	-- List of Wikipedia articles with the same lemma as the non existing rider article. Those lemmas are printed as text "black" in the tables, 
	-- not "blue" or "red". This way there will be no false wikilinks at the WhatLinksHere entry. List should be updated maybe once a year. 
	local black_list = {}
	if wiki=='de' then black_list={ ["Ryan Anderson"]=true, ["Chris Butler"]=true, ["Josef Černý"]=true, ["Brad Evans"]=true, ["Robert Fontaine"]=true, 
		["Carlos Giménez"]=true, ["George Harper"]=true, ["Mathias Jørgensen"]=true, ["Luis Lemus"]=true, ["David Lozano"]=true, ["Jan Maas"]=true, 
		["James McLaughlin"]=true, ["Nikolaj Michajlow"]=true, ["Antonio Molina"]=true, ["Ben O'Connor"]=true, ["Andrea Peron"]=true, ["Cristian Rodríguez"]=true, 
		["Nick Schultz"]=true, ["Adam Stachowiak"]=true, ["Michel Vermote"]=true, ["Johannes Weber"]=true, ["Martin Weiss"]=true, ["Christopher Williams"]=true, 
		["Samuel Williams"]=true, ["Peter Williams"]=true, ['Stephen Williams']=true, ["Michael Woods"]=true, ["Michael Wright"] = true, ["Edoardo Zardini"]=true, 
		["Georg Zimmermann"]=true } end
	if wiki=='en' then black_list={ ["Tiago da Silva"]=true, ["Jan Maas"]=true, ["Alexander Meier"]=true, ["James McLaughlin"]=true, ["Andrea Nencini"]=true, 
		["Johannes Weber"]=true } end
	if wiki=='fr' then black_list={['Pierre Barbier']=true, ['Jessica Cutler']=true, ['Fernanda da Silva']=true, ['Guillaume Delvaux']=true, ['Willy De Waele']=true, 
		['Jules Dubois']=true, ['Jean Dupont']=true, ['Robert Fontaine']=true, ['René Fournier']=true, ['Pierre Gauthier']=true, ['Marc Goossens']=true, 
		['Claude Guyot']=true, ['Amy Hill']=true, ['Liang Hongyu']=true, ['Marcus Johansson']=true, ['Mathias Jørgensen']=true, ['José Mendoza']=true, 
		['Daniel Müller']=true, ['Henri Parmentier']=true, ['Jean Raynal']=true, ['Pascal Robert']=true, ['Jean-Yves Roy']=true, ['Michael Shermer']=true, 
		['Juris Silovs']=true, ['Jacques Simon']=true, ['Guy Thomas']=true, ['Ryan Thomas']=true, ['Hans Vonk']=true, ['Jan Wijnants']=true } end
	return black_list[Label]
end


function WPlink(Qnumber, ...) 
	local link=''
	local entity = mw.wikibase.getEntity( Qnumber )
	local Sitelink = entity:getSitelink() -- link to WParticle
	local Sitelink2 = Sitelink
	local Label = entity:getLabel('ar') or ''
	local Label_fr = entity:getLabel( 'fr' ) or ''
	local a, b
	local official_name = ""
	
	if arg[1] == nil then 	
		if pcall(foo1, Qnumber) then 
			if Sitelink ~= nil then 
				if wiki=="en" then --delete string ", ..." from e.g. "Unley, South Australia"
					if Sitelink~=nil then
						local i, _ = mw.ustring.find(Sitelink, ",")
						if i ~= nil then Sitelink2 = mw.ustring.sub(Sitelink, 1, i-1) end
					end
				end
				link = "[[" .. Sitelink .. "|" .. mw.text.trim(mw.ustring.gsub(Sitelink2, "%b()", "")..' ') .. "]]"	
				if wiki == "de" then -- ru riders get label as alias, to shorten the name
					local a, b = pcall(fooA, 'numeric-id', entity, 'P27', 1) 
					if a == true and (b==159 or b==184 or b==212 or b==232) then link = "[[" .. Sitelink .. "|" .. Label .. "]]" end
				end
			elseif Label ~= '' then 
				if wiki == 'ar' then
					local title = mw.title.new(Label)
					if title and title.exists 
						then link = Label 
				else link = mw.getCurrentFrame():expandTemplate{ title = 'Ill-WD2', args = {id=Qnumber,target='en',label=Label } }--"[[" .. Label.. "]]" 
					end
					
				else
					if black_list(wiki, Label) == true then 
						link = Label -- function black_list: articles that are printed as text, not wikilinks
					else -- detect if there is a different local article with the same name
						local title = mw.title.new(Label)
						if title and title.exists then link = Label else link = "[[" .. Label.. "]]" end
					end
				end
			else link = Label end 
		else return "unknown ID in function WPlink" end
	if link == '' then 
			link = entity:getLabel('fr') or entity:getLabel('en') or entity:getLabel('de') or ''
			if wiki == "ar" then link = entity:getLabel('ar') or entity:getLabel('en') or entity:getLabel('fr') or entity:getLabel('de') or '' end
			if link ~= '' then link = mw.ustring.gsub(link, "%b()", "")
			else link =  "(label missing)" end  
		end
	end -- if arg[1] == nil
	if arg[1] == 'team' then -- add '(team of the winner)'
		a, b = timeStartEnd(Qnumber, 'P1448', 'text', arg[2]) --officialName(entity) 
		local a1, b1 = pcall(fooA, 'numeric-id', entity, 'P361', 1)
		if a1== true then 
			local a2, b2 = timeStartEnd('Q'..b1, 'P1448', 'text', arg[2]) 
			if a2== true then a = a2 b = b2	end
			entity = mw.wikibase.getEntity( 'Q'..b1 ) 
			Sitelink2 = entity:getSitelink() -- link to WParticle		
		end
		if a == true then official_name = b end
		
		if available_lang_priority == false then
			a, b = pcall(fooA, 'text', entity, 'P1448', 2) -- test if more then two official names
			if a == true then
				a, b = timeStartEnd(Qnumber, 'P1448', 'text', arg[2]) --officialName(entity) 
				if a == true then official_name = b end
			else
				a, b = pcall(fooA, 'text', entity, 'P1448', 1) 
				if a == true then official_name = b end	
			end
		end
				
		if Sitelink ~= nil then 
			if official_name == nil then 
				link = "[[".. Sitelink.. "|".. mw.text.trim(mw.ustring.gsub(Sitelink,"%b()","").. ' ') .. "]]" 
			else
				if wiki=="en" then --delete string ", ..." from e.g. "Unley, South Australia"
					local i, _ = mw.ustring.find(Sitelink, ",")
					if i ~= nil then Sitelink = mw.ustring.sub(Sitelink, 1, i-1) end
				end
				link = link .. '[['.. Sitelink.. "|".. official_name.. ']]'
			end
		end
		if link == '' and Sitelink2 ~= nil then -- code goes from season item to team item
			if official_name == nil or official_name == '' then
				link = "[[".. Sitelink2.. "|".. mw.text.trim(mw.ustring.gsub(Sitelink2,"%b()","").. ' ') .. "]]" 	
			else
				if wiki=="en" then --delete string ", ..." from e.g. "Unley, South Australia"
					local i, _ = mw.ustring.find(Sitelink2, ",")
					if i ~= nil then Sitelink2 = mw.ustring.sub(Sitelink2, 1, i-1) end
				end		
				link = link .. '[['.. Sitelink2.."|".. official_name.. ']]' 
			end		
		end

		if Sitelink == nil and Sitelink2 == nil then 
			if official_name ~='' then link = official_name else link = entity:getLabel('ar') end
			if link == nil then link = "(label missing)" end
		end	
	
	-- mw.log('Sitelink=', Sitelink, 'Sitelink2=', Sitelink2, 'official_name=',  official_name) 
	end -- end arg[1]
	if arg[1] == 'pure' then
		if pcall(foo1, Qnumber) then
			if wiki == "en" then --delete string ", ..." from e.g. "Unley, South Australia"
				if Sitelink~=nil then
					local i, _ = mw.ustring.find(Sitelink, ",")
					if i ~= nil then Sitelink2 = mw.ustring.sub(Sitelink, 1, i-1) end
				end
			end		
			if Sitelink ~= nil then link = "[[" .. Sitelink .. "|" .. mw.text.trim(mw.ustring.gsub(Sitelink2, "%b()", "")..' ') .. "]]"	
			elseif wiki == 'ar' then
				local title = mw.title.new(Label)
				if title and title.exists 
					then link = Label 
				else link = mw.getCurrentFrame():expandTemplate{ title = 'Ill-WD2', args = {id=Qnumber,target='en',label=Label } }--"[[" .. Label.. "]]" 
				end
			else link = mw.ustring.gsub(Label, "^(%a)", function (x) return mw.ustring.upper(x) end)		
			end 
		end
	end
	if arg[1] == 'race' then -- for infobox "Competitions"
		local a, b = pcall(fooA, 'numeric-id', entity, 'P31', 1)
		if a == true and b == 1137352 then
			local entity_race = mw.wikibase.getEntity( 'Q' .. b )
			local Label_race = entity_race:getLabel('ar') or ''
			local Sitelink_race = entity_race:getSitelink() or ''
			if Label_race ~= '' and Sitelink ~= nil then link = '[[' .. Sitelink .. '|' .. Label_race .. ']]'
			elseif Sitelink ~= nil then link = '[[' .. Sitelink .. ']]'
			else if Sitelink_race ~= '' then link = '[[' .. Sitelink_race ..'|' .. mw.text.trim(mw.ustring.gsub(Sitelink_race, "%b()", "") .. ' ') .. ']]'
				else link = Label_race or Label end
			end
			if onwikidata == true then link = '[['..entity:getSitelink( 'frwiki')..'|'..entity_race:getLabel('fr')..']]' end
	
		else if Sitelink ~= nil then link = "[[".. Sitelink.. "]]" else link = Label end
		end
	end
	if arg[1] == "Q22348500" then -- add weblink from item "Q22348500" if available
		local Sitelink_claas = mw.wikibase.getEntity( 'Q22348500' ):getSitelink() 	
		if pcall(foo1, Qnumber) then --Sitelink_claas
			if Sitelink == nil then 
				if Sitelink_claas ~= nil then link = "[[" .. Sitelink_claas .. "|" .. Label .. "]]" 
				elseif entity:getLabel( 'ar' )~=nil then link = entity:getLabel( 'ar' )
				elseif entity:getLabel( 'fr' )~=nil then link = entity:getLabel( 'fr' )
				elseif entity:getLabel( 'en' )~=nil then link = entity:getLabel( 'en' )
				elseif entity:getLabel( 'de' )~=nil then link = entity:getLabel( 'de' )				
				else link = Label 
				end 
			end
		end
	end
	return link
end


function national_team(riderID, startOfSeason, entity, property, k)
	-- property: statement where the rider is the value
	-- k: loop
	local national_team, team, nationality, teamID
	-- national team for U23 or older riders
	if pcall(function()
		local i,j, s 
		for _, v in pairs(entity.claims[property][k].qualifiers['P54']) do -- for property 'member of sports team'
			teamID = 'Q'.. v.datavalue.value['numeric-id'] break
		end
	
		national_team = mw.wikibase.getEntity( teamID )
		-- calculate s for national team item
		a, b = pcall(fooA, 'numeric-id', national_team, 'P31', 1) -- test if country
		if a == true and b == 20738667 then -- Q20738667 = national cycling team U23
			if wiki == 'fr' then s =  ' espoirs' else s = ' U23' end
			if wiki == 'mk' then s = ' под 23 години' end
			if wiki == 'ar' then s = ' تحت 23' end
		elseif a == true and (b == 1194951 or b == 23726798) then s = '' end 
			-- Q1194951 = national sports team, Q23726798 = national cycling team
	
		a, b = timeStartEnd(riderID, "P27", 'numeric-id', startOfSeason)
		if a == true then
			local nation = mw.wikibase.getEntityObject( 'Q'..b )
			nationality = nation:getLabel('ar') or nation:getLabel('en') .. ' (en)'
			if national_team:getSitelink() == nil then
				team = nationality.. s
			else
				team = "[[".. national_team:getSitelink().. "|".. nationality.. s.. ']]'
			end
		end

		a, b = timeStartEnd(riderID, "P17", 'numeric-id', startOfSeason)
		if a == true then --team = 'abc'.. b --riderID
			local nation = mw.wikibase.getEntityObject( 'Q'..b )
			nationality = nation:getLabel('ar') or nation:getLabel('en') .. ' (en)'
			if national_team:getSitelink() == nil then
				team = nationality.. s
			else
				team = "[[".. national_team:getSitelink().. "|".. nationality.. s.. ']]'
			end	
		end
	end) then 
	else 
		--standard team
		pcall(function()
		a, b = timeStartEnd(riderID, 'P54', 'numeric-id', startOfSeason)
		if a == true then
			national_team = mw.wikibase.getEntity( 'Q'..b )
	--		g.team[rank] = national_team:getLabel('ar') or g.country[rank].. s
			team = WPlink('Q'..b, 'team', startOfSeason)
		end
		-- guest team
		if teamID ~= nil then team = WPlink(teamID, 'team') end
		end)
	end
	
	return team
end

function timeStartEnd(Qid, property, mode, timeofrace)
	-- mode = 'numeric-id', property = 'P54', Qid = 'Q123'
	local entity = 	mw.wikibase.getEntity(Qid)
	local a, b = pcall(fooA, mode, entity, property, 1)
	local starttime, endtime
	local available_lang_priority = available_lang_priority
	
	if a == true then
		local timeStartEnd = {}
		local num = 1
		local v
		for _, v in pairs(entity.claims[property]) do
			if pcall(function () local test = v.mainsnak.datavalue.value[mode] end) then -- test if not 'unnown value' 
				if pcall(function () starttime = v.qualifiers["P580"][1].datavalue.value.time end) then
	   				starttime = v.qualifiers["P580"][1].datavalue.value.time
					local _,_,year,m,d = string.find(starttime,"(%d+)-(%d+)-(%d+)")
					if m == '00' and d == '00' then starttime = '+'..year..'-01-01T00:00:00Z' end
				end
				if pcall(function () endtime = v.qualifiers["P582"][1].datavalue.value.time end) then
					endtime = v.qualifiers["P582"][1].datavalue.value.time
					local _,_,year,m,d = string.find(endtime,"(%d+)-(%d+)-(%d+)")
					if m == '00' and d == '00' then endtime = '+'..year..'-12-31T00:00:00Z' end
					if m == '01' and d == '01' then endtime = '+'..year..'-12-31T00:00:00Z' end
				end
	  			if v.qualifiers then
	 				if (not v.qualifiers["P580"] or starttime <= timeofrace)
	 					and
	 					(not v.qualifiers["P582"] or endtime >= timeofrace)
	 				then
	 					if available_lang_priority == true and property == "P1448" then
	 						local test = false
							pcall(function () if type( v.qualifiers["P1448"])=='table' then test=true end end)
							if test == false then
								timeStartEnd[num] = v.mainsnak.datavalue.value[mode]
							else
								local lang_module, lang_WD
								local language= ''
								local zaehler
								for i,j in ipairs(translations.lang_priority) do
										lang_module = j
										for number in pairs(v.qualifiers["P1448"]) do
											lang_WD = v.qualifiers["P1448"][number].datavalue.value.language
											if lang_WD == lang_module then zaehler = number break end
										end -- for number in pairs
									if lang_WD == lang_module then language = lang_WD   break end
									end -- for i,j
								if language~='' then -- a WD translation matching translations.lang_priority exist
										local t = v.qualifiers["P1448"][zaehler].datavalue.value.text
										timeStartEnd[num] = t
		 							else timeStartEnd[num] = v.mainsnak.datavalue.value[mode]--  no matching between lang module and "official name" qualifier
									end -- if language~=''
							end --  test if official name qualifier exist
	 					else timeStartEnd[num] = v.mainsnak.datavalue.value[mode]
						end -- if property == "P1448"
	  					num = num + 1
	 				end
	 			else
	 				timeStartEnd[num] = v.mainsnak.datavalue.value[mode]
	 				num = num + 1
	 			end
			end
	 	end
		return a, timeStartEnd[1]
	else return false, '' end
end


function func_date (date, mode)
	--	local date = '+2016-05-20'
	--	local mode = 'small'
	local function standard(datum) 
		if mode=='long' then return mw.language.getContentLanguage():formatDate("j F Y", datum) end 
		if mode=='small' then return mw.language.getContentLanguage():formatDate("j M", datum) end 	
		if mode=='onlyday' then return mw.language.getContentLanguage():formatDate("j", datum) end
	end
	local function ar(datum) 
		local lang = mw.getLanguage('ar') 
		if mode=='long' then return mw.getLanguage('ar'):formatDate("d F Y", datum) end 
		if mode=='small' then return mw.getLanguage('ar'):formatDate("d F", datum) end	
		if mode=='onlyday' then return mw.getLanguage('ar'):formatDate("d", datum) end
		end
	local function br(datum) 
		local lang = mw.getLanguage('br') 
		if mode=='long' then return lang:formatDate("j", datum ) .." a viz ".. lang:formatDate("F Y", datum) end 
		if mode=='small' then return lang:formatDate("j", datum ) .." a viz ".. lang:formatDate("M", datum) end 
		if mode=='onlyday' then return lang:formatDate("j", datum ) end 
	end	
	local function ca(datum, language) 
		local lang = mw.getLanguage(language) 
		if mode=='long' then return lang:formatDate("j", datum) .." de ".. lang:formatDate("F", datum) .." de ".. lang:formatDate("Y", datum) end 
		if mode=='small' then return lang:formatDate("j", datum) .." de ".. lang:formatDate("M", datum) end 
		if mode=='onlyday' then return lang:formatDate("j", datum) end 
	end
	local function cs(datum)
		local lang = mw.getLanguage('cs') 		
		if mode=='long' then return lang:formatDate("j. xg Y", datum) end 
		if mode=='small' then return lang:formatDate("j", datum)  ..". xg ".. lang:formatDate("M", datum) end 
		if mode=='onlyday' then return lang:formatDate("j", datum) end 	
	end
	local function de(datum, language) 
		if mode=='long' then return mw.getLanguage(language):formatDate("j. F Y", datum) end 
		if mode=='small' then return mw.getLanguage(language):formatDate("j. M", datum) end 
		if mode=='onlyday' then return mw.getLanguage(language):formatDate("j.", datum) end 
	end		
	local function eo(datum) 
		local lang = mw.getLanguage('eo') 
		if mode=='long' then return lang:formatDate("j", datum) .."-a de ".. lang:formatDate("F Y", datum) end 
		if mode=='small' then return lang:formatDate("j", datum) .."-a de ".. lang:formatDate("M", datum) end 
		if mode=='onlyday' then return lang:formatDate("j", datum) end 
	end	
	local function en(datum) 
		if mode=='long' then return mw.getLanguage('en'):formatDate("F d, Y", datum) end 
		if mode=='small' then return mw.getLanguage('en'):formatDate("M d", datum) end 	
		if mode=='onlyday' then return mw.getLanguage('en'):formatDate("d", datum) end 	
		end
	local function eu(datum) 
		local lang = mw.getLanguage('eu') 
		if mode=='long' then return lang:formatDate( "Y", datum) ..".eko ".. lang:formatDate("F", datum) .."k ".. lang:formatDate("j", datum) end 
		if mode=='small' then return lang:formatDate( "M", datum) .."k ".. lang:formatDate("j", datum) end 	
		if mode=='onlyday' then return lang:formatDate("j", datum) end 	
	end
	local function fi(datum) -- may be different
		if mode=='long' then return mw.ustring.gsub(mw.getLanguage('fi'):formatDate("j. F Y", date), "%a+", "%0ta") end 
		if mode=='small' then return mw.getLanguage('fi'):formatDate("j. M", date) end
		if mode=='onlyday' then return mw.getLanguage('fi'):formatDate("j.", date) end
	end 
	local function hu(datum) 
		local lang = mw.getLanguage('hu') 
		if mode=='long' then return lang:formatDate( "Y", datum) ..". ".. lang:formatDate("F", datum) .." ".. lang:formatDate("j", datum)..". " end
		if mode=='small' then return lang:formatDate( "M", datum) ..". ".. lang:formatDate("j", datum) end 
		if mode=='onlyday' then return lang:formatDate("j", datum) end 
	end
	local function ja(datum) 
		if mode=='long' then return mw.getLanguage('ja'):formatDate("Y年m月d日", datum) end 
		if mode=='small' then return mw.getLanguage('ja'):formatDate("m月d日", datum) end	
		if mode=='onlyday' then return mw.getLanguage('ja'):formatDate("d日", datum) end	
	end	
	local function lv(datum)
		local lang = mw.getLanguage('lv') 
		if mode=='long' then return lang:formatDate("Y.", datum)  .." gada ".. lang:formatDate("j. F", datum) end 
		if mode=='small' then return lang:formatDate("j. M", datum) end
		if mode=='onlyday' then return lang:formatDate("j.", datum) end 
	end 	
	local function pl(datum) 
		local lang = mw.getLanguage('pl') 
		local date_pl = {"stycznia", "lutego", "marca", "kwietnia", "maja", "czerwca", "lipca", "sierpnia", "września", "października", "listopada", "grudnia"}
		if mode=='long' then return lang:formatDate("j ", datum) .. date_pl[tonumber(lang:formatDate("n", datum))] .. lang:formatDate(" Y", datum) end 
		if mode=='small' then return lang:formatDate("j M", datum) end 	
		if mode=='onlyday' then return lang:formatDate("j", datum) end 	
	end		

	local x = {['']=standard(date), ['ar']=ar(date),  ['br']=br(date), ['ca']=ca(date,'ca'), ['cs']=cs(date), ['da']=de(date,'da'), ['de']=de(date,'de'), ['en']=en(date), ['eo']=eo(date), 
		['es']=ca(date,'es'), ['eu']=eu(date), ['fi']=fi(date), ['fo']=de(date,'fo'), ['hu']=hu(date), ['ja']=ja(date), ['lv']=lv(date), ['no']=de(date,'no'), ['pl']=pl(date)}

	return x[wiki] or x['']
end


function infobox_translate(x)
	-- This function permits to translate fields of the infobox, take the line below, give a Wikipedia (ex : mk), and translate all fields. By default, English values are taken.
	-- l10nDef["//??.wikipedia.org"] = {"RACE DETAILS", "COURSE", "COMPETITION", "COMPETITIONS", "STAGES", "DATE", "DATES", "DISTANCE", "COUNTRY", "COUNTRIES", 
	-- "JOURNEY ORIGIN", "JOURNEY DESTINATION", "TEAMS", "STARTING RIDERS", "ARRIVING RIDERS", "AVERAGE SPEED", "COST", "PALMARES", "WINNER", "SECOND", "THIRD", 
	-- "POINTS", "MOUNTAINS", "SPRINTS", "YOUTH", "COMBATIVITY", "COMBINATION", "TEAM", "Picture", "Caption", "Map", "Special 1", "Special 2", "Documentation", 
	-- "METAS VOLANTES", "REGULARIDAD", "TEAM POINTS"}
 	local l10nDef = { }
	l10nDef["ar"] = {"تفاصيل السباق", "سلسلة", "منافسة", "مسابقات", "مراحل", "التاريخ", "التواريخ", "المسافات", "البلد", "البلدان",
	"نقطة البداية", "نقطة النهاية", "الفرق", "عدد المتسابقين في البداية", "عدد المتسابقين في النهاية", "متوسط السرعة", "الكلفة", "المنصة", "الفائز", "الثاني", 
	"الثالث", "حسب النقاط", "تسلق الجبل", "سباقات السرعة", "أفضل شاب", "تصنيف القتال", "مجموعة", "الفريق", "صورة", "تعليق", "خريطة", "مميز 1", "مميز 2", "توثيق", "سباقات السرعة", "انتظام", "نقاط الفريق", "فوجا بيناريلو", "أزوري دي إيطاليا"}
	l10nDef["en"] = {"Race details", "Course", "Competition", "Competitions", "Stages", "Date", "Dates", "Distance", "Country", "Countries",
	"Journey origin", "Journey destination", "Teams", "Starting riders", "Arriving riders", "Average speed", "Cost", "Palmares", "Winner", "Second", 
	"Third", "Points", "Mountains", "Sprints", "Youth", "Combativity", "Combination", "Team", "Picture", "Caption", "Map", "Special 1", "Special 2", 
	"Documentation", "Intermediate sprints", "Regularidad", "Team points", "Fuga Pinarello", "Azzurri d'Italia"}
	
	local l10n = l10nDef[wiki]
	if not l10n then l10n = l10nDef["en"] end  -- default
	return l10n[x]
end 


function p.winnertable(frame)
	local t = {is_a="", class="", stage="", starttime="", endtime="", time="", date="", dates="", length="", length_unit="", 
	startplace="", endplace="", nr_teams="", nr_participants_start="", nr_participants_end="", speed="", speed_unit="", cost="", cost_unit="", 
	first="", first_team="", second="", second_team="", third="", third_team="", winner_point="", winner_point_team="", winner_mountain="", winner_mountain_team="", 
	winner_sprint="", winner_sprint_team="", winner_young="", winner_young_team="", winner_fighting="", winner_fighting_team="", winner_combination="", 
	winner_combination_team="", winner_metas_volantes="", winner_metas_volantes_team="", winner_regularity="", winner_regularity_team="", 
	winner_fuga_pinarello="", winner_fuga_pinarello_team="", winner_azzurri_ditalia="", winner_azzurri_ditalia_team="", winner_team="", 
	winner_team_points="", previous="", next=""}
	local ref = {stage="", starttime="", endtime="", time="", date="", dates="", length="", nr_participants_start="", nr_participants_end="", 
	speed="", speed_unit="", cost="", first="", second="", third="", winner_point="", winner_mountain="", winner_sprint="", winner_young="", 
	winner_fighting="", winner_metas_volantes="", winner_regularity="", winner_combination="", winner_fuga_pinarello="", winner_azzurri_ditalia="", 
	winner_team="", winner_team_points=""}
	local tt = {icon="", picture="", caption="", name="", nr="", map="" }
	local ttt = {tour={}, country={}}
	local tttt = {special_1a="", special_1b="", special_2a="", special_2b=""}
	
	local entity = ""
	local y, m, d = "", "", ""
	local y2, m2, d2 = "", "", ""
	local a, b, c, k, num, i
	local entityId = frame.args[1]
	local lang = mw.language.getContentLanguage()
	local wiki = string.match(mw.site.server, "%a+")
	local results = false
	local a1, b1, c1, a2, b2, c2
	local timeofrace


	if type( entityId ) ~= 'string' then error( 'parameter must be a string') end
	if not entityId:match( 'Q%d+' ) then error ( 'parameter must be a valid Wikidata item (ex: Q42)' ) end
	local entity = mw.wikibase.getEntity( entityId )

	local localFrame 
	if string.match(frame:getParent():getTitle(), '%P+') == mw.site.namespaces.Template.name 
	then localFrame = frame:getParent() else localFrame = frame end

	if localFrame.args[infobox_translate(29)] then tt.picture = localFrame.args[infobox_translate(29)] end 
	if localFrame.args[infobox_translate(30)] then tt.caption = localFrame.args[infobox_translate(30)] end 
	if localFrame.args[infobox_translate(31)] then tt.map = localFrame.args[infobox_translate(31)] end 

	if  entity:getLabel('ar') ~= nil then tt.name = entity:getLabel('ar')
	else
		if entity:getLabel( 'fr' ) ~= nil then tt.name = entity:getLabel( 'fr' ).. " (fr)"
		else tt.name = "Wikidata doesn´t know" end 
	end

	a, b = pcall(fooA, 'numeric-id', entity, 'P641', 1) 
	if a == true then -- icon for road bicycle racing, Q3609 (road bicycle racing)
		if b == 3609 then tt.icon = " [[File:Cycling (road) pictogram.svg|35px]]" end 
	end
	a, b = pcall(fooA, 'value', entity, 'P18', 1) 
	if a == true and tt.picture == "" then 
		local v
		tt.picture = b
		if pcall(foo3, entity, "P18", 1, "P2096", 1) then
			for _, v in pairs(entity.claims["P18"]) do
				for num=1,#v.qualifiers["P2096"] do
					if v.qualifiers["P2096"][num].datavalue.value.language == lang:getCode() then
					tt.caption = v.qualifiers["P2096"][num].datavalue.value.text end
				end
			end
		end
	end
	
	-- For FR Wiki and Wikidata, exception that permit to display 1er, 2e... for the edition number ; 
	-- for RU Wiki, -й is written after the value of P393
	a, b = pcall(fooA, 'value', entity, 'P393', 1)
	if a == true and tt.nr == "" then
		tt.nr = b .. ". "
		if wiki == "fr" or wiki == "www" then
			if b == 1  then tt.nr = "1<sup>re</sup> " else tt.nr = b .."<sup>e</sup> " end end
		if wiki == "nl" then tt.nr = b .."e " end
		if wiki == "ru" then tt.nr = b .."-й " end
		if wiki == "eo" then tt.nr = b .."-a " end
		if wiki == "cs" then tt.nr = b ..". " end
		if wiki == "hu" then tt.nr = b .."-ik " end
	end
	-- Class of a cycling race. Class is: 1.UWT, 2.UWT, 1.HC, ... add new classes, no problem
	local class = { "Q22231106", "Q22231107", "Q22231108", "Q22231109", "Q22231110", "Q22231111", "Q22231112",
		"Q22231113", "Q22231114", "Q22231115", "Q22231116", "Q22231117", "Q22231118", "Q22231119", "Q23015458", "Q23005601", "Q23005603" } 
	a, b = pcall(fooA, 'numeric-id', entity, 'P31', 1) -- first value for P31
	c, d = pcall(fooA, 'numeric-id', entity, 'P31', 2) -- second value for P31
	if a == true and c == true then -- for two values
		for i=1,#class do -- #class = number of elements in class
   			if "Q"..b == class[i] then t.class = "c"..b t.is_a = "Q"..d break end
   			if "Q"..d == class[i] then t.class = "c"..d t.is_a = "Q"..b break end  		
   		end
 	else -- if there is only one value, assume it is not a class
		if a == true or c == true then t.is_a = "Q"..b end
	end

	a, b = pcall(fooA, 'numeric-id', entity, 'P361', 1) -- Competition of the cycling race : UCI World Tour 2016, UCI Europe Tour 2016...
	if a == true then --ttt.tour = "Q" .. b end
		local i, v
		for i, v in pairs(entity.claims["P361"]) do
			ttt.tour[i] = "T" .. v.mainsnak.datavalue.value["numeric-id"]
		end
	end

	if t.stage == "" then
		if pcall(function() -- This function count the number of value for P527 to determine the number of stages
			t.stage = entity.claims["P527"]
		end
		) then else t.stage = "" end
	end

	a1, b1, c1 = pcall(fooA, 'time', entity, 'P580', 1) 
	if a1 == true and t.starttime == "" then i = 1
		while a1 == true and c1 == 'deprecated' do 
			i = i + 1 
			a1, b1, c1 = pcall(fooA, 'time', entity, 'P580', i) 
		end  
		--b1 = "+2015-07-04T00:00:00Z"
		_, _, y, m, d = string.find(b1, "(%d+)-(%d+)-(%d+)")  
	end
	a2, b2, c2 = pcall(fooA, 'time', entity, 'P582', 1) 
	if a2 == true and t.endtime == "" then i = 1
		while a2 == true and c2 == 'deprecated' do 
			i = i + 1 
			a2, b2, c2 = pcall(fooA, 'time', entity, 'P582', i) 
		end  
		--b2 = "+2015-07-05T00:00:00Z"
		_, _, y2, m2, d2 = string.find(b2, "(%d+)-(%d+)-(%d+)")
	end
	if a1 == true and t.starttime == "" then 
		if y ~= y2 then t.starttime = lang:formatDate( "j F Y", b1 ) 
		elseif m ~= m2 then t.starttime = lang:formatDate( "j F", b1 )
		else t.starttime = lang:formatDate( "j", b1 )
		end
		if wiki == "ar" then 
			if y ~= y2 then t.starttime = lang:formatDate( "d F Y", b1 ) 		
			elseif m ~= m2 then t.starttime = lang:formatDate( "d F", b1 )	
			else t.starttime = lang:formatDate( "d F", b1 )
			end	end		

		if wiki == "en" then 
			if y ~= y2 then t.starttime = lang:formatDate( "F d, Y", b1 ) 		
			elseif m ~= m2 then t.starttime = lang:formatDate( "F d", b1 )	
			else t.starttime = lang:formatDate( "F d", b1 )
			end	end			
	end -- if a1
	if a2 == true and t.endtime == "" then 
		t.endtime = lang:formatDate( "j F Y", b2 ) 
		timeofrace = b2
		if wiki == "ar" then
			if y ~= y2 then t.endtime = lang:formatDate( "d F Y", b2 ) 		
			elseif m ~= m2 then t.endtime = lang:formatDate( "d F Y", b2 )	
			else t.endtime = lang:formatDate( "d، Y", b2 )	
			end	end	
		if wiki == "en" then
			if y ~= y2 then t.endtime = lang:formatDate( "F d, Y", b2 ) 		
			elseif m ~= m2 then t.endtime = lang:formatDate( "F d, Y", b2 )	
			else t.endtime = lang:formatDate( "d, Y", b2 )	
			end	end	
			
	end -- if a2

	-- This function give a format to dates when P585 (date) is used in a single day race
	a1, b1, c1 = pcall(fooA, 'time', entity, 'P585', 1) 
	if a1 == true and t.time == "" then i = 1
		while a1 == true and c1 == 'deprecated' do 
			i = i + 1 
			a1, b1, c1 = pcall(fooA, 'time', entity, 'P585', i) 
		end  		
		t.time = func_date (b1,  'long') 
		timeofrace = b1
	end

	-- This function permits to display an unity (the kilometer) for a distance, with exceptions for macedionan, russian and japanese 
	-- that have other symbols 
	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P3157', 1) 
	if a1 == true and t.length == "" then i = 1
		while a1 == true and c1 == 'deprecated' do 
			i = i + 1 
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P3157', i) 
		end   
		t.length = b1
		a1, b1, _ = pcall(fooA, 'unit', entity, 'P3157', 1)
		if b1 == "http://www.wikidata.org/entity/Q828224" then
			t.length_unit = 'km'
			if  wiki == "ar" then t.length_unit = 'كم' end
		end
	end

	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2043', 1) 
	if a1 == true and t.length == "" then i = 1
		while a1 == true and c1 == 'deprecated' do 
			i = i + 1 
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2043', i) 
		end   
		t.length = b1
		a1, b1, _ = pcall(fooA, 'unit', entity, 'P2043', 1)
		if b1 == "http://www.wikidata.org/entity/Q828224" then
			t.length_unit = 'km'
			if  wiki == "ar" then t.length_unit = 'كم' end
		end
	end

	a, b = pcall(fooA, 'numeric-id', entity, 'P17', 1) -- This function gives countries where the race take place
	if a == true then --and ttt.country == "" then ttt.country = "Q" .. b end
		local i, v
		for i, v in pairs(entity.claims["P17"]) do
   			ttt.country[i] = "C" .. v.mainsnak.datavalue.value["numeric-id"]
   		end
 	end			
	-- Function that give the starting place of a race 
	a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1427', 1) 
	if a1 == true and t.startplace == "" then i = 1
		while a1 == true and c1 == 'deprecated' do 
			i = i + 1 
			a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1427', i) 
		end   
		t.startplace = "Q" .. b1 
	end	
	-- Function that give the finishing place of a race
	a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1444', 1) 
	if a1 == true and t.endplace == "" then i = 1
		while a1 == true and c1 == 'deprecated' do 
			i = i + 1 
			a1, b1, c1 = pcall(fooA, 'numeric-id', entity, 'P1444', i) 
		end   
		t.endplace = "Q" .. b1 
	end	
	-- This function counts the number of value for P1923 (participating teams) and give the number of team that participate at the race
    if pcall(function() 
         t.nr_teams = entity.claims["P1923"]
         end        	
      ) then else t.nr_teams = "" end   

	-- Function that give the number of cyclists at the beginning and at the finishing of a race
	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P1132', 1) 
	if a1 == true and t.nr_participants_start == "" and t.nr_participants_end == "" then i = 1
		while a1 == true and c1 == 'deprecated' do 
			i = i + 1 
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P1132', i) 
		end 
		local v
		for _, v in pairs(entity.claims["P1132"]) do
			if pcall(function()
		   		if v.qualifiers["P276"][1].datavalue.value["numeric-id"] == 529711 then
				t.nr_participants_start = string.gsub(v.mainsnak.datavalue.value.amount, "+", "") end
				end
			) then else t.nr_participants_start = "" end
			if pcall(function()
				if v.qualifiers["P276"][1].datavalue.value["numeric-id"] == 12769393 then
				t.nr_participants_end = string.gsub(v.mainsnak.datavalue.value.amount, "+", "") end
			end
			) then else t.nr_participants_end = "" end
		end	-- for 	
	end -- if a1

	-- This function permits to display an unity (the kilometer per hour) for an average speed, with exceptions for macedionan, russian and japanese 
	-- that have other symbols
	a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2052', 1) 
	if a1 == true and t.speed == "" then i = 1
		while a1 == true and c1 == 'deprecated' do 
			i = i + 1 
			a1, b1, c1 = pcall(fooA, 'amount', entity, 'P2052', i) 
		end 
		t.speed = b1
		a1, b1 = pcall(fooA, 'unit', entity, 'P2052', 1)
		if b1 == "http://www.wikidata.org/entity/Q180154" then
			t.speed_unit = 'km/h'
			if  wiki == "ar" then t.speed_unit = 'كم/س' end	
		end
	end	-- if a1
 	-- This function permits to display an unity for the cost of a cycling race
	a, b = pcall(fooA, 'amount', entity, 'P2130', 1)
	if a == true and t.cost == "" then 
		t.cost = b 
		a, b = pcall(fooA, 'unit', entity, 'P2130', 1)
		if b == "http://www.wikidata.org/entity/Q4916" then t.cost_unit = '€' end	
		if b == "http://www.wikidata.org/entity/Q4917" then t.cost_unit = '$' end	
	end

	a, b = pcall(fooA, 'value', entity, 'P242', 1) -- locator map image
	if a == true and tt.map == "" then tt.map = b end
	a, b = pcall(fooA, 'numeric-id', entity, 'P155', 1) 
	if a == true and t.previous == "" then t.previous = "Q"..b end	
	a, b = pcall(fooA, 'numeric-id', entity, 'P156', 1) 
	if a == true and t.next == "" then t.next = "Q"..b end
	
	local note, qual, id, id_team
	-- By entering a value just below, the Wikipedia added will have Wikidata logos associated with cyclists in the infobox	
	if wiki == "www" or wiki == "mk" or wiki == "ja" or wiki == "ru" then note = 'q' 
	elseif wiki == "www" then note = 'م' 
	else note = 'f' end 
	note = 'f'
	-- By entering a value just below, the Wikipedia added will show the team of the winner
	if pcall(foo3, entity, "P1346", 1, "P642", 1) then
		local k, v, vv
		for k, v in pairs(entity.claims["P1346"]) do
			id_team = '' 
			--id_team = 't26973671'
			a, b = pcall(fooC, 'numeric-id', entity, 'P1346', k, 'P54', 1)
			if a == true then id_team = 't'..b end
		
			if pcall(function() id=v.mainsnak.datavalue.value['numeric-id'] end) then else id=nil end -- id = rider id
			if id ~= nil then
				--timeofrace = "+2016-03-00T00:00:00Z" 
				-- function timeStartEnd finds the team of the rider at the time (timeofrace) of the race
				if id_team == '' and timeofrace ~= nil and timeofrace ~= '' then 
					a, b = timeStartEnd('Q'..id, 'P54', 'numeric-id', timeofrace) 
					if a == true and b ~= nil then id_team = 't' .. b end
				end
			end
--			pcall(function() id=v.mainsnak.datavalue.value['numeric-id'] end) -- rider ID
			
			-- looks into race item if the winner has a P54 statement for beeng a member of a national team 
			pcall(function() 			
				for _, vv in pairs(entity.claims["P1346"][k].qualifiers['P54']) do 
					id_team = '2t'.. ' ('.. national_team(  'Q'..id, timeofrace, entity, 'P1346', k).. ')' 
				end
			end)

			-- looks into race item if the winner has a P642 statement for showing the type of winner (points, mountain, ..)
			pcall(function() 			
				for _, vv in pairs(entity.claims["P1346"][k].qualifiers['P642']) do 
					qual=vv.datavalue.value['numeric-id']

		if id~=nil and qual~=nil and v.rank~='deprecated' then 
			if qual == 20882667 and t.first=="" then t.first=note..id t.first_team=id_team ref.first=references(entity,"P1346",k) results=true end
			if qual == 20882668 and t.second=="" then t.second=note..id t.second_team=id_team ref.second=references(entity,"P1346",k) results=true end
			if qual == 20882669 and t.third=="" then t.third=note..id t.third_team=id_team ref.third=references(entity,"P1346",k) results=true end
			if qual == 20883007 and t.winner_point=="" then t.winner_point=note..id t.winner_point_team=id_team ref.winner_point=references(entity,"P1346",k) results=true end
			if qual == 20883212 and t.winner_mountain=="" then t.winner_mountain=note..id t.winner_mountain_team=id_team ref.winner_mountain=references(entity,"P1346",k) results=true end   			
  			if qual == 20883328 and t.winner_sprint=="" then t.winner_sprint=note..id t.winner_sprint_team=id_team ref.winner_sprint=references(entity,"P1346",k) results=true end
			if qual == 20883139 and t.winner_young=="" then t.winner_young=note..id t.winner_young_team=id_team ref.winner_young=references(entity,"P1346",k) results=true end  
			if qual == 20893983 and t.winner_fighting=="" then t.winner_fighting=note..id t.winner_fighting_team=id_team ref.winner_fighting=references(entity,"P1346",k) results=true end
			if qual == 27067359 and t.winner_metas_volantes=="" then t.winner_metas_volantes=note..id t.winner_metas_volantes_team=id_team ref.winner_metas_volantes=references(entity,"P1346",k) results=true end
			if qual == 27067170 and t.winner_regularity=="" then t.winner_regularity=note..id t.winner_regularity_team=id_team ref.winner_regularity=references(entity,"P1346",k) results=true end
			if qual == 20893979 and t.winner_combination=="" then t.winner_combination=note..id t.winner_combination_team=id_team ref.winner_combination=references(entity,"P1346",k) results=true end
			if qual == 27907715 and t.winner_fuga_pinarello=="" then t.winner_fuga_pinarello=note..id t.winner_fuga_pinarello_team=id_team ref.winner_fuga_pinarello=references(entity,"P1346",k) results=true end
			if qual == 27907747 and t.winner_azzurri_ditalia=="" then t.winner_azzurri_ditalia=note..id t.winner_azzurri_ditalia_team=id_team ref.winner_azzurri_ditalia=references(entity,"P1346",k) results=true end
			if qual == 20882921 and t.winner_team == "" then
				a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( 'Q'..id ), 'P31', 1)
				if a == true and (b == 20738667 or b == 23726798) then -- test if 'national cycling team U23' or 'national cycling team'
					t.winner_team = '2t' .." "..national_team(  'Q'..id, timeofrace, entity, 'P1346', k)
				else
					t.winner_team = note .. id ref.winner_team=references(entity,"P1346",k) results = true
				end
			end
			if qual == 27104269 and t.winner_team_points == "" then t.winner_team_points = note .. id ref.winner_team_points=references(entity,"P1346",k) results = true end
 		end
				end
			end) 
		end	-- for
	end  -- end if pcall

	-- code for references
	local list = {} -- list[1][1] = value from ref.first, list [1][2] = 'first'
	local k
	for k in pairs(ref) do 
		if ref[k]~='' then table.insert(list, {ref[k], k}) end 
	end
	local w, ww 	
	num = #list
	for w=num,1,-1 do
		for ww=1,w do
			if w ~= ww then 
				if list[w][1] == list[ww][1] then list[w][1] = frame:extensionTag{name='ref', args={name=entityId..ww}} break end	
			else list[w][1] = frame:extensionTag{name='ref', content=list[w][1], args={name=entityId..ww}} end 
		end
	end
	for i=1,num do 
		ref[ list[i][2] ] = list[i][1] --list[num+1-i][1] 
	end

	-- transform Q/q-number into flag / WPlink / WDlink
	local k
	local team = true
	local wd = " [[File:Wikidata-logo S.svg|24px|link=d:"	

	for k in pairs(ttt) do -- "^C" ttt.country, "^T" ttt.tour
		if ttt[k][1]~=nil and string.find(ttt[k][1], "^C") then for i=1,#ttt[k] do ttt[k][i] = string.gsub(ttt[k][i], "C", "Q") ttt[k][i] = flag(ttt[k][i], timeofrace).." ".. WPlink( ttt[k][i] ) end end
		if ttt[k][1]~=nil and string.find(ttt[k][1], "^T") then for i=1,#ttt[k] do ttt[k][i] = string.gsub(ttt[k][i], "T", "Q") ttt[k][i] = WPlink( ttt[k][i], 'race') end end
	end	
	for k in pairs(t) do 
		if type(t[k]) == string then
			if string.find(t[k], "^Q") then --t[k], k = startplace, endplace, ... find variables with an item as value
				if pcall(foo1, t[k]) then t[k] = WPlink( t[k] )	end
			end
			if string.find(t[k], "^q") then -- find variables with an item as value (in section Résultats)
				t[k] = mw.ustring.upper( t[k] )
				--look into P27 (country of citizenship) to get the Qnumber of that country
				a, b = timeStartEnd(t[k], "P27", 'numeric-id', timeofrace)
				if a == true and pcall(foo1, t[k]) then t[k] = flag('Q'..b, timeofrace).." "..WPlink( t[k] )..ref[k]..wd..t[k].."]]"
				else
					--look into P17 (country) to get the Qnumber of that country
					a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( t[k] ), 'P17', 1)
					if a == true and pcall(foo1, t[k]) then t[k] = flag("Q"..b, timeofrace).." "..WPlink( t[k] )..ref[k]..wd..t[k].."]]" end
				end
			end
			if string.find(t[k], "^f") then -- no WDitem, frWP
				t[k] = string.gsub(t[k], "f", "Q")
				--look into P27 (country of citizenship) to get the Qnumber of that country
				a, b = timeStartEnd(t[k], "P27", 'numeric-id', timeofrace)
				if a == true and pcall(foo1, t[k]) then t[k] = flag('Q'..b, timeofrace).." "..WPlink( t[k] )..ref[k]
				else	
					--look into P17 (country) to get the Qnumber of that country
					a, b = pcall(fooA, 'numeric-id', mw.wikibase.getEntity( t[k] ), 'P17', 1)
					if a == true and pcall(foo1, t[k]) then t[k] = flag("Q"..b, timeofrace).." "..WPlink( t[k], 'team', timeofrace )..ref[k] else t[k] = WPlink( t[k], 'team', timeofrace )..ref[k] end
				end
			end	
			if string.find(t[k], "^c") then -- find "class"-items, first asci = "c"
				t[k] = string.gsub(t[k], "c", "Q")
				if pcall(foo1, t[k]) then t[k] = WPlink( t[k], "Q22348500" ) end
			end
			if string.find(t[k], "^t") then 
				t[k] = string.gsub(t[k], "t", "Q")
				--timeofrace = "+2008-04-09T00:00:00Z"
				if pcall(foo1, t[k]) then t[k] = " (" .. WPlink( t[k], 'team', timeofrace ) .. ")" end
			end
			if string.find(t[k], "^2t") then t[k] = string.gsub(t[k], "2t", "") end		
		end
	end

    --local nl ="&#10;"
    -- local tooltip = infobox_bottom(2) .. nl .. mw.text.encode( property(1) .. ' (P393)' ) .. nl .. mw.text.encode( property(2) ..' (P17)')
    
    if t.length ~= "" then 
    	t.length, _ = string.gsub(t.length, "[+]", "") -- delets "+" sign from t.length 
    	t.length = lang:formatNum(tonumber(t.length)) -- formats t.length in the way it is done in the local Wiki
    	if wiki == 'fo' then t.length = string.gsub(t.length, "%.", ",") end
    end    
    if t.speed ~= "" then 
    	t.speed, _ = string.gsub(t.speed, "[+]", "")
    	t.speed = lang:formatNum(tonumber(t.speed))
    	if wiki == 'fo' then t.speed = string.gsub(t.speed, "%.", ",") end
    end
    if t.cost ~= "" then 
    	t.cost, _ = string.gsub(t.cost, "[+]", "")
    	t.cost = lang:formatNum(tonumber(t.cost))
    	if wiki == 'fo' then t.cost = string.gsub(t.cost, "%.", ",") end
    end
    
   	local span1, span2 = "<span style='color:#3366CC'>&#x25C0; </span>", "<span style='color:#3366CC'> &#x25B6;</span>"
    local k = t.previous
	local i, _ = string.find(k, "|")
	local j, _ = string.find(k, "]")
	if i ~= nil and j ~= nil then 
		t.previous = string.sub(k, 1, i) .. span1 .. (string.match(string.sub(k, i+1, j-1), "%d%d%d%d") or '') .. string.sub(k, j) 
	else 
		if string.find(k, "%d%d%d%d") == nil then t.previous = '' else t.previous = string.sub(k, string.find(k, "%d%d%d%d")) end
		if t.previous ~= "" then t.previous = span1 .. t.previous end 
	end

	k = t.next
	i, _ = string.find(k, "|")
	j, _ = string.find(k, "]")
	if i ~= nil and j ~= nil then 
		t.next = string.sub(k, 1, i) .. (string.match(string.sub(k, i+1, j-1), "%d%d%d%d") or '') .. span2 .. string.sub(k,j) 
	else 
		if string.find(k, "%d%d%d%d") == nil then t.next = "" else t.next = string.sub(k, string.find(k, "%d%d%d%d")) end
		if t.next ~= "" then t.next = t.next .. span2 end 
	end

	tt.caption = string.gsub(tt.caption, "{{(%w+)}}", function (n) return frame:expandTemplate{ title = n }  end)
	-- for overwriting Wikidata content with data in Wikipedia articles. numbers are from function infobox_translate
	local z = {stage=5, date=6, dates=7, length=8, startplace=11, endplace=12, nr_teams=13, nr_participants_start=14, nr_participants_end=15, 
	speed=16, cost=17, first=19, second=20, third=21, winner_point=22, winner_mountain=23, winner_sprint=24, winner_young=25, winner_fighting=26, 
	winner_combination=27, winner_team=28, winner_team_points=37, winner_metas_volantes=35, winner_regularity=36, winner_fuga_pinarello=38,
	winner_azzurri_ditalia=39}

 	tab = "{| class='wikitable' cellpadding='4' cellspacing='0'; style='border:1px solid rgb(200,200,200);" --float:rgiht; 
    tab = tab .. "margin:0 0 0.5em 0.5em; background-color:rgb(255, 255, 255); color:black; padding:5px; ; "--clear:left
    tab = tab .. "text-align:right; font-size:95%; line-height:1.6em;'\n"
	--if results then tab = tab.."|- \n| colspan='2' style='border-bottom:5px solid white; background-color:#FFDF80; text-align:center' | '''"..infobox_translate(18).."'''\n" end
	if results then tab = tab.."|+ '''"..infobox_translate(18).."'''\n" end
	tab = tab.."|- \n! '''الترتيب'''!! الفائز \n"
	-- defines a factorial function
    if t.first ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(19) .. "'''||" .. t.first .. "\n"
    end
    if t.second ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(20) .. "'''||" .. t.second .. "\n"
    end
    if t.third ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(21) .. "'''||" .. t.third .. "\n"
    end
    if t.winner_point ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(22) .. "'''||" .. t.winner_point .. "\n"
    end
    if t.winner_mountain ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(23) .. "'''||" .. t.winner_mountain .. "\n"
    end
    if t.winner_sprint ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(24) .. "'''||" .. t.winner_sprint .. "\n"
    end
    if t.winner_young ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(25) .. "'''||" .. t.winner_young .. "\n"
    end
    if t.winner_fighting ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(26) .. "'''||" .. t.winner_fighting .. "\n"
    end
    if t.winner_metas_volantes ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(35) .. "'''||" .. t.winner_metas_volantes .. "\n"
    end
    if t.winner_regularity ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(36) .. "'''||" .. t.winner_regularity .. "\n"
    end
    if t.winner_fuga_pinarello ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(38) .. "'''||" .. t.winner_fuga_pinarello .. "\n"
    end
    if t.winner_azzurri_ditalia ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(39) .. "'''||" .. t.winner_azzurri_ditalia .. "\n"
    end
    if t.winner_combination ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(27) .. "'''||" .. t.winner_combination .. "\n"
    end
    if t.winner_team ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(28) .. "'''||" .. t.winner_team .. "\n"
    end
    if t.winner_team_points ~= "" then
        tab = tab .. "|- \n| '''" .. infobox_translate(37) .. "'''||" .. t.winner_team_points .. "\n"
    end

	--tab = tab.."<tr><td style='text-align:right'>"..t.previous.."</td><td style='text-align:left'>" .. t.next .. "\n"
	--tab = tab.."|- \n| "..t.previous.."</td><td style='text-align:right'>" .. t.next .. "\n"
	local s = "d:Wikidata:WikiProject Cycling/Documentation/infobox"
	--tab = tab .. "|- \n| colspan='2' style='text-align:left; border-top:0px solid #FFDF80; font-size:75%' | " .. "[[" .. s .. "|" .. infobox_translate(34) .. "]] [[File:Wikidata-logo S.svg|24px|link=d:".. frame.args[1]  .. "]]" --infobox_bottom(1) 
	tab= tab.."\n|}"
	return tab
end

return p