// Limmud Conference App Form 2006 JavaScript

/*\ TODO:
 *  Validation on add new participant 
\*/

var numParticipants;
var participantData=[];
var dobTxts=[['dobDay','dd'],['dobYear','yyyy']];
var mustSelects=[['dobMonth','mm','mm'],['diet','Please select',''],['roomType','Please select','']];
var hide=['early','shab','room'];
var texts=['title','firstName','lastName','email','mobile','specialNeeds', 'id'];
var checks=['sexM','sexF','accommodationRes','accommodationNonRes','shabbat','earlyCheckIn','nonResSunday','nonResMonday','nonResTuesday','nonResWednesday','nonResThursday'];
var selects=['profession','outCoach','returnCoach'];
var currentYear = (new Date()).getFullYear();

function visParticipant(num,show)
{
  var disp=show?'':'none';
  
  //for(var n=1;n<=8;n++) if(n!=7) participantData[num]['row'+n].style.display=disp;
  for(var n=1;n<=8;n++) participantData[num]['row'+n].style.display=disp;
}

function init()
{
  var element;
  var maxParticipant;
  
  getParticipantData();
  for(var n=0;n<6;n++)
  {
    var participant=participantData[n];
    
    for(m=0;m<dobTxts.length;m++)
    {
      element=participant[dobTxts[m][0]];
      element.noValueText=dobTxts[m][1];
      element.onfocus=dobTextFocus;
      element.onblur=dobTextBlur;
      element.onkeydown=dobTextKeyDown;
      dobTextBlur(element,true);
    }
    for(m=0;m<mustSelects.length;m++)
    {
      element=participant[mustSelects[m][0]];
      element.selectOneText=mustSelects[m][1];
      if(element.options[0].value!="") continue;
      if(element.selectedIndex==0) element.onchange=mustSelectIndexChange;
      else element.options[0]=null;
    }
    for(m=0;m<hide.length;m++) participant[hide[m]].style.display='none';
    participant['accommodationRes'].onclick=selectAccommodationType;
    if(participant['accommodationRes'].checked)
    {
      participant['shab'].style.display=participant['early'].style.display=participant['room'].style.display='';
    }
    participant['accommodationNonRes'].onclick=selectAccommodationType;
    //if(participant['accommodationNonRes'].checked) participant['row7'].style.display='';
    if(!n||!isBlank(n)) maxParticipant=n+1;
    participant['shabbat'].onclick=selectShabbat;
    participant['earlyCheckIn'].onclick=selectEarlyCheckIn;
  }
  for(n=maxParticipant;n<6;n++) visParticipant(n,false);
  numParticipants=maxParticipant;
  setNextPrevVisibility();
  document.getElementById('Next').onclick=showNextParticipant;
  document.getElementById('Prev').onclick=removeLastParticipant;
  document.getElementById('heardother').style.display = (document.getElementById('id_heard').value=='OT'?'block':'none');
  document.getElementById('id_heard').onchange = showHeardOther;

    // set autocomplete=off in forms.py for participant firstname, lastname, and  email
    // set back to on for first participant
    participantData[0]['firstName'].setAttribute('autocomplete','on');
    participantData[0]['lastName'].setAttribute('autocomplete','on');
    participantData[0]['email'].setAttribute('autocomplete','on');
    
}
window.onload=init;

function dobTextFocus(e)
{
  var target=window.event?event.srcElement:e.target;
  
  if(target.value==target.noValueText) target.value='';
}

function dobTextBlur(e,directCall)
{
  var target=directCall?e:(window.event?event.srcElement:e.target);

  if(target.value==''||target.value=='0') target.value=target.noValueText;
}

function dobTextKeyDown(e)
{
  var keyCode=(window.event?event:e).keyCode;

  if(keyCode==8||keyCode==9||keyCode==13||keyCode==46) return true;
  if((keyCode<48||keyCode>57)&&(keyCode<96||keyCode>105)&&(keyCode<37||keyCode>40)) return false;
}

function showNextParticipant()
{
  if(validateLastParticipant(numParticipants-1))
  {
    visParticipant(numParticipants++,true);
    setNextPrevVisibility()
  }
}

