﻿//------------------------------------------------------------------------------
// ASP.NET application: support.metaswitch.com/customerportal
//
// Client-side JavaScript file: customerportal.js
// Common utility functions
//------------------------------------------------------------------------------

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

//Note that this operates on a jQuery object
function enableElement($ele) {
  $ele.removeAttr("disabled");
  $ele.removeClass("disabled");
}

//Note that this operates on a jQuery object
function disableElement($ele, bClearValue) {
  $ele.attr("disabled", "disabled");
  $ele.addClass("disabled");
  if (bClearValue) $ele.val("");
}

//------------------------------------------------------------------------------
// updateTestPlanElementStatus - call webservice to update status field in
// salesforce object corresponding to this select element in the test plan.
// returns true/false whether we were able to issue the update call.
// call returns asynchronously.
//------------------------------------------------------------------------------
function updateTestPlanElementStatus(selTestPlanElement, strType, strObjId)
{
  var strValue;
  var strObjId;
  var bSuccess;
  
  bSuccess = false;
 
  if (selTestPlanElement.selectedIndex >= 0)
  {
    strValue = selTestPlanElement.options[selTestPlanElement.selectedIndex].value;
    bSuccess = true;
  }
  else
  {
    bSuccess = false;
  }
  
  if (bSuccess)
  {
    // Call script service.  
    // This is asynchronous, so we have to pass function handlers
    SalesforceUpdate.UpdateTestPlanElementStatus(strObjId,
                                                 strValue, 
                                                 strType,
                      updateTestPlanElementStatusComplete, 
                      updateTestPlanElementStatusError);
  }
   
  return bSuccess;
}

//------------------------------------------------------------------------------
// updateTestPlanElementStatusComplete
// no action required
//------------------------------------------------------------------------------
function updateTestPlanElementStatusComplete(strXmlResponse) 
{
}

//------------------------------------------------------------------------------
// updateTestPlanElementStatusError
// alert the user
//------------------------------------------------------------------------------
function updateTestPlanElementStatusError(arg)
{
  alert("Error trying to update test plan status!  Please refresh the "
        + "page and try again.  If the error persists please contact your "
        + "Metaswitch representative, and provide the following detailed "
        + "error message: " + arg.get_message());
}

//------------------------------------------------------------------------------
// CSD Portal login page may try to re-post login information to 
// NPD portal or iagdocs
//------------------------------------------------------------------------------
var strRedirectUrl;

function tryRemoteLogin(strControlPrefix, strLoginUrl, strHomeUrl)
{
  var frmForm = document.getElementsByName('aspnetForm')[0];
  var txtUsername = document.getElementById(strControlPrefix + 'txtUsername');
  var hidPassword = document.getElementById(strControlPrefix + 'hidPassword');
  
  if ((txtUsername.value != '') && (hidPassword.value != ''))
  {
    jQuery.post(strLoginUrl, 
                {
                  username: txtUsername.value, 
                  userpassword: hidPassword.value
                },
                remoteLoginPostComplete);
                
    strRedirectUrl = strHomeUrl;
  }
}

function remoteLoginPostComplete(strResponse, textStatus)
{
  if (strRedirectUrl != '')
  {
    location.href = strRedirectUrl;
  }
  else
  {
    document.write(strResponse);
  }
}

//Functions for forecast.aspx

function validateForecastingGrid()
{  
  jQuery('input#forecast_is_valid').val(true);  
  for (var i=PAST_PERIOD_LENGTH+3;i<=PAST_PERIOD_LENGTH+3 + REQUIRED_FORECAST_LENGTH - 1;i++)
  {
    jQuery('tr.period_row').filter(':nth-child(' + i.toString() + ')')
      .find('input.forecast_input').each(function() {
      var curr_val = jQuery(this).val();    
      if (trim(curr_val) == "" || isNaN(curr_val)) jQuery('input#forecast_is_valid').val(false);    
    });
  }  
  if (jQuery('input#forecast_is_valid').val() == "true") {
    jQuery('div#forecast_valid_message p').text("The forecast on this page contains enough data to place orders.").removeClass("error");
    if (trim(jQuery('input#forecast_has_changed').val()) != "true") enableElement(jQuery('input#' + BTN_ORDER_FORM_ID));
  } else {
    jQuery('div#forecast_valid_message p').text("The forecast on this page does not contain enough data to place orders.").addClass("error");    
    disableElement(jQuery('input#' + BTN_ORDER_FORM_ID), false);
  }  
}

