/* window.onload = CookieTest(); */
/* Set a cookie to be sure that one exists. */
document.cookie = 'killme' + escape('nothing')

var missingInputBgColor = '#FFD700';
var optionSelectedBgColor = '#FFD700';
function CookieTest()
{
 /* check for a cookie */
  if (document.cookie == '')
  {
    /* if a cookie is not found - alert user -
     change cookieexists field value to false */
    //alert("You need to enable Cookies to use the online score sheet system!");

    /* If the user has Cookies disabled an alert will let him know
        that cookies need to be enabled to log on.*/
    document.getElementById('strCookieTest').value = 'false';
  } else {
   /* this sets the value to true and nothing else will happen,
       the user will be able to log on*/
    document.getElementById('strCookieTest').value = 'true';
  }
}

function CheckScore(PlayerID,fld)
{
  if (PlayerID == '0')
  {
    $('#' + fld).val(0);
    $('#' + fld).attr('disabled','disabled');
    $('#' + fld).css('background-color',null);
  } else {
    $('#' + fld).val('');
    $('#' + fld).removeAttr('disabled');
    $('#' + fld).css('background-color',missingInputBgColor);
  }
}

function GetOtherPlayer(fld)
{
  var strPlayer = prompt('Please enter the players full name:');
  if(strPlayer != '' && strPlayer != null)
  {
    document.getElementById('strNotes').value += '\n' + fld.getAttribute('manditory') + ': ' + strPlayer + '\n';
  } else {
    fld.selectedIndex = 0;
  }
}

function RefreshImage(valImageId)
{
	var objImage = document.images[valImageId];
	if (objImage == undefined)
  {
		return;
	}
	var now = new Date();
	objImage.src = objImage.src.split('?')[0] + '?x=' + now.toUTCString();
}

function numbersonly(myfield, e, dec)
{
  var key;
  var keychar;

  if (window.event)
  {
     key = window.event.keyCode;
  } else if(e) {
     key = e.which;
  } else {
     return true;
  }
  keychar = String.fromCharCode(key);

  // control keys
  if ((key==null) || (key==0) || (key==8) ||(key==9) || (key==13) || (key==27))
  {
    return true;
  }  else if ((("0123456789").indexOf(keychar) > -1)) {
     return true;
  } else {
    return false;
  }
}

function GamesWon(pts)
{
  var games = '';
  switch (pts)
  {
    case '0':
      games = 0;
      break;
    case '1':
      games = 24;
      break;
    case '2':
      games = 25;
      break;
  }
  document.getElementById('GW').value = games;
}

function CheckForm(frm)
{
  var passed = true;
  var msg = 'You must fill in the following field(s) to continue:\n';
  var binAttendance = false;
  var intAttendance = 0;
  for (var i=0; i<frm.elements.length; i++)
  {
    if(frm.elements[i].getAttribute('manditory') != null)
    {
      if(frm.elements[i].name == 'attendance')
      {
        $(frm.elements[i]).parent().css('background-color',null);
        $(frm.elements[i]).parent().next().css('background-color',null);
      }
      $(frm.elements[i]).css('background-color',null);
      if(frm.elements[i].value.length == 0 || frm.elements[i].value == null)
      {
        msg += '\n-- ' + frm.elements[i].getAttribute('manditory');
        $(frm.elements[i]).css('background-color',missingInputBgColor);
        passed = false;
      } else {
        if(frm.elements[i].getAttribute('subtype') != null)
        {
          switch (frm.elements[i].getAttribute('subtype'))
          {
            case 'email':
              if(!isValidEmail(frm.elements[i].value))
              {
                msg += '\n-- ' + frm.elements[i].getAttribute('manditory') + ' is not a valid email address';
                passed = false;
              }
              break;
            case 'phone':
              if(frm.elements[i].value.search(/\d{3}\-\d{3}\-\d{4}/) == -1)
              {
                msg += '\n-- ' + frm.elements[i].getAttribute('manditory') + ' is not a valid phone number (xxx-xxx-xxxx)';
                passed = false;
              }
              break;
            case 'score':
              if(parseInt(frm.elements[i].value) > 180 )
              {
                msg += '\n-- ' + frm.elements[i].getAttribute('manditory') + ' is not a valid score';
                frm.elements[i].style.backgroundColor = missingInputBgColor;
                passed = false;
              }
              break;
            case 'attendance':
              if(frm.elements[i].checked) intAttendance++;
              break;
          }
        }
      }
    }
  }
  if($('input[name=attendance]').length)
  {
    if(intAttendance > 4) binAttendance = true;
    if(!binAttendance)
    {
      msg += '\n-- Player Attendance' +
             '\n--> You have selected ' + intAttendance + ' player(s)';

      $(":checkbox").each(function() {
        if(!this.checked)
        {
          $(this).parent().css('background-color',missingInputBgColor);
          $(this).parent().next().css('background-color',missingInputBgColor);
        }
      });
      passed = false;
    }
  }
  if(!passed)
  {
    alert(msg);
  } else {
    for (var i=0; i<frm.elements.length; i++)
    {
      if(frm.elements[i].disabled) frm.elements[i].disabled = false;
    }
  }
  return passed;
}

