/* miniHustle v0.1

   This script contains AJAX functions which can be used on any site/store.

   ~Michael@CommerceV3 */

// Create a new XMLHttpRequest object to talk to the Web server

// Initialize
var xmlHttp = false;

// Begin IE Code
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
  xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
  try {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (e2) {
    xmlHttp = false;
  }
}
@end @*/
// End IE Code

if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
  // Mozilla and every other sane browser :)
  xmlHttp = new XMLHttpRequest();
}

function callServer(params,type,store) {
  // Call Server using the following url:
  if(type == 'getShipCost') {
    var url = "/services/ajax/shipCost.php";
  } else if (type == 'getNewShipCost') {
    var url = "/services/ajax/shipCalculator.php";
  }
  url += params;
  // open connection.  usage: xmlHttp.open(METHOD,URL,ASYNC)
  xmlHttp.open("GET", url, true);
  // call a function when onreadystatechange updates
  xmlHttp.onreadystatechange = updatePage;
  // must send *something*, so send null
  xmlHttp.send(null);
}

function updatePage() {
  var response = '';
  if (xmlHttp.readyState == 4) {
    // if readState == 4 (page is complete), get responseText
    response = xmlHttp.responseText;
  }
  if(response != '') {
    showShipCost(response);    
  }
}

/* End AJAX Functions */

/* Begin Site Functions */

function getShipType(type_name) {
  var type = 'r';
  var type_obj = document.getElementById(type_name+'c');
  if (type_obj && type_obj.checked) {
    type = 'c';
  }
  return type;
}

function getNewShipCost(zip,country,method,type_obj,store) {
  var type = getShipType(type_obj);
  if ((zip == '' && country == 'United States') || country == '') {
    alert('Please enter your zip code (US only) and country to continue.');
    return false;
  } else if (method == '') {
    alert('Please select a shipping method before continuing.');
    return false;
  }
  var sendString = '?zip='+zip+'&country='+country+'&method='+method+'&store='+store+'&type='+type;
  // Check for an argument at key 4.  This argument is the recipient name for multiple ship-tos
  if (arguments[5] != '') {
    sendString += '&recip='+arguments[5];
  }
  callServer(sendString,'getNewShipCost',store);
}

function getShipCost(store, skus, prices, qtys, weights, tqty, zip, country, state, methods) {
  if((zip == '' || zip.length != '5') && country == "United States") {
    alert('US residents must enter a 5-digit zip code to more accurately estimate shipping costs.');
    unloadBar('processPanel');
    document.getElementById('calcButton').disabled = false;
    document.getElementById('calcButton').value = 'Re-calculate Shipping';
    return false;
  } else if(state == '' && country == 'United States') {
    alert('US residents must select a ship-to state to more accurately estimate shipping costs.');
    unloadBar('processPanel');
    document.getElementById('calcButton').disabled = false;
    document.getElementById('calcButton').value = 'Re-calculate Shipping';
    return false;
  }
  document.getElementById('errorMessage').innerHTML = '&nbsp;';
  var sendString = '?askus='+skus.substr(0,skus.length-1)+'&aprices='+prices.substr(0,prices.length-1);
  sendString += '&aqtys='+qtys.substr(0,qtys.length-1)+'&aweights='+weights.substr(0,weights.length-1);
  sendString += '&szips='+zip+'&scountries='+country.replace(' ','+')+'&sstates='+state+'&smethods='+methods.replace(' ','+');
  sendString += '&sgrps='+tqty+'&scities=&sprices=&tprice=&tship=&store='+store;

  callServer(sendString,'getShipCost',store);
  return false; // Always return something, return false
}

function showShipCost(response) {
  if (!response.match(/^NEWESTIMATOR/) && !response.match(/^Error/)) {
    unloadBar('processPanel');
    document.getElementById('resultsPanel').style.display = 'block';
    document.getElementById('resultsPanel').innerHTML = response;
  } else if (response.match(/^NEWESTIMATOR/)) {
    response = response.replace('NEWESTIMATOR','');
    populateFields(response);
  } else if (response.match(/^Error/)) {
    alert(response);
  }
}

// Populate Fields: Populates the estimator fields based on res
/*******************************************************************************
 * Function:  populateFields()
 * Author:    Michael@CommerceV3
 * Variables: res = pipe and newline delimited string of results from callServer
 * Purpose:   
 *******************************************************************************/
function populateFields(res) {
  // Make this an array instead of a flat string
  res = formatResults(res);

  for (var i=0,n=res.length;i<n;i++) {
    /*
       res[i][0] will either be 'shipto' or 'totals'
       res[i][1] is either the ship num (-1) or the promo deduction depending on the item at res[i][0]
       res[i][2] is the ship total or order total depending on res[i][0]
       res[i][3] is the total before promo deductions if res[i][0] is 'shipto' or the order tax total if res[i][0] is 'totals'
       res[i][4] is the tax total if res[i][0] is 'shipto' or the recipient if res[i][0] is 'totals'
       res[i][5] is the recipient if res[i][0] is 'shipto', no value if res[i][0] is 'totals'
       res[i][6] is the ship method if and only if res[i][0] is 'shipto'.
    */
    if (res[i][0] == 'shipto') {
      var id = (res[i][5] != '') ? '_'+res[i][5] : '';
      if (document.getElementById('method'+id).value != res[i][6]) {
        alert('Your shipping method has been changed to '+res[i][6]);
      }
      document.getElementById('method_label'+id).innerHTML = res[i][6] + ' ';
      document.getElementById('method_cost'+id).innerHTML = '$' + res[i][2];
      var shipTotal = res[i][2];
    }
    if (res[i][0] == 'totals') {
      var id = (res[i][4] != '') ? '_'+res[i][4] : '';
      document.getElementById('total_cost'+id).innerHTML = '$' + res[i][2];
      if (shipTotal == '0.00' && res[i][5] > 0) {
        document.getElementById('method_cost'+id).innerHTML = '$' + res[i][5];
      }
      if (res[i][1] > 0 && res[i][1] != '' && res[i][4] == '') {
        document.getElementById('promo').innerHTML = 'Promo Deduction:';
        document.getElementById('promo_price').innerHTML = '- $' + res[i][1];
      }
    }
  }
}