function setupForecastingGrid()
{
  disableElement(jQuery('input#' + BTN_SAVE_ID), false);
  disableElement(jQuery('input#' + BTN_CANCEL_ID), false);
  if (trim(jQuery('input#forecast_has_changed').val()) == "true") {
    jQuery('div#forecast_changed_message').show();
    enableElement(jQuery('input#' + BTN_SAVE_ID));
    enableElement(jQuery('input#' + BTN_CANCEL_ID));
    disableElement(jQuery('input#' + BTN_ORDER_FORM_ID), false);
  } else {
    jQuery('div#forecast_changed_message').hide();
    disableElement(jQuery('input#' + BTN_SAVE_ID), false);
    disableElement(jQuery('input#' + BTN_CANCEL_ID), false);
    enableElement(jQuery('input#' + BTN_ORDER_FORM_ID));
  }
  jQuery('input.forecast_input').each(function() {
    var $input = jQuery(this);
    if ((user_ecp_id == 0) || (updates_permitted != "True") || (trim($input.parent().next().html()) != '') ||
        $input.parent().parent().hasClass('current_month') || 
        $input.parent().parent().hasClass('next_month')) {      
      disableElement($input, false);
      if (trim($input.val()) == '' && ($input.parent().parent().hasClass('current_month') || 
         $input.parent().parent().hasClass('next_month'))) {
         $input.val("0");
      }
    }
    else {
      $input.blur(function() {
        validateForecastingGrid();
      }).change(function() {
        jQuery('div#forecast_changed_message').show();
        enableElement(jQuery('input#' + BTN_SAVE_ID));
        enableElement(jQuery('input#' + BTN_CANCEL_ID));
        disableElement(jQuery('input#' + BTN_ORDER_FORM_ID), false);
        jQuery('input#forecast_has_changed').val(true);
      });
    }
  });  
}

function calculateOrderValuesInRow($period_row)
{ 
  var per_seat_cost = parseInt($period_row.find('input.order_per_seat_cost').val());
  var prev_ordered = parseInt($period_row.find('td.order_prev').html());
  var seats_required = parseInt($period_row.find('input.forecast_input').val());  
  $period_row.find('td.order_diff').html(seats_required - prev_ordered);
  $period_row.find('td.order_cost_diff').html((seats_required - prev_ordered) * per_seat_cost);
  $period_row.find('td.order_cost_total').html(seats_required * per_seat_cost);
}

function calculateMonthlyTotals()
{
  jQuery('table#orders_by_month tr.monthly_total_row').each(function() {
    var row_total = 0;
    var row_diff = 0;
    var $this_row = jQuery(this);    
    var index = $this_row.parent().children().index($this_row);
    jQuery('table.orders_by_service_level').each(function () {
      var $source_row_in_table = jQuery(this).find('tr.period_row:eq(' + (index - 1).toString() + ')');
      row_diff += parseInt($source_row_in_table.children('td.order_cost_diff').html());
      row_total += parseInt($source_row_in_table.children('td.order_cost_total').html());
    });    
    $this_row.find('td.monthly_diff_cell').html(row_diff);
    $this_row.find('td.monthly_total_cell').html(row_total);    
  });
}

function setupOrderForm()
{ 
  jQuery('input.forecast_input').each(function() {
    var $input = jQuery(this);    
    if (trim($input.val()) == '' && ($input.parent().parent().hasClass('current_month_nocolour') || 
        $input.parent().parent().hasClass('next_month_nocolour'))) {
      $input.val("0");
      disableElement($input, false);      
    }
  });
  jQuery('table.orders_by_service_level tr.period_row').each(function() {
    calculateOrderValuesInRow(jQuery(this));
    jQuery(this).find('input.forecast_input').change(function() {
      calculateOrderValuesInRow(jQuery(this).parent().parent());
      calculateMonthlyTotals();
    });
  });  
  calculateMonthlyTotals();
}

function setupValidation(bForecastsRequired)
{
  jQuery('#aspnetForm').validate({
    errorContainer: "#errorBox",
    errorLabelContainer: "#errorBox",
    wrapper: "p class='error'"
  });
  jQuery.validator.addMethod('minforecast', function(value) {
    return (trim(value) == '') || (parseFloat(value) == 0) || (parseFloat(value) >= 20);
  }, 'Forecast has to be a minimum of 20');
  jQuery.validator.addMethod('min_value', function(value, element) {
    var $hidden_minimum = jQuery(element).next('.forecast_input_minimum');
    if ($hidden_minimum.length) {
      var minval = $hidden_minimum.val();
      return (isNaN(value) || isNaN(minval) || value >= minval);
    } else {
      return true;
    }
  }, 'You cannot reduce your order for the current month');
  jQuery("input.forecast_input").each(function(){
    jQuery(this).rules("add", { digits: true, minforecast:true });
    if (jQuery(this).hasClass("has_min_value")) jQuery(this).rules("add", { min_value: true });
    if (bForecastsRequired) jQuery(this).rules("add", { required: true });    
  });
}

function doForecastStartOfDay()
{  
  if ((user_ecp_id == 0) || (updates_permitted != "True")) {
    jQuery('div#forecast_not_updateable').show();
  }
  setupForecastingGrid();
  validateForecastingGrid();
  setupValidation(false);
}

function doOrderStartOfDay()
{
  setupOrderForm();
  setupValidation(true);
}