//function to check valid email address
function isValidEmail(strEmail)
{
  validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
  //validRegExp = \b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b;
  //validRegExp = ^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})$;
  //strEmail = document.forms[0].email.value;
  // search email text for regular exp matches
  if (strEmail.search(validRegExp) == -1)
  {
    //alert('A valid e-mail address is required.\nPlease amend and retry');
    return false;
  }
  return true;
}

function CheckForm2(frm)
{
  var passed = true;
  var msg = 'You must fill in the following field(s) to continue:\n';
  if (frm.Name.value == '')
  {
    msg += '\n-- Contact name';
    passed = false;
  }
  if (frm.Email.value == '')
  {
    msg += '\n-- Contact email';
    passed = false;
  } else {
    if(!isValidEmail(frm.Email.value))
    {
      msg += '\n-- You must enter a valid email address';
      passed = false;
    }
  }
  if (frm.Phone.value == '')
  {
    msg += '\n-- Contact phone';
    passed = false;
  } else {
    if(frm.Phone.value.search(/\d{3}\-\d{3}\-\d{4}/) == -1)
    {
      msg += '\n-- You must enter a valid contact phone number (xxx-xxx-xxxx)';
      passed = false;
    }
  }
  if (frm.JitneyDate.value == '')
  {
    msg += '\n-- Jitney date';
    passed = false;
  }
  if (frm.JitneyName.value == '')
  {
    msg += '\n-- Jitney name';
    passed = false;
  }
  if (frm.Community.value == '')
  {
    msg += '\n-- Comunity';
    passed = false;
  }
  if (frm.JitneyInfo.value == '')
  {
    msg += '\n-- Jitney info';
    passed = false;
  }
  if(!passed) alert(msg);
  return passed;
}

function CheckWonLostTied(score,fld)
{
  switch(score)
  {
    case '0':
      //alert('lost');
      ResetPlayers();
      SelectOptionByValue('#intGamesWon','0');
      $('#intGamesWon').css('background-color', missingInputBgColor);
      break;
    case '0.1':
      //alert('lost by default');
      SelectOptionByValue('#intGamesWon','0');
      $('#intGamesWon').css('background-color',null);
      $('#intGamesWon').attr('disabled','disabled');
      SetPlayersNA();
      $('#binDefault').val('true');
      break;
    case '1':
      //alert('tied');
      SelectOptionByValue('#intGamesWon','24');
      $('#intGamesWon').css('background-color', null);
      ResetPlayers();
      $('#intGamesWon').attr('disabled','disabled');
      break;
    case '2':
      //alert('won');
      ResetPlayers();
      SelectOptionByValue('#intGamesWon','25');
      $('#intGamesWon').css('background-color', missingInputBgColor);
      break;
    case '2.1':
      //alert('won by default');
      SelectOptionByValue('#intGamesWon','25');
      $('#intGamesWon').css('background-color',null);
      $('#intGamesWon').attr('disabled','disabled');
      SetPlayersNA();
      $('#binDefault').val('true');
      break;
    default:
      ResetPlayers();
      SelectOptionByValue('#intGamesWon','');
      $('#intGamesWon').css('background-color', missingInputBgColor);
      break;
  }
  $(fld).css('background-color', score == '' ? missingInputBgColor : null);
  $('#intGamesWon > option').each(function(){
    switch(parseInt(score))
    {
      case 0:
        if(parseInt($(this).val()) < 24)
        {
          $(this).removeAttr('disabled');
        } else {
          $(this).attr('disabled','disabled');
        }
        break;
      case 2:
        if(parseInt($(this).val()) < 25)
        {
          $(this).attr('disabled','disabled');
        } else {
          $(this).removeAttr('disabled');
        }
        break;
      default:
        $(this).removeAttr('disabled');
        break;
    }
  });
}

