/*******************************************************************************
/* Calculations
/******************************************************************************/

function calculateTotal()
{
  var bSuccess = true;

  var oCostInput = null;
  var oQuantityInput = null;

  clearError();

  var fFlowerWholesaleTotal = 0.0;
  for (var i = 1; (oCostInput = document.getElementById('flowerCost' + i + 'Input')) != null; i++)
  {
    oQuantityInput = document.getElementById('flowerQuantity' + i + 'Input');
    if (oQuantityInput == null)
    {
      bSuccess = false;
      break;
    }

    trimTextInput(oQuantityInput);
    trimTextInput(oCostInput);

    var oCostStr = oCostInput.value.replace(/^\$/, '');

    if ((oQuantityInput.value.length < 1) && (oCostStr.length < 1))
      continue;

    var fQuantity = 0.0;
    var fCost = 0.0;

    if (bSuccess)
    {
      fQuantity = parseFloat(oQuantityInput.value);
      fCost = parseFloat(oCostStr);

      if (!isNaN(fCost))
        oCostInput.value = formatMoney(fCost);
    }

    if (bSuccess && (oQuantityInput.value.length < 1))
    {
      bSuccess = false;
      showError(null, new Array(oQuantityInput));
    }

    if (bSuccess && (oCostStr.length < 1))
    {
      bSuccess = false;
      showError(null, new Array(oCostInput));
    }

    if (bSuccess && isNaN(fQuantity))
    {
      bSuccess = false;
      showError("Please enter a valid quantity.", new Array(oQuantityInput));
    }

    if (bSuccess && isNaN(fCost))
    {
      bSuccess = false;
      showError("Please enter a valid cost.", new Array(oCostInput));
    }

    if (bSuccess)
      fFlowerWholesaleTotal += fQuantity * fCost;
  }

  var fHardgoodsWholesaleTotal = 0.0;
  for (var i = 1; (oCostInput = document.getElementById('hardgoodCost' + i + 'Input')) != null; i++)
  {
    oQuantityInput = document.getElementById('hardgoodQuantity' + i + 'Input');
    if (oQuantityInput == null)
    {
      bSuccess = false;
      break;
    }

    trimTextInput(oQuantityInput);
    trimTextInput(oCostInput);

    var oCostStr = oCostInput.value.replace(/^\$/, '');

    if ((oQuantityInput.value.length < 1) && (oCostStr.length < 1))
      continue;

    var fQuantity = 0.0;
    var fCost = 0.0;

    if (bSuccess)
    {
      fQuantity = parseFloat(oQuantityInput.value);
      fCost = parseFloat(oCostStr);

      if (!isNaN(fCost))
        oCostInput.value = formatMoney(fCost);
    }

    if (bSuccess && (oQuantityInput.value.length < 1))
    {
      bSuccess = false;
      showError(null, new Array(oQuantityInput));
    }

    if (bSuccess && (oCostStr.length < 1))
    {
      bSuccess = false;
      showError(null, new Array(oCostInput));
    }

    if (bSuccess && isNaN(fQuantity))
    {
      bSuccess = false;
      showError("Please enter a valid quantity.", new Array(oQuantityInput));
    }

    if (bSuccess && isNaN(fCost))
    {
      bSuccess = false;
      showError("Please enter a valid cost.", new Array(oCostInput));
    }

    if (bSuccess)
      fHardgoodsWholesaleTotal += fQuantity * fCost;
  }

  var fRetailTotal = 0.0;
  if (bSuccess)
  {
    var fFlowerMarkup = 0.0;
    if (fFlowerWholesaleTotal != 0.0)
    {
      var oFlowerMarkupInput = document.getElementById('flowerMarkupInput');
      trimTextInput(oFlowerMarkupInput);

      if (oFlowerMarkupInput.value.length < 1)
      {
        bSuccess = false;
        showError(null, new Array(oFlowerMarkupInput));
      }

      if (bSuccess)
        fFlowerMarkup = parseFloat(oFlowerMarkupInput.value);

      if (bSuccess && isNaN(fFlowerMarkup))
      {
        bSuccess = false;
        showError("Please enter a valid markup rate for flowers.", new Array(oFlowerMarkupInput));
      }
    }

    var fHardgoodsMarkup = 0.0;
    if (fHardgoodsWholesaleTotal != 0.0)
    {
      var oHardgoodsMarkupInput = document.getElementById('hardgoodsMarkupInput');
      trimTextInput(oHardgoodsMarkupInput);

      if (oHardgoodsMarkupInput.value.length < 1)
      {
        bSuccess = false;
        showError(null, new Array(oHardgoodsMarkupInput));
      }

      if (bSuccess)
        fHardgoodsMarkup = parseFloat(oHardgoodsMarkupInput.value);

      if (bSuccess && isNaN(fHardgoodsMarkup))
      {
        bSuccess = false;
        showError("Please enter a valid markup rate for hardgoods.", new Array(oHardgoodsMarkupInput));
      }
    }

    if (bSuccess)
      fRetailTotal = fFlowerWholesaleTotal * fFlowerMarkup + fHardgoodsWholesaleTotal * fHardgoodsMarkup;
  }

  var fTotal = 0.0;
  if (bSuccess)
  {
    if (fRetailTotal == 0.0)
      fLaborChargePercentage = 0.0;
    else
    {
      var oLaborChargeInput = document.getElementById('laborChargeInput');
      trimTextInput(oLaborChargeInput);

      var sLaborChargeStr = oLaborChargeInput.value.replace(/%$/, '');

      if (sLaborChargeStr.length < 1)
      {
        bSuccess = false;
        showError(null, new Array(oLaborChargeInput));
      }

      var fLaborChargePercentage = 0.0;

      if (bSuccess)
        fLaborChargePercentage = parseFloat(sLaborChargeStr);

      if (isNaN(fLaborChargePercentage))
      {
        bSuccess = false;
        showError("Please enter a valid labor charge percentage.", new Array(oLaborChargeInput));
      }
    }

    if (bSuccess)
      fTotal = fRetailTotal * (1.0 + fLaborChargePercentage / 100.0);
  }

  var oSellPriceSpan = document.getElementById('sellPriceSpan');
  if (bSuccess)
  {
    oSellPriceSpan.innerHTML = formatMoney(fTotal);
  }
  else
  {
    oSellPriceSpan.innerHTML = '';
  }
}

