/* progress_bar.js
 * definitions of bespoke progress bars for Confirmit surveys and functions 
 * that write them into survey pages (HTML documents) using the W3C DOM API
 *
 * Version 2.3 - added CirclesGreen and CirclesBlue
 * Version 2.2 - added CirclesMaroon progress bar for H&P US Template.
 * Version 2.1 - changed getProgressPercentage() so it looks for blue.gif as 
 *               well as silver.gif
 * Version 2.0 - changed writeProgressBar() to make it GUT compatible; 
 *               removed sayHello() debugging function; changed 
 *               getProgressPercentage() to read width attr from a comment 
 *               node because progress bar is now commented out by default
 * Version 1.0 - first version
 *
 * Copyright (2005) Research Now Ltd.
 */

 
/* ProgressBar constructor - creates ProgressBar objects
 * There are 2 kinds of progress bar:
 *
 * (A) ones that represent extents of completion by different images. Thus a 
 *     change in progress is illustrated by REPLACING the image that showed 
 *     the previous extent of completion, and 
 * (B) ones that use a single image to show extents of completion. This 
 *     single image's width is increased/stretched each time progress 
 *     advances. 
 *
 * Progress in Confirmit surveys is expressed as a percentage. 0% means a 
 * respondent is about to start. 100% means they've completed the survey.
 *
 * baseName             - relative URL of the base name of the ProgressBar's 
 *                        image(s)
 * numberOfImages       - the number of images in the progress bar sequence. 
 *                        For stretch-able "B" type progress bars, this will 
 *                        be 1.
 * percentageMultiplier - a positive integer by which the percentage is 
 *                        multiplied when calculating the width to show for
 *                        the image of a stretch-able "B" type image. This 
 *                        param should be 0 for "A" type progress bars.
 */
function ProgressBar(baseName, numberOfImages, percentageMultiplier) {
  var universalBaseURL      = "http://survey.researchnow.co.uk" 
  			    + "/webprod/resources/PBAR/";
  this.baseName             = universalBaseURL + baseName;
  this.numberOfImages       = numberOfImages;
  this.percentageMultiplier = percentageMultiplier;
}

/* ProgressBar instances, stored in an associative array */
var progressBars                 = new Array();
progressBars['confirmIt']        = null;
progressBars['beer']             = new ProgressBar("beer/Beer.gif", 10, 0);
progressBars['speedometer']      = new ProgressBar("car/Dial.gif", 11, 0);
progressBars['bottle']           = new ProgressBar("beer/Bottle.jpg", 11, 0);
progressBars['car']              = new ProgressBar("car/Car.jpg", 11, 0);
progressBars['skoda']            = new ProgressBar("Skoda/Car.gif", 11, 0);
progressBars['electricGuitar']   = new ProgressBar("music/ElectricGuitar.jpg",
					11, 0);
progressBars['accousticGuitar']  = new ProgressBar(
					"music/AccousticGuitar.jpg", 11, 0);
progressBars['keyboard']         = new ProgressBar("music/Keyboard.jpg",
					11, 0);
progressBars['radio']            = new ProgressBar("radio/Radio.gif", 11, 0);
progressBars['redLine']          = new ProgressBar("redLine.gif", 1, 2);
progressBars['lawnMower']        = new ProgressBar("Lawn/Lawn.gif", 11, 0);
progressBars['pram']             = new ProgressBar("Pram/Pram.gif", 10, 0);
progressBars['vopLogo']          = new ProgressBar("vop_logo/vop_anim.gif",
					14, 0);