function SetPlayersNA()
{
  $('#binDefault').val('false');
  SelectOptionByValue('#intMaleMVP','0');
  $('#intMaleMVP').attr('disabled','disabled');
  SelectOptionByValue('#intFemaleMVP','0');
  $('#intFemaleMVP').attr('disabled','disabled');
  SelectOptionByValue('#intMaleMSLP','0');
  $('#intMaleMSLP').attr('disabled','disabled');
  SelectOptionByValue('#intFemaleMSLP','0');
  $('#intFemaleMSLP').attr('disabled','disabled');
  SelectOptionByValue('#intMaleHighScore','0');
  $('#intMaleHighScore').attr('disabled','disabled');
  SelectOptionByValue('#intFemaleHighScore','0');
  $('#intFemaleHighScore').attr('disabled','disabled');
  $('#MHSP').val(0);
  $('#MHSP').attr('disabled','disabled');
  $('#FHSP').val(0);
  $('#FHSP').attr('disabled','disabled');
  SelectOptionByValue('#intMaleHighOut','0');
  $('#intMaleHighOut').attr('disabled','disabled');
  SelectOptionByValue('#intFemaleHighOut','0');
  $('#intFemaleHighOut').attr('disabled','disabled');
  $('#MHOP').val(0);
  $('#MHOP').attr('disabled','disabled');
  $('#FHOP').val(0);
  $('#FHOP').attr('disabled','disabled');
  $('#int180a').attr('disabled','disabled');
  $('#int180b').attr('disabled','disabled');
  $('#int180c').attr('disabled','disabled');
  $('#int180d').attr('disabled','disabled');
  $('#int180e').attr('disabled','disabled');
  $('#int180f').attr('disabled','disabled');
  $('#int180g').attr('disabled','disabled');
  $('#int180h').attr('disabled','disabled');
  $('#int180i').attr('disabled','disabled');
  $('#int180j').attr('disabled','disabled');
}

function ResetPlayers()
{
  $('#binDefault').val('false');
  $('#intGamesWon').removeAttr('disabled');
  SelectOptionByValue('#intMaleMVP','');
  $('#intMaleMVP').removeAttr('disabled');
  SelectOptionByValue('#intFemaleMVP','');
  $('#intFemaleMVP').removeAttr('disabled');
  SelectOptionByValue('#intMaleMSLP','');
  $('#intMaleMSLP').removeAttr('disabled');
  SelectOptionByValue('#intFemaleMSLP','');
  $('#intFemaleMSLP').removeAttr('disabled');
  SelectOptionByValue('#intMaleHighScore','');
  $('#intMaleHighScore').removeAttr('disabled');
  SelectOptionByValue('#intFemaleHighScore','');
  $('#intFemaleHighScore').removeAttr('disabled');
  $('#MHSP').val('');
  $('#MHSP').removeAttr('disabled');
  $('#FHSP').val('');
  $('#FHSP').removeAttr('disabled');
  SelectOptionByValue('#intMaleHighOut','');
  $('#intMaleHighOut').removeAttr('disabled');
  SelectOptionByValue('#intFemaleHighOut','');
  $('#intFemaleHighOut').removeAttr('disabled');
  $('#MHOP').val('');
  $('#MHOP').removeAttr('disabled');
  $('#FHOP').val('');
  $('#FHOP').removeAttr('disabled');
  $('#int180a').removeAttr('disabled');
  $('#int180b').removeAttr('disabled');
  $('#int180c').removeAttr('disabled');
  $('#int180d').removeAttr('disabled');
  $('#int180e').removeAttr('disabled');
  $('#int180f').removeAttr('disabled');
  $('#int180g').removeAttr('disabled');
  $('#int180h').removeAttr('disabled');
  $('#int180i').removeAttr('disabled');
  $('#int180j').removeAttr('disabled');
}

function SelectOptionByValue(fld,val)
{
  if($(fld).length)
  {
    if(val=='') val = '""'
    $(fld +' option[value='+val+']').attr('selected','selected');
  }
}

//the following functions are used on the survey form
function CheckSurvey(frm)
{
  var binSelected = false;
  for(i = 0;i < frm.intSurveyOptionID.length; i++)
  {
  //alert(frm.intSurveyOptionID[i].checked);
    if(frm.intSurveyOptionID[i].checked) binSelected = true;
  }
  if(!binSelected) alert('You have not selected an option yet!');
  return(binSelected);
}

