Kassbinette / Gaslands Roster

// ==UserScript==
// @name         Gaslands Roster
// @namespace    http://kassbinette.No-Domain-Name.net/
// @version      1.0.1
// @description  Enhance html gaslands roosters produced by battlescript. The script will execute on  local HTML files identified as battlescript rosters.  (on basis of the 'body.battlescribe' css class). to allow this script to execute enable files url in chrome extension manager : https://stackoverflow.com/questions/9931115/run-greasemonkey-on-html-files-located-on-the-local-filesystem
// @license      MIT
// @author       Kassbinette
// @match        file://*/*.html
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js
// @connect      self
// @grant        GM_setValue
// @grant        GM_getValue
// @ressource    roundSquare https://drive.google.com/uc?1XL-Qd7UFol98Rr594i0s0o3po-bHiZnz
// @ressource    gaslandsPng https://drive.google.com/uc?1mmzTi8odZeXjKhj0ePP70-1eFN6ibutI
// @copyright    2020, Kassbinette (https://openuserjs.org/users/Kassbinette)
// @downloadURL  https://openuserjs.org/install/Kassbinette/Gaslands_Roster.user.js
// @updateURL    https://openuserjs.org/meta/Kassbinette/Gaslands_Roster.meta.js

// ==/UserScript==

(function() {
    'use strict';
    $(document).ready(function(){
        relookRoster();
    });
    // Your code here...
})();

var IMG_PATH ="https://drive.google.com/uc?";
var gaslandsPng_ID = "1mmzTi8odZeXjKhj0ePP70-1eFN6ibutI";
var roundSquarePng_ID = "1XL-Qd7UFol98Rr594i0s0o3po-bHiZnz";
var vehiculeDices =  ["Vitesse","Danger","Equipage", "Activation"];
var teamDices = ["Votes du public"];
var vehiculesSelector = ".category-names span:contains('Vehicule')";

function getImgFullPath(imgID) {
	// return IMG_PATH + imgName;
    return "https://drive.google.com/uc?id=" + imgID
}

function relookRoster(){
    if($(document).text().includes('body.battlescribe'))
    {
        addStyle();
        addAmmunitionBoxes();
        addHullBoxes("Carrosserie");
        addVehiculesDicesBoxes(vehiculesSelector);
        addPageBreaks(vehiculesSelector);
        addTeamDicesBoxes("h1");
        /// Change look
        addHeaderPicture();
        addNameInputBoxes();
        centerNumericTds();
        $("p:contains('Created with')").hide()
    }
}

function addStyle(){
// $("style").last().after("<link rel='stylesheet' href='http://kassbinette.great-site.net/style.css' type='text/css' >");
        $("style").last().after("<style>"+css+"</style>");
}

function addAmmunitionBoxes(){
    var keyword='Arme'
	$('th:contains('+ keyword +')').parent().parent().parent().children().find('tr').each(function(){
     var tdText = $(this).find(':nth-child(5)').text()
     var i = 0 ;
     if(tdText != 'Munitions'){
		var nbMunitions = parseInt(tdText);
		var strOutput ="";
		for( i=0; i <nbMunitions;i++)
		{
            var str = "";
			if(i%3 ==0 && i>0){
				str ="<br/>"
            }
			else{
				str =""
            }
			strOutput = strOutput + str + '<input name="bulletBox" type="checkbox" />';
		};
		$(this).find(':nth-child(5)').html( strOutput );
     }
	});

}

function addHullBoxes(keyword){
	$('th:contains('+ keyword +')').each(function(){
        var i = 0;
		var tdHull = $(this).closest("table").find('td:eq(2)')
		var nbHull = parseInt(tdHull.text());
		var strOutput ="";
		for( i=0; i <nbHull;i++)
		{
			var str = ""
			if(i%5 ==0 && i>0){
				str ="<br/>"
            }
			else{
				str =""
            }
			strOutput = strOutput + str + '<input name="hullBox" type="checkbox" />';
		};
		$(tdHull).html(
		   $(tdHull).text().replace(tdHull.text(),strOutput)
		)
	});
}

function addVehiculesDicesBoxes(selector){
	$(selector).each(function(){
		var strOutput = "<table style='border:0px solid black'>"
		strOutput = strOutput + addDiceHeaders(vehiculeDices)
		strOutput = strOutput + addDiceShadows(vehiculeDices)
		strOutput = strOutput + "</table>"
		$(this).parent().parent().children("h4").after(strOutput)
	});

}

function addTeamDicesBoxes(selector){
	$(selector).each(function(){
		var strOutput = "<table style='border:0px solid black'>"
		strOutput = strOutput + addDiceHeaders(teamDices)
		strOutput = strOutput + addDiceShadows(teamDices)
		strOutput = strOutput + "</table>"
		$(this).after(strOutput)
	});
}

