/****************************************************************************************

Please feel free to look around, but BE WARNED this is trainee level code
(if you haven't spotted that already) and you won't learn much.

 ***************************************************************************************/

  var gmt
  var perhour = new Array
  perhour[0] = " mph"
  perhour[1] = " kph"

function loader() {
   if (document.cookie != "") {
                                       // remove "variable=" from cookie
      var values  =  document.cookie.split("=")
                                       // split stored chainring and sprocket values
      var values2 =  values[1].split(">>")

      for (i = 0; i < values2.length; i++) {
         if (values2[i] == 'undefined') {values2[i] = ""}
      }
      document.gears1.ring1.value     = values2[0]
      document.gears1.sprock1.value   = values2[1]
      document.gears1.gear.value      = values2[2]
      document.gears1.heightMetric.value    = values2[3]
      document.gears1.weightMetric.value    = values2[4]
      document.gears1.distance.value  = values2[5]
      document.gears1.time.value      = values2[6]
      document.gears1.spdcad.value    = values2[7]
      document.gears1.distcad.value   = values2[8]
      document.gears1.timecad.value   = values2[9]
      document.gears1.heightImperial.value    = values2[10]
      document.gears1.weightImperial.value    = values2[11]
      document.gears1.weightImperialLbs.value    = values2[12]
   }
                                       // cookie expiry date one year from today...
   var exp = new Date()
   var oneYearFromNow = exp.getTime() + (365*24*60*60*1000)
   exp.setTime(oneYearFromNow)
                                       // ...must be in GMT format
   gmt = exp.toGMTString()
}
// *******************************************
function cookieSet() {
   var list =          document.gears1.ring1.value
              + ">>" + document.gears1.sprock1.value
              + ">>" + document.gears1.gear.value
              + ">>" + document.gears1.heightMetric.value
              + ">>" + document.gears1.weightMetric.value
              + ">>" + document.gears1.distance.value
              + ">>" + document.gears1.time.value
              + ">>" + document.gears1.spdcad.value
              + ">>" + document.gears1.distcad.value
              + ">>" + document.gears1.timecad.value
              + ">>" + document.gears1.heightImperial.value
              + ">>" + document.gears1.weightImperial.value
              + ">>" + document.gears1.weightImperialLbs.value
   document.cookie = "list=" + list + "; expires=" + gmt
}

// *******************************************
function avspd() {

   cookieSet()

   if (!number(document.gears1.distance.value)) {
      document.gears1.speed.value = 'The distance>' + document.gears1.distance.value +
                                    '< must be a number'
      return false
   }
   if (!numberList(document.gears1.time.value)) {
      document.gears1.speed.value = 'The time>' + document.gears1.time.value +
                                    '< must be up to 3 numbers (hours minutes seconds)' +
                                    'separated by blanks'
      return false
   }
   distance = parseFloat(document.gears1.distance.value,10)

   secs = timeToSecs(document.gears1.time.value)
   average = (distance/(secs/3600))
   if (document.gears1.kmormi.selectedIndex == 0) {
      mph = average
      kph = milesToKm(average)
   }
   else {
      kph = average
      mph = kmToMiles(kph)
   }

   kph = kph.toFixed(2)
   mph = mph.toFixed(2)
   document.gears1.speed.value = kph + " kph, " + mph + " mph."
}
// *******************************************
function cogs() {
   if (!number(document.gears1.gear.value)) {
      document.gears1.part3.value = 'The gear>' + document.gears1.gear.value +
                                    '< must be in Inches or Metres. '
      return false
   }
   if (document.gears1.wheel2.value != "") {
      diameter = document.gears1.wheel2.value
      if (!numberList(document.gears1.wheel2.value)) {
         document.gears1.part3.value = 'The wheelsize>' + document.gears1.wheel2.value +
                                       '< must be in Inches or Centimetres. '
         return false
      }
      userWheelsize = true
   }
   else {
      var wheelSize = document.gears1.diameter2.selectedIndex
      var diameter  = document.gears1.diameter2.options[wheelSize].value
      userWheelsize = false
   }


   document.gears1.part3.value = ''
   cookieSet()
                                       // check if development specified in Inches or Metres
   var inInches
   (document.gears1.development2.selectedIndex == 0) ? inInches = true : inInches = false

   if (inInches) {
                                       // the development is in inches
      if (userWheelsize) {
         if ((document.gears1.units2.selectedIndex == 1)) {
                                       // manual wheel selection in centimetres; convert to inches.
            diameter = cmToIn(diameter)
         }
      }
   }
   else {
                                       // the development is required in metres
      if (!userWheelsize  || (userWheelsize && document.gears1.units2.selectedIndex == 0)) {
                                       //   convert to centimetres for either of:
                                       // 1. manual wheel selection in inches
                                       // 2. auto selection from list
         diameter = inToCm(diameter)
      }
   }

   if (userWheelsize && (document.gears1.dorc2.selectedIndex == 1)) {
                                       // if it's a circumference, divide by 2 pi
            diameter = diameter/(Math.PI)
   }

   gearvalue = parseFloat(document.gears1.gear.value)

  chainwheel:
   for (i = 22; i < 70; i++) {
      previous = 0
  sprocket:
      for (j = 32; j > 10; j--) {

                                       // calculation of gear in Inches
         if (inInches) {
            ratio = ((i/j) * diameter).toFixed(2)
         }
         else {
                                       // calculation of gear in Metres
            ratio = (((i/j) * diameter*Math.PI)/100).toFixed(2)
         }
                                       // for each chainring give the sprocket which gives the gear
                                       // as near to but less than the required ratio

         if ((ratio > gearvalue) & (ratio != 0))  {
            k=j+1
            document.gears1.part3.value += i.toString() + "x" + k.toString() +  " " + previous  +  "  "
            break sprocket
         }
         previous = ratio
      }
   }
}