//the following functions are used on the change password form
function CheckChangePwd(frm)
{
  var msg = '';
  var passed = true;
  if(frm.strCurrentPassword.value == '' || frm.strNewPassword.value == '' || frm.strConfirmNewPassword.value == '')
  {
    passed = false;
    msg = 'You must fill in all fields to continue.'
    frm.strCurrentPassword.style.backgroundColor = '';
    if(frm.strCurrentPassword.value == '') frm.strCurrentPassword.style.backgroundColor = missingInputBgColor;
    frm.strNewPassword.style.backgroundColor = '';
    if(frm.strNewPassword.value == '') frm.strNewPassword.style.backgroundColor = missingInputBgColor;
    frm.strConfirmNewPassword.style.backgroundColor = '';
    if(frm.strConfirmNewPassword.value == '') frm.strConfirmNewPassword.style.backgroundColor = missingInputBgColor;
  } else {
    if(frm.strNewPassword.value != frm.strConfirmNewPassword.value)
    {
      frm.strNewPassword.style.backgroundColor = missingInputBgColor;
      frm.strConfirmNewPassword.style.backgroundColor = missingInputBgColor;
      passed = false;
      msg = 'The passwords do not match!'
    } else {
      if(frm.strNewPassword.value.length < 6)
      {
        frm.strNewPassword.style.backgroundColor = missingInputBgColor;
        frm.strConfirmNewPassword.style.backgroundColor = missingInputBgColor;
        passed = false;
        msg = 'New password must bet at least six (6) characters long!'
      } else {
        if(frm.strNewPassword.value == frm.strCurrentPassword.value)
        {
          frm.strCurrentPassword.style.backgroundColor = missingInputBgColor;
          frm.strNewPassword.style.backgroundColor = missingInputBgColor;
          frm.strConfirmNewPassword.style.backgroundColor = missingInputBgColor;
          passed = false;
          msg = 'The new password you entered is the same as the current password!'
        }
      }
    }
  }
  if(!passed) alert(msg);
  return passed;
}

function PlayerAttendance(val,chkd, fld)
{
//alert(fld);
  if(val != '')
  {
    var aFld = ['#intFemaleMSLP', '#intFemaleMVP', '#intFemaleHighScore', '#intFemaleHighOut',
                '#intMaleMSLP', '#intMaleMVP', '#intMaleHighScore', '#intMaleHighOut',
                '#int180a', '#int180b', '#int180c', '#int180d', '#int180e', '#int180f', '#int180g', '#int180h', '#int180i', '#int180j'];
    $.each(aFld, function()
    {
      if(chkd)
      {
        $(this + ' option[value=' + val + ']').removeAttr('disabled');
        $('#' + fld).parent().css('background-color',null);
        $('#' + fld).parent().next().css('background-color',null);
      } else {
        $(this + ' option[value=' + val + ']').attr('disabled','disabled');
      }
    });
  }
}

$(document).ready(function()
{
  if($('#npwd').length)
  {
    $('#npwd').alphanumeric();
    $('#cnpwd').alphanumeric();
    $('#npwd').password_strength();
    $('#cnpwd').change(function() { if($('#npwd').val() != $(this).val()) alert('Passwords do not match!') });
  }
  //alert($('#formFunction').val());
  if($('#formFunction').value = 'ScoreSheet')
  {
    if($('#MHSP').length) $('#MHSP').numeric(177);
    if($('#FHSP').length) $('#FHSP').numeric(177);
    if($('#MHOP').length) $('#MHOP').numeric(170);
    if($('#FHOP').length) $('#FHOP').numeric(170);
    if($('#intPoints').length) $('#intPoints').change(function() { CheckWonLostTied($(this).val(), $(this)) });
    if($('#intGamesWon').length) $('#intGamesWon').change(function() { $(this).css('background-color',$(this).val() == '' ? missingInputBgColor : null) });
    if($('#intMaleHighScore').length) $('#intMaleHighScore').change(function() { CheckScore($(this).val(),'MHSP') });
    if($('#intMaleHighOut').length) $('#intMaleHighOut').change(function() { CheckScore($(this).val(),'MHOP') });
    if($('#intFemaleHighScore').length) $('#intFemaleHighScore').change(function() { CheckScore($(this).val(),'FHSP') });
    if($('#intFemaleHighOut').length) $('#intFemaleHighOut').change(function() { CheckScore($(this).val(),'FHOP') });
    var aFld = ['#intFemaleMSLP', '#intFemaleMVP', '#intFemaleHighScore', '#intFemaleHighOut',
                '#intMaleMSLP', '#intMaleMVP', '#intMaleHighScore', '#intMaleHighOut',
                '#MHSP', '#MHOP', '#FHSP', '#FHOP'];
    $.each(aFld, function(i,v)
    {
      if($(v).length)
      {
        $(v).change(function()
        {
          $(v).css('background-color',$(v).val() == '' ? missingInputBgColor : null)
        });
      }
    });
    if($('input[name=attendance]').length)
    {
      $('input[name=attendance]').each(function(){
        $(this).click(function(){
          PlayerAttendance($(this).val(), $(this).attr('checked'), $(this).attr('id'));
        });
      });
    }
    if($('input[name=intSurveyOptionID]').length)
    {
      $('input[name=intSurveyOptionID]').each(function(){
        $(this).click(function(){
          $('input[name=intSurveyOptionID]').each(function(){
            $(this).parent().parent().css('background-color',null);
          });
          $(this).parent().parent().css('background-color',optionSelectedBgColor);
        });
      });
    }
  }
});