function removeLastParticipant()
{
  if(isBlank(numParticipants-1)||confirm("Are you sure?  You will lose any information you have entered for this participant."))
  {
    visParticipant(--numParticipants,false);
    blankParticipant(numParticipants);
    setNextPrevVisibility()
  }
}

function setNextPrevVisibility()
{
  document.getElementById('Next').style.display=(numParticipants==6?'none':'');
  document.getElementById('Prev').style.display=(numParticipants==1?'none':'');
}

function mustSelectIndexChange(e)
{
  var target=window.event?event.srcElement:e.target;
  
  if(target.selectedIndex)
  {
    target.options[0]=null;
    target.onchange=null;
  }
}

function selectAccommodationType(e)
{
  var target=window.event?event.srcElement:e.target;
  if(target.participant==undefined) target=document.getElementById(target.getAttribute("for"));
  var participant=participantData[target.participant];
  var days = participant['row6'].getElementsByTagName('input');
  var checked = participant['accommodationRes'].checked
  if (!checked)
  {
    participant['shabbat'].checked=false;
    participant['earlyCheckIn'].checked=false;
    element=participant['roomType']
    if (element.options[0].value!="")
    {
      for(n=0;n<=element.options.length;n++)
      {
        if(n<element.options.length) thisOpt=element.options[n];
        element.options[n]=n?lastOpt:new Option(element.selectOneText,"");
        if(n<element.options.length) lastOpt=thisOpt;
      }
      element.selectedIndex=0;
      element.onchange=mustSelectIndexChange;
    }
  }
  var ch = false;
  for (var x=0;x < days.length;x++) if (days[x].checked) ch = true;
  if (!ch) for (var x=0;x < days.length;x++) days[x].checked = true;
  participant['shab'].style.display=participant['early'].style.display=participant['room'].style.display=checked?'':'none';
}

function selectShabbat(e)
{
  var target=window.event?event.srcElement:e.target;
  if(target.participant==undefined) target=document.getElementById(target.getAttribute("for"));

  if(target.checked) participantData[target.participant]['earlyCheckIn'].checked=false;
}

function selectEarlyCheckIn(e)
{
  var target=window.event?event.srcElement:e.target;
  if(target.participant==undefined) target=document.getElementById(target.getAttribute("for"));

  if(target.checked) participantData[target.participant]['shabbat'].checked=false;
}

function blankParticipant(num)
{
  var participant=participantData[num];
  for(m=0;m<dobTxts.length;m++)
  {
    element=participant[dobTxts[m][0]];
    element.value=element.noValueText;
  }
  for(m=0;m<mustSelects.length;m++)
  {
    element=participant[mustSelects[m][0]];
    if(element.options[0].value=="") continue;
    for(n=0;n<=element.options.length;n++)
    {
      if(n<element.options.length) thisOpt=element.options[n];
      element.options[n]=n?lastOpt:new Option(element.selectOneText,"");
      if(n<element.options.length) lastOpt=thisOpt;
    }
    element.selectedIndex=0;
   }
  for(n=0;n<texts.length;n++) if(participant[texts[n]]) participant[texts[n]].value='';
  for(n=0;n<checks.length;n++) if(participant[checks[n]]) participant[checks[n]].checked=false;
  for(n=0;n<selects.length;n++) if(participant[selects[n]]) participant[selects[n]].selectedIndex=0;
  for(n=0;n<hide.length;n++) participant[hide[n]].style.display='none';  
}