// *******************************************
function gears() {
   document.gears1.part2cad.value = ''
   document.gears1.part2.value    = ''
   gearCalc = true
                                       // retrieve chainring and sprocket values from window
   if (!integerList(document.gears1.ring1.value)) {
      document.gears1.part2.value += 'The list of chainrings >' + document.gears1.ring1.value +
                                    '< must be a series of numbers.\n'
      gearCalc = false
   }
   if (!integerList(document.gears1.sprock1.value)) {
      document.gears1.part2.value += 'The list of sprockets >' + document.gears1.sprock1.value +
                                    '< must be a series of numbers.\n'
      gearCalc = false
   }
   speedcad = 0
   if (document.gears1.spdcad.value.search(/\S/) >= 0) {
                                       // Is the speed a valid number?
     if (!number(document.gears1.spdcad.value)) {
        document.gears1.part2cad.value += 'The speed >' + document.gears1.spdcad.value +
                                      '< must be a number (optional).\n'
     }
     else
     {
                                       // Speed valid, select units
        speedcad = parseFloat(document.gears1.spdcad.value,10)
        if (document.gears1.spdunits.selectedIndex == 0) {speedcad = milesToKm(speedcad)}
     }
   }

                                       // diameter 1. (from the list)
   if (document.gears1.wheel.value != "") {
      userWheelsize = true
      diameter = document.gears1.wheel.value
      if (!numberList(diameter)) {
          document.gears1.part2.value += 'The wheelsize >' + diameter +
                                         '< is not a number, default value used.\n'
         userWheelsize = false
      }
   }
   if (document.gears1.wheel.value.search(/\S/) < 0 || !userWheelsize) {
                                       // diameter (or circumference) 2. (by data entry)
      wheelSize = document.gears1.diameter.selectedIndex
      diameter  = document.gears1.diameter.options[wheelSize].value
      userWheelsize = false
   }
   cookieSet()

                                       // Are 2 out of 3 of distance, time, speed
                                       // specified?  If so, the 3rd can be calculated
   distcad = 0
   if (document.gears1.distcad.value.search(/\S/) >= 0) {
                                       // Is the distance a valid number?
     if (!number(document.gears1.distcad.value)) {
        document.gears1.part2cad.value += 'The distance >' + document.gears1.distcad.value +
                                      "< must be a number (optional).\n" ;
     }
     else
     {
                                       // Distance valid, select units
        distcad = parseFloat(document.gears1.distcad.value,10)
        if (document.gears1.kmormil.selectedIndex == 0) {distcad = milesToKm(distcad)}
     }
   }
   timecad = 0
   if (document.gears1.timecad.value.search(/\S/) >= 0) {
                                       // Is the time a valid list of number?
     if (!numberList(document.gears1.timecad.value)) {
        document.gears1.part2cad.value += 'The time >' + document.gears1.timecad.value +
                                      "< must be up to 3 numbers (hh mm ss) (optional).\n" ;
     }
     else
     {
                                       // Time valid, turn into computable number
        timecad = timeToSecs(document.gears1.timecad.value)
     }
   }
   if ((speedcad != 0 && distcad == 0 && timecad == 0) ||
       (speedcad == 0 && distcad != 0 && timecad == 0) ||
       (speedcad == 0 && distcad == 0 && timecad != 0) ||
       (speedcad == 0 && distcad == 0 && timecad == 0) ||
       (speedcad != 0 && distcad != 0 && timecad != 0)   )   {
        document.gears1.part2cad.value += "You must specify 2 out of 3 " +
                                      "(speed, distance, time) to get the third.\n" ;
   }

                                       // We now have time in secs, distance in km, speed in km/sec...

   if (speedcad != 0 && distcad != 0 && timecad == 0) {
      timecad = (distcad/speedcad)*3600
   }
   else
   if (speedcad != 0 && distcad == 0 && timecad != 0) {
      distcad = speedcad*(timecad/3600)
   }
   else
   if (speedcad == 0 && distcad != 0 && timecad != 0) {
      speedcad = distcad/(timecad/3600)
   }
                                       // ... time in secs, distance in km, speed in kph
   mTemp = kmToMiles(distcad).toFixed(2)
   essM = ""
   if (mTemp != 1) essM = "s"

   document.gears1.part2cad.value += "Distance: " + distcad.toFixed(2) + "Km (" +
                                      kmToMiles(distcad).toFixed(2) + " mile" + essM + "). " +
                                     "\nSpeed: " + speedcad.toFixed(2) + " kph (" +
                                      kmToMiles(speedcad).toFixed(2) + " mph). " +
                                     "\nTime: "  + secsToHhmmssTxt(timecad) + "\n\n";

                                       // store validated rings & sprockets in cookie

                                       // create arrays of rings and sprockets
   var rings2   = document.gears1.ring1.value.split(/ /g)
   var sprocks2 = document.gears1.sprock1.value.split(/ /g)
                                       // extract array lengths
   var rl = rings2.length
   var sl = sprocks2.length

   if (userWheelsize && (document.gears1.dorc.selectedIndex == 1)) {
                                       // if it's a circumference, divide by 2 pi
            diameter = diameter/(Math.PI)
   }
                                       // check if development required in Inches or Metres
   var inInches
   (document.gears1.development.selectedIndex == 0) ? inInches = true : inInches = false

   if (inInches) {
                                       // the development is required in inches
      if (userWheelsize) {
         if ((document.gears1.units.selectedIndex == 1)) {
                                       // manual wheel selection in centimetres; convert to inches.
            diameter = cmToIn(diameter)
         }
      }
   }
                                       // the development is required in metres
   if (!userWheelsize  || (userWheelsize && document.gears1.units.selectedIndex == 0)) {
                                       //   convert to centimetres for either of:
                                       // 1. manual wheel selection in inches
                                       // 2. auto selection from list
      diameterM = inToCm(diameter)
   }
                                       // loop calculating each ratio, keeping a list
   var cads = ""
   var cad
   var ratios = ""
   var ratio
   for (j = 0; j < sl; j++) {
      ratios += "    " +sprocks2[j] + " "
      cads   += "    " +sprocks2[j] + " "
   }
   cads   += "\n"
   ratios += "\n"
   for (i = 0; i < rl; i++) {
      for (j = 0; j < sl; j++) {
                                       // enable calculations (input is strings)
         ch = parseInt(rings2[i],10)
         sp = parseInt(sprocks2[j],10)
                                       // calculation of gear in Inches
         ratioI = ((ch/sp) * diameter).toFixed(2)
         ratioM = (((ch/sp) * diameterM*Math.PI)/100).toFixed(2)
         if (inInches) {istring = ratioI.toString() + " "}
         else          {istring = ratioM.toString() + " "}

         if (istring.length == 6) {istring = " " + istring}
         ratios += istring

         if (speedcad != 0) {
            istring = ((speedcad*1000)/60/ratioM).toFixed(2)
            istring = istring.toString() + " "
            if (istring.length == 6) {istring = " " + istring}
            cads += istring
         }
      }
                                       // line break for new chainring
      ratios += "\n"
      cads   += "\n"
   }
   document.gears1.part2.value += ratios
                                       // only assign value if speed actually specified!
   if (speedcad != 0) {
      document.gears1.part2cad.value = cads + "\n" + document.gears1.part2cad.value
   }
}
// *******************************************
function bmi() {

   theWeight = 0
   theHeight = 0
   document.gears1.bmivalue.value = ""
                              /* Check if Metric or Imperial height supplied           */
   document.gears1.heightMetric.value      = trim(document.gears1.heightMetric.value);
   document.gears1.heightImperial.value    = trim(document.gears1.heightImperial.value);
   document.gears1.weightMetric.value      = trim(document.gears1.weightMetric.value);
   document.gears1.weightImperial.value    = trim(document.gears1.weightImperial.value);
   document.gears1.weightImperialLbs.value = trim( document.gears1.weightImperialLbs.value);

   document.gears1.bmivalue.value += 'Height: ';
   if (document.gears1.heightMetric.value.search(/\S/) > -1) {
      document.gears1.bmivalue.value += 'metric'

      if (number(document.gears1.heightMetric.value)) theHeight = document.gears1.heightMetric.value
      else document.gears1.bmivalue.value += ' but not a single number'
   }
   else
   if (document.gears1.heightImperial.value.search(/\S/) > -1) {
      document.gears1.bmivalue.value += 'imperial'
/*      document.gears1.bmivalue.value += 'imperial' + ">" + document.gears1.heightImperial.value + "<!" + theHeight;*/

      if (numberList(document.gears1.heightImperial.value)) theHeight = inToCm(myfiToInches("0 0 " + document.gears1.heightImperial.value))/100;
      else document.gears1.bmivalue.value += ' but not numbers'
   }
   else document.gears1.bmivalue.value += ' no value given'
   document.gears1.bmivalue.value += '; '

                              /* Check if Metric or Imperial weight supplied           */

   document.gears1.bmivalue.value += 'Weight: ';
   if (document.gears1.weightMetric.value.search(/\S/) > -1) {
      document.gears1.bmivalue.value += 'metric'

      if (number(document.gears1.weightMetric.value)) theWeight = document.gears1.weightMetric.value
      else document.gears1.bmivalue.value += ' but not a single number'
   }
   else
   if (document.gears1.weightImperial.value.search(/\S/) > -1) {
      document.gears1.bmivalue.value += 'imperial (stones lbs ozs)'

      if (numberList(document.gears1.weightImperial.value)) theWeight = ozsToKilos(stoneToOzs(document.gears1.weightImperial.value));
      else document.gears1.bmivalue.value += ' but not numbers'
   }
   else
   if (document.gears1.weightImperialLbs.value.search(/\S/) > -1) {
      document.gears1.bmivalue.value += 'imperial (lbs ozs)'

      if (numberList(document.gears1.weightImperialLbs.value)) theWeight = ozsToKilos(stoneToOzs("0 " + document.gears1.weightImperialLbs.value));
      else document.gears1.bmivalue.value += ' but not numbers'
   }
   else document.gears1.bmivalue.value += ' no value given'
   document.gears1.bmivalue.value += '; \n'

                              /* Make calculations if both height and weight correct   */

   if (theHeight != 0 && theWeight != 0) {

      theHeightI = inchesToFiTxt(mToIn(theHeight))
      theWeightI = ozsToStoneLbOzsTxt(kilosToOzs(theWeight))


      theHeight = parseFloat(theHeight).toFixed(2)
      theWeight = parseFloat(theWeight).toFixed(2)


      document.gears1.bmivalue.value +=   "Height: " + theHeight + "m (" + theHeightI + ")\n" +
                                          "Weight: " + theWeight + "kg (" + theWeightI + ")\n"

      document.gears1.bmivalue.value +=   "BMI: " + (theWeight/(theHeight*theHeight)).toFixed(2)
   }

   cookieSet()
}

