/* 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;
var response = '';

// 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 queryServer(params,type) {
  // Call Server using the following url:
  var url = "/services/avshopcom/shipCost.php";
  if(type == 'getShipCost') {
    url += params;
  }
  if (arguments[2] >= '0') {
    url += '&s_page='+arguments[2];
  }
  // open connection.  usage: xmlHttp.open(METHOD,URL,ASYNC)
  xmlHttp.open("GET", url, true);
  // call a function when onreadystatechange updates
  if (arguments[2] >= '0') {
    xmlHttp.onreadystatechange = updateShipPage;
  } else {
    xmlHttp.onreadystatechange = updatePage;
  }
  // must send *something*, so send null
  xmlHttp.send(null);
}

function updatePage() {
  if (xmlHttp.readyState == 4) {
    // if readyState == 4 (page is complete), get responseText
    response = xmlHttp.responseText;
    showShipCost(response);
  }
}

function updateShipPage() {
  if (xmlHttp.readyState == 4) {
    response = xmlHttp.responseText;
    if(response != '') {
      showPrice(response);
    }
  }
}

/* End AJAX Functions */

/* Begin Site Functions */
function getShipCost(skus, prices, qtys, weights, tqty, zip, country, method) {
  if((zip == '' || zip.length != '5') && country == "United States") {
    alert('US residents must enter a 5-digit zip code to more accurately estimate shipping.');
    document.getElementById('calcButton').disabled = false;
    document.getElementById('calcButton').value = 'Re-calculate Shipping';
    return false;
  }
  document.getElementById('errorMessage').innerHTML = '&nbsp;';
  var method = method.replace(' ','+').replace('& ','').replace(',','');
  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(' ','+')+'&smeths='+method;
  sendString += '&sgrps='+tqty+'&scities=&sprices=&tprice=&tship=';
  if (arguments[8] >= '0') {
    queryServer(sendString,'getShipCost',arguments[8]);
  } else {
    queryServer(sendString,'getShipCost');
  }
}

function showShipCost(response) {
  if(response != '') {
    var items = response.split('::'), price = items[0], msg = items[1];
    if(price >= 0) {
      if(price == 0) {
        price = '0.00';
      }
      var splitPrice = price.toString().split('.');
      if(splitPrice[1].length < 2) {
        price = splitPrice.join('.')+'0';
      }
      var cartPrice = parseFloat(document.getElementById('cartTotal').innerHTML);
      var totalPrice = parseFloat(price) + parseFloat(cartPrice);
      splitPrice = totalPrice.toString().split('.');
      if(typeof splitPrice[1] != 'undefined' && splitPrice[1].length < 2) {
        totalPrice = splitPrice.join('.')+'0';
      } else if(typeof splitPrice[1] != 'undefined' && splitPrice[1].length > 2) { // Apparently 14.97 + 3.59 = 18.560000000000002 according to javascript, fix it
        splitPrice[1] = splitPrice[1].substr(0,2);
        totalPrice = splitPrice.join('.');
      }
      document.getElementById('shipCost').innerHTML = 'Estimated Shipping Cost: $'+price;
      document.getElementById('totalCost').innerHTML = 'Estimated Total Cost: $'+totalPrice;
    }
    if(msg != '') {
      document.getElementById('errorMessage').innerHTML = msg;
      var items = msg.split(' to ');
      items = items[1].split(' due');
      var newMeth = items[0];
      document.getElementById('method').value = newMeth;
    }
  } else {
    alert('Error: No response from service.\n\nIf this error continues please contact our customer service.');
  }
  document.getElementById('calcButton').disabled = false;
  document.getElementById('calcButton').value = 'Re-calculate Shipping';
}

function showPrice(response) {
  if (response != '') {
    var items = response.split('::'), price = items[0], msg = items[1], id = items[2];
    document.getElementById('mPrice'+id).innerHTML = '- $'+price;
  }
}