function validateLastParticipant(num)
{
  var participant=participantData[num];
  var error=[];
  var emailTest=/^(.+@([^.]+\.)+[^.]{2,6})?$/;
  var mobileTest=/^[0-9 -]*$/;
  var numberTest=/^0*[1-9][0-9]*$/;
  var monthLastDays=[31,29,31,30,31,30,31,31,30,31,30,31];
  
  if(participant['firstName'].value=='') error.push("you must supply your first name");
  if(participant['lastName'].value=='') error.push("you must supply your last name");
  if(num==0&&participant['email'].value=='') error.push("you must supply your e-mail address");
  else if(!emailTest.test(participant['email'].value)) error.push("your e-mail address is not valid");
  else if(num==0&&document.getElementById('id_repeat_email')&&participant['email'].value!=document.getElementById('id_repeat_email').value) error.push("e-mail addresses do not match");
  if(!mobileTest.test(participant['mobile'].value)) error.push("your mobile number format is incorrect");
  if(!numberTest.test(participant['dobDay'].value)||!numberTest.test(participant['dobYear'].value)) error.push("day and year must be numeric");
  else if(participant['dobMonth'].options[participant['dobMonth'].selectedIndex].value=="mm") error.push("you must select a month");
  else if(participant['dobDay'].value>monthLastDays[participant['dobMonth'].selectedIndex-1]) error.push("the day is too large for the selected month");
  else if(participant['dobDay'].value==29&&participant['dobMonth'].selectedIndex==2&&participant['dobYear'].value%4) error.push("selected year is not a leap year");
  else if(participant['dobYear'].value<1850||participant['dobYear'].value>currentYear) error.push("the year is outside allowed range");
  if(participant['diet'].options[participant['diet'].selectedIndex].value=="") error.push("you must select a menu option");
  if(!participant['accommodationRes'].checked&&!participant['accommodationNonRes'].checked) error.push("you must select an accommodation option");
  
  if(error.length)
  {
    var errorStr="You cannot add another participant until you correct the current participant:\n";
    for(n=0;n<error.length;n++) errorStr+="* "+error[n]+(n==error.length-1?'.':';')+"\n";
    alert(errorStr);
    return false;
  }
  else return true;
}

function isBlank(num)
{
  var participant=participantData[num];
  
  for(n=0;n<texts.length;n++) if(participant[texts[n]] && participant[texts[n]].value!='') return false;
  for(n=0;n<checks.length;n++) if(participant[checks[n]] && participant[checks[n]].checked) return false;
  for(n=0;n<selects.length;n++) if(participant[selects[n]] && participant[selects[n]].selectedIndex) return false;
  for(n=0;n<mustSelects.length;n++)
  {
    element=participant[mustSelects[n][0]]
    if(element.options[element.selectedIndex].value!=mustSelects[n][2]) return false;
  }
  for(n=0;n<dobTxts.length;n++)
  {
    element=participant[dobTxts[n][0]];
    if(element.value!=element.noValueText&&element.value!="") return false;
  }
  return true;
}

function getParticipantData()
{
  var data=[
    ['id', 'id'],
    ['title','title'],
    ['firstName','firstname'],
    ['lastName','surname'],
    ['sexM','sex_0'],
    ['sexF','sex_1'],
    ['dobDay','dob_day'],
    ['dobMonth','dob_month'],
    ['dobYear','dob_year'],
    ['diet','diet'],
    ['email','email'],
    ['mobile','mobile'],
    ['specialNeeds','specialneeds'],
    ['profession','profession'],
    ['outCoach','outcoach'],
    ['returnCoach','returncoach'],
    ['accommodationRes','accommodation_0'],
    ['accommodationNonRes','accommodation_1'],
    ['roomType','roomtype'],
    ['shabbat','shabbat'],
    ['earlyCheckIn','earlycheckin'],
    ['nonResSunday','days_0'],
    ['nonResMonday','days_1'],
    ['nonResTuesday','days_2'],
    ['nonResWednesday','days_3'],
    ['nonResThursday','days_4']
  ];
  
  for(n=0;n<6;n++)
  {
    participantData[n]=[];
    for(m=0;m<data.length;m++)
        {
            // console.log('n: ' + n + ', m: ' + m + ', data[m]: ' + data[m]);
participantData[n][data[m][0]]=document.getElementById('id_participant_set-'+n+'-'+data[m][1]);
      if(participantData[n][data[m][0]]) {
          participantData[n][data[m][0]].participant=n;
      }
    }
    participantData[n]['early']=document.getElementById('early'+(n+1));
    participantData[n]['shab']=document.getElementById('shab'+(n+1));
    participantData[n]['room']=document.getElementById('room'+(n+1));
    //DR 20/12/07 disable residential non-discounted bookings
    //if (document.location.toString().indexOf('discount') == -1)
    //  participantData[n]['accommodationRes'].disabled=true;
    for(m=1;m<=8;m++) participantData[n]['row'+m]=document.getElementById('participant'+(n+1)+'_'+m);
  }
}

function showHeardOther(e)
{
  var target=window.event?event.srcElement:e.target;
  
  document.getElementById('heardother').style.display = (target.value=='OT'?'block':'none');
}