/*******************************************************************************
/* Arrays
/******************************************************************************/

function indexOf(aArray, element)
{
  for (var i = 0; i < aArray.length; i++)
    if (aArray[i] == element)
      return i;
  return -1;
}

/*******************************************************************************
/* Text Formatting
/******************************************************************************/

function formatMoney(fAmount)
{
  if (isNaN(fAmount))
    return '';
  return '$' + fAmount.toFixed(2);
}

function trim(sX)
{
  return sX.replace(/^\s+|\s+$/g, '');
}

function trimTextInput(oInput)
{
  oInput.value = trim(oInput.value);
}

/*******************************************************************************
/* Input Event Handlers
/******************************************************************************/

function filterInput(filterType, evt, allowDecimal, allowCustom)
{
  var keyCode, Char, inputField, filter = '';
  var alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var num   = '0123456789';
  // Get the Key Code of the Key pressed if possible else - allow
  if(window.event){
      keyCode = window.event.keyCode;
      evt = window.event;
  }else if (evt)keyCode = evt.which;
  else return true;
  // Setup the allowed Character Set
  if(filterType == 0) filter = alpha;
  else if(filterType == 1) filter = num;
  else if(filterType == 2) filter = alpha + num;
  if(allowCustom)filter += allowCustom;
  if(filter == '')return true;
  // Get the Element that triggered the Event
  inputField = evt.srcElement ? evt.srcElement : evt.target || evt.currentTarget;
  // If the Key Pressed is a CTRL key like Esc, Enter etc - allow
  if((keyCode==null) || (keyCode==0) || (keyCode==8) || (keyCode==9) || (keyCode==13) || (keyCode==27) )return true;
  // Get the Pressed Character
  Char = String.fromCharCode(keyCode);
  // If the Character is a number - allow
  if((filter.indexOf(Char) > -1)) return true;
  // Else if Decimal Point is allowed and the Character is '.' - allow
  else if(filterType == 1 && allowDecimal && (Char == '.') && inputField.value.indexOf('.') == -1)return true;
  else return false;
}

function selectAll(oTextInput)
{
  oTextInput.focus();
  oTextInput.select();
}

/*******************************************************************************
/* Error Handling
/******************************************************************************/

var sHighlightedElementClass = 'required';
var oHighlightedElementRegex = new RegExp('(^| )' + sHighlightedElementClass + '(?=( |$))', 'i');

function clearError()
{
  showError();
}

function getAssociatedLabels(oElement)
{
  var aResult = new Array();
  var aLabels = document.getElementsByTagName('label');
  for (var i = 0; i < aLabels.length; i++)
  {
    var oLabel = aLabels[i];
    if (oLabel && oLabel.htmlFor == oElement.id)
      aResult.push(oLabel);
  }
  return aResult;
}

function highlightElementLabels(oElement, bHighlighted)
{
  var aLabels = getAssociatedLabels(oElement);
  for (var i = 0; i < aLabels.length; i++)
    highlightElement(aLabels[i], bHighlighted);
}

function highlightElement(oElement, bHighlighted)
{
  if (bHighlighted)
  {
    if (oElement.className)
    {
      if (!oHighlightedElementRegex.test(oElement.className))
        oElement.className += ((oElement.className.length > 0) ? ' ' : '') + sHighlightedElementClass;
    }
    else
      oLabel.className = sHighlightedElementClass;
  }
  else
  {
    if (oElement.className)
        oElement.className = oElement.className.replace(oHighlightedElementRegex, '');
  }
}

function showError(sErrorMessage, aHighlightControls)
{
  var oErrorMessageDiv = document.getElementById('errorMessageDiv');
  if (sErrorMessage)
  {
    oErrorMessageDiv.innerHTML = sErrorMessage;
    oErrorMessageDiv.style.visibility = 'visible';
  }
  else
  {
    oErrorMessageDiv.innerHTML = '';
    oErrorMessageDiv.style.visibility = 'hidden';
  }

  if (!aHighlightControls)
    aHighlightControls = new Array();

  var aInputs = document.getElementsByTagName('input');
  for (var i = 0; i < aInputs.length; i++)
  {
    var oInput = aInputs[i];
    if (indexOf(aHighlightControls, oInput) >= 0)
    {
      highlightElementLabels(oInput, true);
      highlightElement(oInput, true);
      selectAll(oInput);
    }
    else
    {
      highlightElementLabels(oInput, false);
      highlightElement(oInput, false);
    }
  }
}
