 // --------------- Cookies ---------------------------
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
//    document.cookie = cname + "=" + encodeURI(cvalue) + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
        if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}
// --------------- End Cookies ---------------------------

// Toggle all checkboxes
function getElement(elementId)
{
    return document.getElementById(elementId);
}

//function toggleSelectFor(htmlcontent,checkboxsource, nameprefix, orgColor) {  (Before Bootstrap)
function toggleSelectFor(htmlcontent,checkboxsource, nameprefix) {
    var content = getElement(htmlcontent);
//    var state = getElement(checkboxsource);  Impossible to see if checked or not with Boostrap
// $(toggle_chk).length is 2 for data-table and 1 for a regular table. No idea why...
//    var state = $(toggle_chk)[$(toggle_chk).length-1].checked;
//    var checkboxsourceelement = document.getElementById(checkboxsource);
//    var state = (checkboxsourceelement.value == "on");
//    var state = document.getElementById(checkboxsource).checked;
//    var state = $( checkboxsourceelement ).prop( "checked" );

    //Exempel: $("input[id='theCheckboxId']").is(":checked");

    var tempstring = "input[id='" + checkboxsource + "']";
    var state = $(tempstring).is(":checked");

    // now:  find other items like the stated one (IN id=content)
    var inputs = content.getElementsByTagName('INPUT');
    for (var i=0; i<inputs.length; i++) {
        var element = inputs[i];
        var n = element.name;
        if (element.type == 'checkbox') {
            if ((n.length >= nameprefix.length) && (nameprefix == n.substring(0,nameprefix.length))) {
                parentElement = element.parentNode.parentNode;

                if (parentElement.nodeName == "TR")
                {
                  if (state && parentElement.className != 'selectedTableRow'){
                      $(parentElement).toggleClass('selectedTableRow');
  			    }
                  if (!state && parentElement.className == 'selectedTableRow'){
                      $(parentElement).toggleClass('selectedTableRow');
    			    }
   			    }
                element.checked = state;
            }
        }
    }
}

function confirmation(displaystring) {
    var answer = confirm(displaystring)
    if (answer){
        return true;
    }
    else{
	return false;
    }
}

function notEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus(); // set the focus to this input
		return false;
	}
	return true;
}