function addDiceHeaders(arr){
	var strOutput ="<tr>"
    var j =0;
	for (j = 0; j<arr.length; j++ ){
		strOutput = strOutput + "<th>" +arr[j] +" </th>"
	}
	strOutput = strOutput +"</tr>"
	return strOutput
}

function addDiceShadows(arr){
    var j =0;
	var strOutput ="<tr>"
	var imgStr = "<img class='DiceShadow' src='"+getImgFullPath(roundSquarePng_ID)+"'/>"
	var tdStr = "<td>"+imgStr+"</td>"
	for (j = 0; j<arr.length; j++ ){
		strOutput = strOutput + tdStr
	}
	strOutput = strOutput +"</tr>"
	return strOutput
}

function addPageBreaks(selector){
	$(selector).each(function(){
		$(this).parent().parent().addClass("pagebreak")
	});
}

function addHeaderPicture(){
	$("h1").before("<img class='center' src='" + getImgFullPath(gaslandsPng_ID)+"'>")
}



function addNameInputBoxes(){
    var selector = ".rootselection.pagebreak > h4"
    var vehiculeIndex = 0;
    $(selector).each(function(){
        var headerText = $(this).text();
        var nameSeparator = " - " ;
        var nameStopChar = headerText.indexOf(nameSeparator);
        if (nameStopChar>0)
        {
           var vehiculeName = headerText.substring(0, nameStopChar)
           $(this).text( $(this).text().substring(nameStopChar + nameSeparator.length))
           saveAVehiculeName(vehiculeIndex, vehiculeName);
        }
		$(this).append(" : <input class='names' name='vehiculeName'></input>")
         vehiculeIndex++;
	});
    addWaterMark();
    loadNames();
}

function addWaterMark(){
     var selector = 'input[name="vehiculeName"]';
    var watermark = "Nom du véhicule"

    $(selector).val(watermark).addClass('watermark');

	//if blur and no value inside, set watermark text and class again.
 	$(selector).blur(function(){
  		if ($(this).val().length == 0){
    		$(this).val(watermark).addClass('watermark');
		}
 	});

	//if focus and text is watermark, set it to empty and remove the watermark class
	$(selector).focus(function(){
  		if ($(this).val() == watermark){
    		$(this).val('').removeClass('watermark');
		}
 	});

    $(selector).change(function(){
        storeNames();
    });
}

function storeNames(){
    var selector = 'input[name="vehiculeName"]';
    var i = 0;
    $(selector).each(function(){
        saveAName(i,$(this).val());
        i++
    });
}

function saveAVehiculeName(index, name){
    var teamName = $("h1").text();
    GM_setValue(teamName + "vehiculeName"+index,name);
}

function loadNames(){
    var teamName = $("h1").text()
    var selector = 'input[name="vehiculeName"]';
    var i = 0;
    $(selector).each(function(){
        if(GM_getValue(teamName+"vehiculeName"+i) != '')
        {
            $(this).val('').removeClass('watermark');
            $(this).val(GM_getValue(teamName+"vehiculeName"+i));
            $(this).blur()
        }
        i++
    });
}

function centerNumericTds(){
    var index = 0;
    $('th:contains("Vehicule")').parent().parent().parent().children().find('tr').each(function(){
        if (index>0){
            $(this).find("td:nth-child(4)").css("text-align","center");
            $(this).find("td:nth-child(5)").css("text-align","center");
            $(this).find("td:nth-child(6)").css("text-align","center");
        }
        index++;
    });
}

var css =
    '@media print { ' +
'    .pagebreak { ' +
'        clear: both; ' +
'        page-break-after: always; ' +
'    }		' +
'} ' +
'.DiceShadow{ ' +
'	height:60px; ' +
'	display: block; ' +
'	margin-left: auto; ' +
'	margin-right: auto; ' +
'	padding-left:5px; ' +
'	padding-right:5px ' +
'} ' +
'th,td{ ' +
'	font-size: smaller; ' +
'} ' +
 '' +
'.center {  ' +
'  display: block;  ' +
'  margin-left: auto; ' +
'  margin-right: auto; ' +
'  width: 50%; ' +
'} ' +
'h1, h2, h3, h4, th, .bold{' +
'	font-family:"28 Days Later"; ' +
'    font-weight: bold; ' +
'} ' +
'div.battlescribe h1{ ' +
'	font-size: large; ' +
'} ' +
'   input.watermark { color: #999; font-family:"Arial";} ' +
'	input.names { ' +
'		padding:4px; ' +
'		text-indent: 5px; ' +
'		width:200px; ' +
'		font-size:22px; ' +
'        font-family:"28 Days Later"; ' +
'        border-top:0px; ' +
'        border-left:0px; ' +
'        border-right:0px; ' +
'	}' ;