/************************************************************************************
 * Function:  formatResults()
 * Author:    Michael@CommerceV3
 * Variables: res = pipe and newline delimited string of results from populateFields
 * Purpose:   Format res for easier use
 ************************************************************************************/
function formatResults(res) {
  tmp = res.split("\n"); // split on newline first
  var nRes = new Array();
  for (var i=0,n=tmp.length;i<n;i++) {
    var ar = tmp[i].split("\|");
    nRes[i] = ar;
  }
  return nRes;
}

/************************[ Begin Progress Bar ]***************************************/
// Note: It doesn't matter how you style your progress bar as long as it consists of
// 2 elements: the bar and the fluid.  They must be nested (fluid inside the bar).
// Initialize barStop.  This controls whether the bar moves or not.  It's important.
var barStop = false;

/*******************************************************************************
 * Function:  initBar()
 * Author:    Michael@CommerceV3
 * Variables: bar   = str, ID of the bar containing the fluid.
 *            fluid = str, ID of the fluid.
 *            panel = str, ID of the panel containing the bar
 * Purpose:   Initilize the progress bar, get it running.
 * Note:      barStop is used in the global scope and is always used/checked
 *            by the progress bar to see if it should continue.
 *******************************************************************************/
function initBar(bar,fluid,panel) {
  // Set barStop to false if it's true
  if (barStop) {
    barStop = false;
  }
  // Set the display of the panel to block
  document.getElementById(panel).style.display = 'block';
  // Call barFill() function with an intial 0% fill and + as our oper
  // See barFill() function for variable definitions
  barFill(bar,fluid,0,'+');
}

/*******************************************************************************
 * Function:  unloadBar()
 * Author:    Michael@CommerceV3
 * Variables: panel = str, ID of the panel containing the bar
 * Purpose:   Unload the progress bar, stop it.
 * Note:      barStop is used in the global scope and is always used/checked
 *            by the progress bar to see if it should continue.
 *******************************************************************************/
function unloadBar(panel) {
  // Set barStop to true if it's false
  if (!barStop) {
    barStop = true;
  }
  // Set the display of the panel to none to hide it
  document.getElementById(panel).style.display = 'none';
}

/*******************************************************************************
 * Function:  barFill()
 * Author:    Michael@CommerceV3
 * Variables: bar   = str, ID of the bar containing the fluid.
 *            fluid = str, ID of the fluid.
 *            fill  = int, Percentage of fluid filling the bar (no '%' sign).
 *            oper  = str, + or - depending on whether the bar is filling or
 *                    being emptied.
 * Purpose:   To fill and empty the progress bar and give people something
 *            to watch while waiting on their results.
 * Note:      barStop is used in the global scope and is always used/checked
 *            by the progress bar to see if it should continue.
 * Further:   This function is called both by itself and initBar().  It doesn't
 *            EVER need to be invoked separately.
 *******************************************************************************/
function barFill(bar,fluid,fill,oper) {
  // Initialize timeOut variable. This controls the speed of fill.
  var timeOut = 50;
  // Initialize fillAmt variable. Percentage of fill for each barFill() call.
  var fillAmt = 5;
  // Check if barStop is set to true, if so, exit the function immediately.
  if (barStop) { return false; }
  // Initialize theFluid and theBar based on the id's passed by 'bar' and 'fluid'
  var theFluid = document.getElementById(fluid);
  var theBar = document.getElementById(bar);
  // Get the current fill level of the bar
  fill = (oper == '+') ? parseInt(parseInt(fill)+parseInt(fillAmt)) : parseInt(parseInt(fill)-parseInt(fillAmt));
  // Set fluid's width to fill%
  theFluid.style.width = fill+'%';
  // Change alignment based on oper.  If oper is '+', align left. If '-', align right.
  theBar.style.textAlign = (oper == '+') ? 'left' : 'right';
  theFluid.style.cssFloat = (oper == '+') ? 'left' : 'right';
  // Determine if the oper needs to change and call the appropriate function.
  if (fill == 100 && oper == '+') {
    setTimeout('barFill(\''+bar+'\',\''+fluid+'\','+fill+',\'-\')',timeOut);
  } else if (fill == 0 && oper == '-') {
    setTimeout('barFill(\''+bar+'\',\''+fluid+'\','+fill+',\'+\')',timeOut);
  } else {
    setTimeout('barFill(\''+bar+'\',\''+fluid+'\','+fill+',\''+oper+'\')',timeOut);
  }
}
/************************[ End Progress Bar ]***************************************/

