var highZ = 999;
//var maxnumsimul,instrument,mydomain,mailinglist;
//maxnumsimul=Number(xGetElementById('maxnumsimul').value)

vars= new Array('maxnumsimul','instrument')
function init() {
  mybutton=xGetElementById('cancelpost')
//alert(xGetElementById('movetab'))
  if (xGetElementById('movetab') != null) {  DragSetup() }
  myform=xGetElementById('DefinePost')
  if (myform != null) {
  for (iinp=0;iinp < myform.elements.length;iinp++) {
     if (myform.elements[iinp].type == 'select-one') {
          myselect=myform.elements[iinp]
         for (iopt=0; iopt < myselect.length;iopt++) {
             if (myselect.options[iopt].disabled) {
                 xColor(myselect.options[iopt],'#AAAAAA')
                 if (myselect.selectedIndex == iopt) {
                  sindex=NextEnabled(myselect,iopt)
                  myselect.selectedIndex = sindex 
                }
             }
         }
     }
  }
  }
  SetWindowWidth()
}
function ProcessSubmit() {
  myform=xGetElementById('PostHoursForm')
  editform=xGetElementById('DefinePost')
//for (i=0;i<myform.length;i++) {
//alert(myform.elements[i].name+' '+myform.elements[i].value)
//}
//  input=xGetElementById('newentry')
if (editform.elements['status'].value != 'new') {
//  alert('status: '+editform.elements['status'].value)
  oldentry=myform.elements[xGetElementById('status').value]
  oldentry.value='open' 
}
input=document.PostHoursForm.newentry
  mydomain=xGetElementById('mydomain').value
  mailinglist=xGetElementById('mailinglist').value
  maxnumsimul=Number(xGetElementById('maxnumsimul').value); // alert(maxnumsimul)
  filedate=xGetElementById('filename').value
  datestartobj=xGetElementById('weekdaystart')
  datestartindex=datestartobj.options.selectedIndex
  weekdaystart=datestartobj.value
  datestartstring=datestartobj.options[datestartindex].text
  dateendobj=xGetElementById('weekdayend')
  dateendindex=dateendobj.options.selectedIndex
  weekdayend=dateendobj.value
  dateendstring=dateendobj.options[dateendindex].text
  starth=xGetElementById('hhstart').value
  endh=xGetElementById('hhend').value
  startmin=xGetElementById('minstart').value
  endmin=xGetElementById('minend').value
  poster=xGetElementById('postname').value
  postemail=xGetElementById('postemail').value
  advisor=xGetElementById('postadvisor').value
  autoemail=xGetElementById('automail')
  posttype=xGetElementById('type').value
  for (i=0;i<editform.length;i++)   {
//    alert(editform.elements[i].name)
    if (editform.elements[i].value == '') {
        optionalinput= 'phone,automail,othername,maxnum'
//        alertmessage=editform.elements[i].name+' not defined';  
        if (optionalinput.search(editform.elements[i].name) < 0) {
            alert(editform.elements[i].name+' not defined');return    
         }
    }
  }
error=CheckDate(datestartstring,starth,startmin,dateendstring,endh,endmin)
if (error != '') {alert(error); return} // else {alert('no error')}
if (Number(editform.maxnum.value) > 0 & editform.maxnum.value != editform.defaultValue) {
         maxnum='_'+editform.maxnum.value
}
else {maxnum=''}
if (posttype=='other') {
          if (editform.othername.value != "") {
               posttype=editform.othername.value+maxnum
           }
           else {alert('No name specified for event'); return}
}
else {posttype=posttype+maxnum}
//     alert(editform.type[j].checked)
//doautoemail=editform.type[4].value;
if (autoemail.checked==true) { doemail=autoemail.value} else {doemail='no'} 
//alert(autoemail.checked+' ='+doemail);

  inpname=weekdaystart+':'+starth+':'+startmin+'-'
+weekdayend+':'+endh+':'+endmin
  inpvalue=poster+':'+advisor+':'+postemail+':'+doemail+','+posttype
tempb=''; for (i=0;i<maxnumsimul;i++) {tempb=tempb+Number(1)+';'}
numposts=tempb.split(";")
for (i=0;i<myform.length;i++) { 
//   if (inpname == myform.elements[i].name ) {
//       alert(inpname+'  '+'already exists'); return }
//    else {
      temp= new Array(); temps=new Array(); tempe=new Array(); // for (j=0;j<4;j++) { temp[j]=''}
      temp=myform.elements[i].name.split("-"); 
      if (xDef(temp[0]) ) {temps=temp[0].split(":");}
      if (xDef(temp[1]) ) { tempe=temp[1].split(":");}
      cwd=temps[0]; 
      csh=Number(temps[1]);
      csm=Number(temps[2]);
      cewd=tempe[0]
      ceh=Number(tempe[1])
      cem=Number(tempe[2])
      cboat=(tempe[3]) 
      if (xDef(temp[1]) ) {
         cs=csh+(csm/60)
         ce=ceh+(cem/60) 
         ns=Number(starth)+Number(startmin)/60
         ne=Number(endh)+Number(endmin)/60
//         confirm(cwd+' '+csh+' '+csm+' '+ceh+' '+cem+': '+cs+' - '+ce) 
//         for (nboat=0;nboat<maxnumsimul;nboat++) {   
//          if (weekdaystart == cwd & cboat == 'Boat'+Number(nboat+1) &  ns < ce & ne > cs)  {
//              numposts[nboat]=Number(numposts[nboat])+1
//              }
//           else {}          
//          alert(numposts[nboat]+' simultaneous for '+nboat)   
//          }                 
       }
  
}
posts=1; freeboat=''
//alert(numposts[0]+' '+numposts[1])
for (i=0;i<maxnumsimul;i++) {
     if (numposts[i] >1) {posts=posts+1} else {freeboat=Number(i)+1}  
     }
if (posts > maxnumsimul ) {alert('No more signups are possible during '+inpname); return}
if (maxnumsimul > 1) {
    inpname=inpname+':'+'Boat'+freeboat
}
       input.name=inpname
        input.value=inpvalue 

//  input.name=weekday.value+':'+starth.value+':'+startmin.value+'-'
//+endh.value+':'+endmin.value  
//  input.value=poster.value+','+posttype

if (doemail=='yes') {message='An e-mail will be sent to the listserv'}
    else {
     if (editform.maxnum.value > 0) {
message='No e-mail was sent.  You may want to send an e-mail to the listserv at '+mailinglist+'@'+mydomain+' to let students know'
     }
   else {message=""}
   }
if (confirm(input.name+': '+input.value+'\n '+message ) ) { 
   myform.submit()
  }
}
function DragSetup()
{
  xMoveTo('PostHours', 200, 400);
  xEnableDrag('movetab', OnDragStart, OnDrag, null);
  xShow('PostHours');
}
function OnDragStart(ele, mx, my)
{
  xZIndex('PostHours', highZ++);
}
function OnDrag(ele, mdx, mdy)
{
  xMoveTo('PostHours', xLeft('PostHours') + mdx, xTop('PostHours') + mdy);
}
function SetDefault(oldinput,newinput) {
  mynewinput=xGetElementById(newinput)
  myoldinput=xGetElementById(oldinput)
  startnum=Number(myoldinput.value)
  for (i=0;i<=3;i++){
     hh=startnum+i
     mynewinput.options[i]= new Option(hh,hh,false,false)
  }
  mynewinput.selectedIndex=2
}
function SetSelected(select1,selectmod) {
  myselect=xGetElementById(select1)
  mymodselect=xGetElementById(selectmod)
  myindex=myselect.selectedIndex 
  mymodselect.selectedIndex=myindex
}
function RemoveEntry(entryid) {
//alert(entryid)
xDisplay('PostHours','block')
myform=xGetElementById('PostHoursForm')

formvalues='' //Input:'+input.name+'='+input.value+'  Form: '+myform.name+':\n\n'
for (i=0;i<myform.length;i++) {
   if (entryid == myform.elements[i].name) {
//   if (myform.elements[i].name == 'newentry') {            
//              myform.elements[i].name=entryid
              removedinput=myform.elements[i]
              oldname=removedinput.value            
              myform.elements[i].value='open'               
//              alert(myform.elements[i].name+'='+myform.elements[i].value)
     }
//   formvalues=formvalues+myform.elements[i].name+' '+myform.elements[i].value+'\n'
}
if (confirm('Remove '+oldname+', '+removedinput.name+' from schedule?') )
{  myform.submit()}
}
function AddStudent(entryid) {
 myform=xGetElementById('PostHoursForm')
 editformid='DefineStudent'+entryid
 editform=xGetElementById(editformid)
addstring=editform.elements['skipper'].value+','+editform.elements['type'].value
if (editform.elements['maxnumb'].value != '')
    {addstring=addstring+'_'+editform.elements['maxnumb'].value}
stnames=''
//autoemail=xGetElementById('automail')
skipperinfo=new Array()
skipperinfo=editform.elements['skipper'].value.split(":")
doemail=skipperinfo[2]
//if (autoemail.checked==true) { doemail=autoemail.value} else {doemail='no'}
for (i=3;i<editform.length;i=i+2) {
   if (editform.elements[i].value != '') {
      for(j=2;j<i;j=j+2) {
         if (editform.elements[i].value == editform.elements[j].value){
            alert('Duplicate entries'); return }
      }
      stnames=stnames+' '+editform.elements[i].value
      addstring=addstring+','+editform.elements[i].value+':'+editform.elements[i+1].value }
   else {}
  }
myform.elements[entryid].value=addstring
if (confirm('Signing up '+stnames+' for '+entryid) ) {
          if (doemail == "yes") {message='An e-mail will be sent to the Instructor'}
          else {message='Automatic e-mail is turned off\nNo e-mail was sent to the instructor. You may want to contact him/her directly'}
//          message='Currently no e-mails are sent automatically to the instructors.  You may want to contact the instructor '
//+'directly that you signed up.\n\n Auto e-mail features will be added in the future'
          alert(message)  
          myform.submit()}
}
function raise(layerid) {
mylayer=xGetElementById(layerid)

oldZindex=Number(xZIndex(mylayer))
//xInnerHtml('top'+layerid,'Raise '+layerid+': old: \n z-index:'+oldZindex+'\n')
//if (oldZindex < 10) {
  newZindex=oldZindex+100
//  newZindex=103
  xZIndex(mylayer,newZindex)
  //mylayer.style.borderWidth='1'
  xBorderWidth(mylayer,'medium')
  //mylayer.style.borderColor='red'
  xBorderColor(mylayer,'red')
  //xBackground('Mon:10:00-12:00','cyan')
//  xInnerHtml('top'+layerid,'New:  zindex:'+xZIndex(mylayer)+'\n Border: //'+xBorderWidth(mylayer)+xBorderColor(mylayer)+'\n  Background:'+xBackground(mylayer))
//xInnerHtml('top'+layerid,'Old z-index: '+oldZindex+' New z-index: '+newZindex)
//}
}
function lower(layerid) {
mylayer=xGetElementById(layerid)

oldZindex=xZIndex(mylayer)
//xInnerHtml('top'+layerid,'Lower '+layerid+': Old: '+oldZindex+'\n')
//if (oldZindex > 10) {
   newZindex=oldZindex-100
//   mylayer.style.borderWidth='thin'
//   mylayer.style.borderColor='black'
   xBorderWidth(mylayer,'thin')
   xBorderColor(mylayer,'black')
   xZIndex(mylayer,newZindex)
//}
//xInnerHtml('top'+layerid,'Lower, new:'+xZIndex(mylayer)+'\nBorder:'+xBorderWidth(mylayer)+' //'+xBorderColor(mylayer)+'\n Background:'+xBackground(mylayer))
//xInnerHtml('top'+layerid,'Old z-index: '+oldZindex+' New z-index: '+newZindex)
}
function SetAndSubmit(form,name,newvalue) {
SetWindowWidth()
 myform=xGetElementById(form)
//alert(myform+' '+name+' '+newvalue)
 myform.elements[name].value=newvalue
msg=myform.name+' form (id='+myform.id+')\n'
for (i=0;i < myform.elements.length;i++) {
msg=msg+myform.elements[i].name+'='+myform.elements[i].value+'\n'
}
//alert(msg)
//alert(myform.id+' '+myform.elements[name].name+' '+myform.elements[name].value)
myform.submit()
}
function SetForm(form,name,newvalue) {
 myform=xGetElementById(form)
/* alert('Form:'+myform+' ('+myform.elements.length+' entries)') */
 
input=myform.elements[name]
if (input.type == 'text' | input.type == 'hidden'){
 if (newvalue == 'default') {input.value=input.defaultValue; typ='default'}
 else {input.value=newvalue; typ='newvalue'}
// alert('Set Value of '+name+'='+input.value+'('+typ+')')
}
if (input.type == 'select-one') {
  numopts=input.length; i=0;
  while (i< numopts) {
    if (newvalue == 'default') {
      if (input.options[i].defaultSelected) {
         oindex=NextEnabled(input,i);
//          alert(input.options[jj].value+' disabled:'+input.options[jj].disabled)
         i=numopts
      }
      else {if (i == numopts-1) {oindex=NextEnabled(input,0); } i++}
    } 
    else {
      if (input.options[i].value == newvalue) { oindex=NextEnabled(input,i);  i=numopts}
      else {i++}    
    }
  }
  input.options.selectedIndex=oindex;
//  alert('Set Value of '+name+'='+input.options[input.selectedIndex].value)
}
if (input.type == 'checkbox') {
  if (newvalue == 'default') { input.checked=input.defaultChecked}
  else {  if (input.value == newvalue) {input.checked=true} }
//  alert('Set Value of '+name+'='+input.checked)
}
}
function NextEnabled(myinput,start) {
jj=start; jjcount=0;
numopts=myinput.length
while (myinput.options[jj].disabled & jjcount < numopts) {
   if (jj == numopts-1) {jj=0} 
   else {jj++};
   jjcount++
}
return jj
}
function alertrules() {
message='Advance sign up for on the water instruction is restricted to ONE lesson a day '
+'and TWO lessons per week until 24 h ahead of a lesson.\n\nIf a lesson is still open '
+'less than 24 h prior to the start of the lesson they can be signed up for beyond that limit'
+'\n\nEntries in violation of that rule are subject to removal'
alert(message)
}
function alertsorry() {
message='You have reached your limit of two lessons per week.  \n You can arrange additional '
+'instruction by contacting an instructor directly'
alert(message)
}
function CheckDate(wds,hs,ms,wde,he,me) {
cdate = new Date()
sdate = new Date(Date.parse(wds+','+hs+':'+ms))
edate = new Date(Date.parse(wde+','+he+':'+me))
//alert('start day '+wds+' '+hs+':'+ms+' end day '+wde+' '+he+':'+me+'\n'+'curdate:'+cdate+' Start Date:'+sdate+'End date:'+edate)
diff=(edate-sdate)/(60000)
cdiff=(sdate-cdate)/60000
if(diff < 5) {return('Block must be minimum of 5 minutes')}
if (cdiff < 0) {return('You can not sign up for time before the current time: '+cdate.toLocaleString())}
numsimul=CheckOverlap(sdate,edate)
if (numsimul > maxnumsimul) {return('At least part of this time is already taken by '+maxnumsimul+' users')}

return('')
}
function PreSetValues(formid,entry,name,group,contact,type,othername,maxnum,automail,wd,hh,mm,wde,hhe,mme) {

SetForm(formid,'Name',name)
SetForm(formid,'Advisor',group)
SetForm(formid,'email',contact)
SetForm(formid,'type',type)
SetForm(formid,'othername',othername)
SetForm(formid,'maxnum',maxnum)
SetForm(formid,'automail',automail)
SetForm(formid,'weekday start',wd); //alert('setting weekday to '+wd+' thruogh '+wde)
SetForm(formid,'Start h',hh); //alert('setting hh to '+hh)
SetForm(formid,'Start min',mm)
SetForm(formid,'weekday end',wde)
SetForm(formid,'End h',hhe)
SetForm(formid,'End min',mme)
SetForm(formid,'status',entry)
//alert(xGetElementById('othernameinp')+' '+xGetElementById('attendanceinp')+' '+xGetElementById('autoemailinp'))
if (Number(maxnum) > 0) {xDisplay('attendanceinp','inline');xDisplay('autoemailinp','inline')}
else {xDisplay('attendanceinp','none');xDisplay('autoemailinp','none')}
if (type == 'other') {xDisplay('othernameinp','inline') }
else {xDisplay('othernameinp','none')}
 


/* i=0; myform=xGetElementById(formid)
while (i< myform.elements.length) {
  if (confirm(myform.elements[i].name+'('+myform.elements[i].type+')='+myform.elements[i].value)) {i++} else {i=myform.elements.length}
} */
}
function SetFormDefaults(formid) {
myform=xGetElementById(formid)
EnableAll(xGetElementById('hhstart'))
EnableAll(xGetElementById('hhend'))
for (count=0;count<myform.length;count++) {
   myname=myform.elements[count].name
//   alert(myname+' ('+i+'/'+myform.length+')')
  SetForm(formid,myname,'default')
}
xDisplay('attendanceinp','none');xDisplay('autoemailinp','none')
xDisplay('othernameinp','none')
}
function CheckOverlap(nsdate,nedate) {
nsimul=1;
filedatea=new Array(); filedatea=filedate.split(".")
wnum=Number(filedatea[2]); fyear=Number(filedatea[1])
for (i=0;i<myform.length;i++) { 
//   if (inpname == myform.elements[i].name ) {
//       alert(inpname+'  '+'already exists'); return }
//    else {
   if (myform.elements[i].value != 'open') {
      temp= new Array(); temps=new Array(); tempe=new Array(); // for (j=0;j<4;j++) { temp[j]=''}
      temp=myform.elements[i].name.split("-"); 
      if (xDef(temp[0]) ) {temps=temp[0].split(":");}
      if (xDef(temp[1]) ) { tempe=temp[1].split(":");}
      if (temp.length > 1) {
        cwd=temps[0]; 
        csh=Number(temps[1]);
        csm=Number(temps[2]);
        cewd=tempe[0]
        ceh=Number(tempe[1])
        cem=Number(tempe[2])
        cboat=(tempe[3])
        csdate = Week2Date(fyear,cwd,wnum,csh,csm)
        cedate = Week2Date(fyear,cewd,wnum,ceh,cem)
//        csdate = new Date(Date.parse(cwd+','+csh+':'+csm))
//        cedate = new Date(Date.parse(cewd+','+ceh+':'+cem))
//        alert('comparing '+nsdate+'-'+nedate+' with '+csdate+'-'+cedate)
        if (Number(nsdate) < Number(cedate) && Number(nedate) > Number(csdate)) {nsimul++}
      }
   }
//   else {alert('skipping entry '+myform.elements[i].name)}
}
return(nsimul)
}
function Week2Date(year,wd,weeknum,hour,min) {
week = new Array('Mon','Tue','Wed','Thu','Fri','Sat','Sun')
dow=0
while (week[dow] != wd && dow < week.length) {
  dow++
}
onejan = new Date(year,0,1)
onejanoffset=onejan.getTimezoneOffset()
onejandow=Number(onejan.getDay())-1
if (onejandow < 0) {onejandow=6}
timethisyear=Number((86400000*(7*(weeknum-1)+dow-onejandow))+3600000*hour+60000*min)
mydateraw = new Date(Number(onejan)+timethisyear)
mydateoffset=mydateraw.getTimezoneOffset()
mydate= new Date(Number(mydateraw)+(mydateoffset-onejanoffset)*60000)
//alert('wd='+wd+' weeknum='+weeknum+' year='+year+' dow='+dow+' onejan='+onejan+' onejandow='+onejandow+' onejanoffset='+onejanoffset+' timethisyear='+timethisyear+'  mydateraw='+mydateraw+' mydateoffset='+mydateoffset+' mydate='+mydate)
//alert(mydate)
return(mydate)
}
function DisableOptions(curselect,selectid,maxindex) {
 myselect=xGetElementById(selectid)
myselect.selectedIndex=maxindex
for (i=Number(maxindex)+1;i<myselect.options.length;i++) {
     if (curselect.selectedIndex == curselect.options.length-1) { 
               //   xDisplay(myselect.options[i],'none');
                 xColor(myselect.options[i],'#AAAAAA')
                 myselect.options[i].disabled = true
     }
     else { 
//        xDisplay(myselect.options[i],'block');
        xColor(myselect.options[i],'#000000')
        myselect.options[i].disabled = false 
     }
//     if (i==Number(maxindex)+1) {alert(myselect.options[i].value+'='+myselect.options[i].disabled+' '+xColor(myselect.options[i]))}
}
}
function CheckDisabled(myselect) {
  if (myselect.options[myselect.selectedIndex].disabled) {
   SetForm(myselect.form,myselect.name,'default')
  }
}
function EnableAll(myselect) {
for (io=0;io<myselect.length;io++) {
  myselect.options[io].disabled=false;
  xColor(myselect.options[io],'#000000')
 }
}
function SetWindowWidth() {
 windowhsize=Number(xClientWidth());
 windowvsize=Number(xClientHeight())
AddHidden('all','windowwidth',windowhsize)
AddHidden('all','windowheight',windowvsize)
/*  for (i=0;i<document.forms.length;i++) {  
    myform=document.forms[i]   
    if (myform.action) { 
        if (! xDef(myform.elements['windowwidth'])) {
  //           alert('adding new element windowwidth in'+myform.name); 
             AddHidden(myform,'windowwidth',windowhsize); }
        else { 
           if (Number(myform.elements['windowwidth'].value) != windowhsize) {
//alert('modifying existing '+myform.elements['windowwidth'].name+' from '+myform.elements['windowwidth'].value+'to '+windowhsize+'in form '+myform.name)         
              AddHidden(myform,'windowwidth',windowhsize); }
//           else {alert('keeping '+myform.elements['windowwidth'].name+'='+myform.elements['windowwidth'].value+' in form '+myform.name)}
        }
//      alert(myform.name+'-'+myform.action.value+':'+myform.elements['windowwidth'].name+'='+myform.elements['windowwidth'].value) 
      }  
  } */
}