function isNumeric(elem, helperMsg){
	var numericExpression = /^[0-9]+$/;
	if(elem.value.match(numericExpression)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

function isAlphabet(elem, helperMsg){
	var alphaExp = /^[a-zA-Z]+$/;
	elem.value = elem.value.trim();
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

function isAlphanumeric(elem, helperMsg){
	var alphaExp = /^[0-9a-zA-Z]+$/;
// ger fel i IE8	elem.value = elem.value.trim();
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

function lengthRestriction(elem, min, max){
	var uInput = elem.value;
	if(uInput.length >= min && uInput.length <= max){
		return true;
	}else{
		alert("Please enter between " +min+ " and " +max+ " characters");
		elem.focus();
		return false;
	}
}

function madeSelection(elem, helperMsg){
	if(elem.value == "Please Choose"){
		alert(helperMsg);
		elem.focus();
		return false;
	}else{
		return true;
	}
}

function emailValidator(elem, helperMsg){
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	if(elem.value.match(emailExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

// Show/hide id
function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }

// Show/hide id in parent from an iframe
function toggle_parent_visibility(id) {
       var e = parent.document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }

function resizeIframe(obj){
//   obj.style.height = 1200;
//   obj.style.width = 1400;
//   obj.style.height = obj.contentWindow.document.body.scrollHeight + 20 + 'px';
//   obj.style.width = obj.contentWindow.document.body.scrollWidth + 20 + 'px';

//  obj = Object(objName);

//  if (optional === undefined) {
//    optional = "default value";
//  }

   obj.style.height = 1200;
   obj.style.width = 1400;
   obj.style.height = obj.contentWindow.document.body.scrollHeight + 20 + 'px';
   obj.style.width = obj.contentWindow.document.body.scrollWidth + 20 + 'px';

//   self.frameElement.style.height = 1200;
//   self.frameElement.style.width = 1400;
//   self.frameElement.style.height = self.frameElement.contentWindow.document.body.scrollHeight + 20 + 'px';
//   self.frameElement.style.width = self.frameElement.contentWindow.document.body.scrollWidth + 20 + 'px';
    }


// Toggle table row color
/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: Gil Davis | ayse incebulut | http://www.webdeveloper.com/forum/showthread.php?p=717824#post717824 */
//function toggleRowColor(element,orgColor) {
//  markColor=orgColor.substring(1,5)+"C0";
//  tr = element.parentNode.parentNode;
//  tr.style.backgroundColor = (element.checked) ? markColor : orgColor;
//}

// New function needed for striped Bootstrap-table
function toggleRowColor(element){
  tr = element.parentNode.parentNode;
  $(tr).toggleClass('selectedTableRow');
}


// File extension filter
function LimitAttach(form, file, messagetext, type) {
  if (type=="doc")
  {
    extArray = new Array(".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx");
  }
  else
  {
    extArray = new Array(".gif", ".jpg", ".png", ".bmp");
  }
  allowSubmit = false;
  if (!file){
    return false;
  }

  while (file.indexOf("\\") != -1)
    file = file.slice(file.indexOf("\\") + 1);
    ext = file.slice(file.indexOf(".")).toLowerCase();
    for (var i = 0; i < extArray.length; i++) {
      if (extArray[i] == ext) { allowSubmit = true; break; }
    }

  if (allowSubmit) {
    return true;
  }
  else {
    alert(messagetext + (extArray.join("  ")));
      return false;
  }
}

// Show/Hide table column
function show_hide_column(id_of_table, col_no, do_show) {
  var stl;
  if (do_show) stl = 'table-cell'
  else         stl = 'none';
   var tbl  = document.getElementById(id_of_table);
  var rows = tbl.getElementsByTagName('tr');
   for (var row=0; row<rows.length;row++) {
	if (row == 0){
      var cels = rows[row].getElementsByTagName('th');
    }
    else {
      var cels = rows[row].getElementsByTagName('td');
    }
    cels[col_no].style.display=stl;
  }
}

// Limit the number of characters per textarea
function textCounter(field,cntfield,maxlimit) {
  if (field.value.length > maxlimit) // if too long...trim it!
    field.value = field.value.substring(0, maxlimit);
  // otherwise, update 'characters left' counter
  else
    cntfield.value = maxlimit - field.value.length;
}

// Plus/Minus buttons
function PlusMinusButtons(plusButton,minusButton,resultValue) {
    let plus = document.getElementById(plusButton),
    minus = document.getElementById(minusButton),
    result = document.getElementById(resultValue);
    plus.addEventListener("click", ()=>{
      let a = parseInt(result.value);
      a++;
      result.value = a.toString();
    });

    minus.addEventListener("click", ()=>{
      let a = parseInt(result.value);
      if(a > 0){
        a--;
        result.value =a.toString();
      }
    });
}

// Match protocol lineup buttons
function lineupButtons() {
  let btns = document.querySelectorAll('[id*="mal_inc_butt_"]');
  btns.forEach(btn => {
    btn.addEventListener('click', (event)=> {
	var h_b = btn.id.substring(0,1);
    var no = btn.id.split('_').pop();
	var el = document.getElementsByName(h_b + "_mal_" + no);
	var a = parseInt(el[0].value);
    a++;
    el[0].value = a.toString();
    });
  });

  btns = document.querySelectorAll('[id*="ass_inc_butt_"]');
  btns.forEach(btn => {
    btn.addEventListener('click', (event)=> {
	var h_b = btn.id.substring(0,1);
    var no = btn.id.split('_').pop();
	var el = document.getElementsByName(h_b + "_ass_" + no);
	var a = parseInt(el[0].value);
    a++;
    el[0].value = a.toString();
    });
  });

  btns = document.querySelectorAll('[id*="utv2_inc_butt_"]');
  btns.forEach(btn => {
    btn.addEventListener('click', (event)=> {
	var h_b = btn.id.substring(0,1);
    var no = btn.id.split('_').pop();
	var el = document.getElementsByName(h_b + "_utv_" + no);
	var a = parseInt(el[0].value);
    a = a  + 2;
    el[0].value = a.toString();
    });
  });

  btns = document.querySelectorAll('[id*="utv5_inc_butt_"]');
  btns.forEach(btn => {
    btn.addEventListener('click', (event)=> {
	var h_b = btn.id.substring(0,1);
    var no = btn.id.split('_').pop();
	var el = document.getElementsByName(h_b + "_utv_" + no);
	var a = parseInt(el[0].value);
    a = a  + 5;
    el[0].value = a.toString();
    });
  });
}

// Game watch
class gameWatch {
  constructor(id, resetTime, delay=100) { //Delay in ms
    this.state = "paused";
	this.since = Date.now();
	this.resetTime = resetTime;
    this.delay = delay;
    this.display = document.getElementsByName(id);
    this.saveBtn = document.getElementsByName("submit");
	this.timeDisplay = this.display[0].value;
	if (this.timeDisplay == "00:00" || this.timeDisplay == ""){
		this.setTime(this.resetTime);
	}else{
		this.setTime(this.timeDisplay);
	}
}
  
  setTime(time) {
    var minutes = parseInt(time.substring(0,2));
    var seconds = parseInt(time.substring(3,5));
	if (isNaN(minutes) || isNaN(seconds)){
		this.value = 0;
	}else{
		this.value = ((minutes * 60) + seconds) * 1000;
	}
    this.update();
  }

  formatTime(ms) {
    var hours   = Math.floor(ms / 3600000);
    var minutes = Math.floor((ms - (hours * 3600000)) / 60000);
    var seconds = Math.floor((ms - (hours * 3600000) - (minutes * 60000)) / 1000);
    var ds = Math.floor((ms - (hours * 3600000) - (minutes * 60000) - (seconds * 1000))/100);
    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return minutes+':'+seconds;
  }
  
  update() {
    if (this.state=="running") {
	  this.value = (this.since - Date.now()); // 1000;
    }
	  if (this.value <= 0){
	    this.stop();
	    this.display[0].style.backgroundColor = 'red';
      }else{
         this.display[0].value = this.formatTime(this.value);
	  }
  }
  
  start() {
    if (this.state=="paused") {
      this.display[0].style.backgroundColor = 'aqua';
      this.saveBtn[0].disabled = true;
      this.state="running";
	  this.since = Date.now() + this.value;
      if (!this.interval) {
        var t=this;
        this.interval = setInterval(function(){t.update();}, this.delay);
      }
    }
  }
  
  stop() {
    this.display[0].style.backgroundColor = '';
    if (this.state=="running") {
      this.saveBtn[0].disabled = false;
      this.state="paused";
      if (this.interval) {
        clearInterval(this.interval);
        this.interval = null;
      }
    }
  }
  
  reset() {
    this.stop();
    this.setTime(this.resetTime);
  }
}