progressBars['traffic']          = new ProgressBar("Traffic/Traffic.gif", 9, 0);
progressBars['sport']            = new ProgressBar("Sport/Sport.jpg", 11, 0);
progressBars['circles']          = new ProgressBar("Circles/Circles.gif", 43, 0);
progressBars['circlesVOP']       = new ProgressBar("CirclesVOP/Circles.gif", 43, 0);
progressBars['circlesHP']        = new ProgressBar("CirclesHP/Circles.gif", 43, 0);
progressBars['circlesBlack']     = new ProgressBar("CirclesBlack/Circles.gif", 43, 0);
progressBars['circlesOrange']    = new ProgressBar("CirclesOrange/Circles.gif", 43, 0);
progressBars['circlesRed']       = new ProgressBar("CirclesRed/Circles.gif", 43, 0);
progressBars['circlesRedSmall']  = new ProgressBar("CirclesRedSmall/Circles.gif", 35, 0);
progressBars['circlesMaroon']    = new ProgressBar("CirclesMaroon/Circles.gif", 43, 0);
progressBars['circlesGreen']     = new ProgressBar("CirclesGreen/Circles.gif", 43, 0);
progressBars['circlesBlue']      = new ProgressBar("CirclesBlue/Circles.gif", 43, 0);
progressBars['circlesBlueSmall'] = new ProgressBar("CirclesBlueSmall/Circles.gif", 35, 0);
progressBars['circlesVOPSmall']  = new ProgressBar("CirclesVOPSmall/Circles.gif", 36, 0);
progressBars['starsGreen']       = new ProgressBar("StarsGreen/Stars.gif", 29, 0);
progressBars['circlesOrangeer']    = new ProgressBar("CirclesOrangeer/Circles.gif", 43, 0);


 
/* gets the percentage of the respondent's progress in the current survey by 
 * querying the width attribute of ConfirmIt's own progress bar (which 
 * exists entirely inside a comment node). If Confirmit's own progress bar 
 * can't be found, returns -1.
 */
function getProgressPercentage() {
  var pbarHolder   = document.getElementById("progressBarHolder");
  var pbarChildren = pbarHolder.childNodes;
  
  /* find first comment node inside progressBarHolder div, then get the 
   * value of the width attr of the silver.gif image (on some servers it's 
   * blue.gif), then return it divided by 2 because Confirmit's default 
   * progress bar is a stretch-able image whose percentage multiplier is 2 
   * (i.e. 1% is represented graphically by a width of 2 pixels)
   */
  for (var i = 0; i < pbarChildren.length; i++) {
    var nextChild = pbarChildren[i];
    if ( nextChild.nodeType == 8 /* Node.COMMENT_NODE */ ) {
      var regex   = /(?:blue|silver)\.gif width="?(\d+)/;
      var matches = regex.exec(nextChild.data);
      return matches == null ? -1 : matches[1] / 2;
    }
  }
  
  return 0;    // in case the comment node wasn't found (unlikely!)
}

/* overwrites ConfirmIt's default progress bar image with the one specified 
 * by the PROGRESS_BAR_NAME global variable.
 *
 * NOTE:
 * We would pass PROGRESS_BAR_NAME as an argument but this function was 
 * designed to be an asynchronous handler for the body.onload event, and it 
 * needs to be assigned to body.onload as an rvalue without arguments.
 */
function writeProgressBar() {
  var pbar = progressBars[PROGRESS_BAR_NAME];
  
  // abort - use no progress bar or, if "default", Confirmit's default will 
  // be used
  var pcnt = getProgressPercentage();
  if (pbar == null || pbar.length == 0 || pcnt < 0 || pbar == "default") 
    return;

  var pBarBasename = pbar.baseName;
  var numImages    = pbar.numberOfImages;
  var multiplier   = pbar.percentageMultiplier;
  
  // pad image number to 3 digits
  var imgNumber = Math.round( pcnt / (100 / numImages) );
  if (imgNumber == 0) ++imgNumber;	// pbar images start at 1, not 0
  imgNumber = "" + imgNumber;		// cast to string
  while (imgNumber.length < 3)
    imgNumber = '0' + imgNumber;

  // insert image number into image basename, just before the 
  // "\.(jpg)|(gif)|(png)" file type suffix
  var imgSuffixIdx = pBarBasename.lastIndexOf(".");
  var imgSuffix    = pBarBasename.substring(imgSuffixIdx);
  var imgPrefix    = pBarBasename.substring(0, imgSuffixIdx);
  var imgSrc       = imgPrefix + imgNumber + imgSuffix;

  // create new img element
  var imgElem   = document.createElement("img");
  var srcAttr   = document.createAttribute("src");
  srcAttr.value = imgSrc;
  imgElem.setAttributeNode(srcAttr);

  // if progress bar is a single image whose width stretches
  if (multiplier > 0) {
    var widthAttr   = document.createAttribute("width");
    widthAttr.value = multiplier * pcnt;
    imgElem.setAttributeNode(widthAttr);

    // In Firefox we need to explicitly set the height as well or it appears 
    // as 10 times greater than whatever we set the width to!!
    var img          = new Image();
    img.src          = imgSrc;
    var heightAttr   = document.createAttribute("height");
    heightAttr.value = img.height;
    imgElem.setAttributeNode(heightAttr);
  }
  
  // replace 1st (and only) table in the progressBarHolder div
  var pbarHolder = document.getElementById("progressBarHolder");
  pbarHolder.appendChild(imgElem);
}