// $Id: product.js,v 1.2 2008/03/09 01:02:29 andy Exp $
var prod_descr = new Object;
var prod_data = new Object();
var prod_keymap = new Object();
var prod_option = new Object();
var prod_option_price = new Object();
var prod_option_func = new Object();
var prod_shipping = new Object();
var prod_stockcode = new Object();
var prod_location = new Object();

var options = {};
options['batt'] = 'Battery';
options['cell'] = '#cell';
options['chan'] = 'Channel';
options['colour'] = 'Colour';
options['conn'] = 'Connector';
options['decoder'] = 'Decoder';
options['freq'] = 'Frequency';
options['KV'] = 'RPM/Volt (Kv)';
options['len'] = 'Length';
options['model'] = 'Model Type';
options['motor'] = 'Motor';
options['mount'] = 'Mount Type';
options['pack'] = 'Pack';
options['ratio'] = 'Ratio';
options['shaft'] = 'Shaft Type';
options['size'] = 'Size';
options['tagSel'] = '->';
options['type'] = 'Type';
options['receiver'] = 'Receiver';
options['servo'] = 'Servo';
options['lipo'] = 'LiPo';
options['esc'] = 'ESC';
options['wind'] = 'Wind';
options['option'] = '';     // a generic option

Object.keys = Object.keys || function(o) {  
  var result = [];  
  for(var name in o) {  
    if (o.hasOwnProperty(name))  
      result.push(name);  
  }  
  return result;  
};  

var debug = 0;
function AddProduct(id, option)
{
  if (window.event != null) window.event.returnValue = false;

//  if (location.hostname == 'micron.acronym.co.uk') {
//    var options = new Array();
//    for (var i=1; i<arguments.length; i++) {
//      options.push(arguments[i]);
//    }
//    shopping_cart(id, options);
//    return;
//  }

  var live_testing = false;
  var vat_separate = true;

  if (navigator.platform.substr(0, 5) === "Linux") {
    //debug = 1;
  
//live_testing = true;
//    if (window.navigator.javaEnabled() && "undefined" !== typeof java
//          && "undefined" !== typeof java.net) {
//      var hostname = java.net.InetAddress.getLocalHost().getHostName();
//      if (hostname === "andy-laptop") {
//        window.status = hostname;
//        live_testing = true;
//      }
//    }
  }

	var prodfrm = document.products;
	var frm = document.addproduct;
  if (debug) {
    var opts = Array.prototype.slice.call(arguments, 1);
    alert("AddProduct(" + id + ", " + opts.join(', ') + ")");
  }

  var micron_cart = false;
  if ((location.hostname == 'micron.acronym.co.uk'
        || location.hostname == 'localhost'
        || location.hostname.match(/127.0.0.1/))
      && false === live_testing) {

    var url = 'http://' + location.hostname + ':' + location.port +  '/cart.cgi';
    frm.action = url;
    frm.target = null;
    micron_cart = true;
  }

	// Clear any previous option data from the form
  frm.on0.value = frm.os0.value = '';

  var optionsList = new Array();
  var optionsCode = new Array();
  var optionsLoc = new Array();
  var optionsName = new Array();
  var quantity = new Array();

  var opSel = '';     // concatenated option selector
	if (option) {
    // Loop over all possible options
    for (var i=1; i<arguments.length; i++) {
      option = arguments[i];
      var optName = options[option];
      if ("undefined" === typeof optName || null === optName) {
        if (debug) alert("Unknown option '" + option + "', keys are: "
          + Object.keys(options).join(", "));
return;
        continue;
      }

      var ele = prodfrm.elements[id + '.' + option];
      if (null == ele) {
        if (debug) alert("No form element for option '" + option + "'");
        continue;
      }
      var optText, optValue;
      if (ele.type == 'select-one') {
        var index = ele.selectedIndex;
        if (null == index) {
          if (debug) alert("no selectedIndex");
          continue;
        }
        optText = ele.options[ele.selectedIndex].text;
        optValue = ele.options[ele.selectedIndex].value;
      }
      else if (ele.type === 'checkbox') {
        if (!ele.checked) continue;
        optText = ele.value; 
        var qe_name = ele.name + '_quantity';
        var qe = prodfrm.elements[qe_name];
        if (null != qe && !isNaN(parseInt(qe.value))) {
          quantity[ele.name] = parseInt(qe.value);
          optValue = 'x' + quantity[ele.name];
        }
        else {
          optValue = 'yes';
        }
      }
      if (debug) alert("option '" + option + "' optText '" + optText + "' optValue '" + optValue + "'");
      if (optValue == '' || optValue == 'x') {
        //alert("Please choose a value for " + options[option]);
        return;     // blank or 'x' means not available
      }
      var optValue_parts = optValue.split('::');
      var optCode, optLoc, optName;
      // parts = keystring::code::location::description
      if (optValue_parts.length > 1) {
        optValue = optValue_parts[0];
        optionsCode.push(optCode = optValue_parts[1]);
        optionsLoc.push(optLoc = optValue_parts[2] || '');
        optionsName.push(optName = optValue_parts[3] || '');
      }
      if (opSel != '') opSel += '.';
      opSel += optValue;

      var opt_name, micron_opt_name, item_quantity = 1;
      var po = prod_option[id];
      if (po == 'v') {
        opt_name = optValue;
        micron_opt_name = optValue;
      }
      else if (po == 'm') {
        if (ele.type == 'checkbox') {
          if (quantity[ele.name]) {
            opt_name = optValue;
            micron_opt_name = optName + '(' + optValue + ')';
            item_quantity = quantity[ele.name];
          }
          else {
            var key = option + ':1';
            opt_name = prod_keymap[id][key];
            micron_opt_name = optName;
          }
        }
        else {
          var key = option + ':' + optValue;
          opt_name = prod_keymap[id][key];
          micron_opt_name = opt_name;
        }
        if (debug) alert("prod_keymap[" + id + "][" + key + "] = '" + opt_name + "'");
      }
      else {
        opt_name = optText;
        micron_opt_name = opt_name;
      }
      if (debug) alert("po '" + po + "', opt_name '" + opt_name + "', opSel '" + opSel + "'");

      if (micron_cart) {
        if ("none" === opt_name) continue;
        if ("undefined" === typeof optCode) optCode = '';
        if ("undefined" === typeof optLoc) optLoc = '';
        optionsList.push(micron_opt_name + '//' + item_quantity + '//' + optName
          + '//' + optCode + '//' + optLoc);
      }
      else {
        var optLabel = options[option];
        optionsList.push(optLabel + '(' + opt_name + ')');
        //optionsList.push(optName + '(' + opt_name + ')');
      }
    }
  }
  if (debug) alert("id = '" + id + "', opSel = '" + opSel + "'");

  if (optionsList.length > 0) {
    frm.on0.value = 'Options';
    frm.os0.value = micron_cart
      ? optionsList.join('::')
      : optionsList.join(', ');
  }

	var data = prod_data[id];
	if (null == data)  {
    if (debug) alert("No product data for '" + id + "'");
		return;
	}
  // non-null entry in prod_option_price indicates that the price
  // is calculated so use it directly
  var amount;
  if (null != prod_option_price[id]) {
    amount = prod_data[id];
  }
  else {
	  if (null != opSel && null != data[opSel]) {
		  data = data[opSel];
	  }
    amount = data[0];
  }
  var name;
  if (null != prod_descr[id])
    name = prod_descr[id];
  else
    name = data[1];
  if (debug) alert(id + ", " + opSel + " = '" + name + "' at " + amount);
  if (null == amount || amount < 0) {
    if (debug) alert("amount is null");
    return;
  }
  if (amount == 0) {
    return;
  }

  var stock_code = '', stock_location = '';
  if (optionsCode.length == 1) {
    stock_code = optionsCode[0];
    stock_location = optionsLoc[0];
  }
  else if (prod_stockcode[id]) {
    stock_code = prod_stockcode[id];
    stock_location = prod_location[id];
  }
  if ("undefined" === typeof stock_code) stock_code = '';
  if ("undefined" === typeof stock_location) stock_location = '';
	frm.item_number.value = id + ' / ' + stock_code + ' / ' + stock_location;;
	frm.item_name.value = name;

  if (vat_separate) {
    var vat_multiplier = 1.2;
    var netvalue = Math.round(amount * 100 / vat_multiplier) / 100;
    var tax = amount - netvalue;
    tax = Math.round(tax * 100) / 100;
    frm.amount.value = netvalue;
    // don't add any tax, let PayPal calculate
    //frm.tax.value = tax;
    //frm.tax_rate.value = 20;
  }
  else {
	  frm.amount.value = amount;
  }

  var ship_ele = document.getElementsByName('shipping');
  if (null != prod_shipping[id]) {
    if (ship_ele.length > 0) {
      ship_ele[0].value = prod_shipping[id];
    }
    else {
      frm.innerHTML += '<input type="hidden" name="shipping" value="'
          + prod_shipping[id] + '">';
    }
    if (debug) alert('shipping ' +  prod_shipping[id]);
  }
  else {
    if (ship_ele.length > 0) {
      frm.removeChild(ship_ele[0]);
    }
  }
	frm.submit();
}
function update_price(frm, prod_tag, func)
{
  var prod_tag_prefix = prod_tag + '.';
  var ele = frm.elements[prod_tag + '.base_price'];
  if (null == ele) {
//      if (debug)
//        alert('update_price(' + prod_tag + ") no 'base_price' element");
    return;
  }
  var total_price = ele.value;
  total_price = parseFloat(total_price);
  var price_node = document.getElementById(prod_tag + '.price');
  if (null == price_node) return;
  var ele_array = new Array;
  var ele_array_idx = 0;
  var pop = prod_option_price[prod_tag];
  if (null == pop) {
    if (debug)
      alert('update_price(' + prod_tag
          + ") no 'prod_option_price' slot");
    return;
  }
  var selCount = 0;
  for (var i=0; i<frm.elements.length; i++) {
    var e = frm.elements[i];
    if (e.name.substr(0, prod_tag_prefix.length) == prod_tag_prefix) {
      var opt_name = e.name.substr(prod_tag.length+1);
      var pop = prod_option_price[prod_tag][opt_name];
      if (e.type == 'select-one') {
        if (e.name.match('_quantity')) continue;
        if (null == pop) {
          if (debug) {
            alert('update_price(' + prod_tag
              + ") no 'prod_option_price' for '" + opt_name + "'");
          }
          continue;
        }
        if ('x' == e.value) {    // 'x' means ignore this option
          // Find first valid selection
//alert("x found");
          for (var j=0; j<e.options.length; j++) {
            var optval = e.options[j].value;
            if (j == 0 && optval == '') {
              e.selectedIndex = 0;
              continue;
            }
            if (optval != '' && optval != 'x') {
//alert("set to " + j);
              e.selectedIndex = j;
              continue;
            }
          }
          // if all else fails set the select to the top
          e.selectedIndex = 0;
        }
        var si = e.selectedIndex;
        var oprice = pop[si];
        if (null == oprice) {
          if (debug)
            alert('update_price(' + prod_tag
                + ") no 'prod_option_price' for '" + opt_name
                + "' index " + si);
          continue;
        }
        total_price += parseFloat(oprice);
        ele_array[ele_array_idx++] = e;
        if (si > 0) {
          selCount++;
        }
      }
      else if (e.type == 'checkbox' && e.checked == true) {
        var price = parseFloat(pop);
        var qname = e.name + '_quantity';
        if (frm.elements[qname]) {
          var quantity = parseInt(frm.elements[qname].value);
          if (isNaN(quantity)) quantity = 1;
          price *= quantity;
        }
        total_price += price;
        selCount++;
      }
    }
  }
  //selected_option_count[prod_tag] = selCount;
  if (null != func) {
    total_price = func(ele_array, total_price);
  }
  if (isFinite(total_price)) {
    total_price = sprintf("%.2f", total_price);
    price_node.innerHTML = '&#163; ' + total_price;
    prod_data[prod_tag] = total_price;
  }
  else {
    price_node.innerHTML = total_price;
    prod_data[prod_tag] = -1;
  }
  var cnt_div = document.getElementById(prod_tag + '.option_count');
  if (null != cnt_div) {
    cnt_div.innerHTML = selCount;
  }
}

var exclusive_elements = new Object;
function exclusive(ele, prod_tag, is_exclusive)
{
  var frm = ele.form;
  var isSel = ele.type == 'select-one'
    ? ele.selectedIndex > 0 ? true : false
    : ele.checked ? true : false;
  for (var name in exclusive_elements) {
    if (name.substr(0, prod_tag.length) != prod_tag)
      continue;
    var e = frm.elements[name];
    if (null == e) continue;

    var sub_isSel = e.type == 'select-one'
      ? e.selectedIndex > 0 ? true : false
      : e.checked ? true : false;

//alert("name " + e.name + ", type " + e.type + ", isSel " + isSel + ", sub_isSel " + sub_isSel);
    if (is_exclusive && ele.name != name && isSel) {
      if (e.type == 'select-one') e.selectedIndex = 0;
      else                        e.checked = false;
    }
    else if (!is_exclusive && exclusive_elements[name] && sub_isSel) {
      if (e.type == 'select-one') e.selectedIndex = 0;
      else                        e.checked = false;
    }
  }
}

function deselect_options(prod_tag)
{
  var frm = document.forms['products'];

  for (var i=0; i<frm.elements.length; i++) {
      var e = frm.elements[i];
      if (e.name.substr(0, prod_tag.length) == prod_tag) {
          var opt_name = e.name.substr(prod_tag.length+1);
          if (e.type == 'select-one') {
            e.selectedIndex = 0;
          }
          else if (e.type == 'checkbox') {
            e.checked = false;
          }
      }
  }
  update_price(frm, prod_tag);
}

function shopping_cart(id, options)
{
alert(id + ", #args=" + options.length);
  for (var i=0; i<options.length; i++) {
    option = options[i];
alert("option " + option);
  }
  callAjax('/cart.cgi?add=1', update_cart_display);
}

function RightClickMenu(ev)
{
//  ev ||= window.event;
  var btn = ev.target || ev.srcElement;
  if (ev.stopPropagation) ev.stopPropagation();
  if (ev.preventDefault) ev.preventDefault();
  //var popup = document.getElementById('right_click_menu');
  var anchor = document.getElementById('right_click_anchor');
  var code = btn.id.substr(11);
  var option_keys = new Object;
  for (var key in prod_keymap[code]) {
    var parts = key.split(':');
    option_keys[parts[0]] = 1;
  }
  var option_keyset = keys(option_keys);
  var pname, stock_code, stock_location;
  if (option_keyset.length == 0) {
    pname = prod_descr[code];
    stock_code = prod_stockcode[code];
    stock_location = prod_location[code];
  }
  else if (option_keyset.length == 1) {
    var key0 = option_keyset[0];
    var parts = btn.form.elements[code + '.' + key0].value.split('::');
    var option_code = parts[1];
    if (null != option_code) {
      pname = prod_descr[code] + ':' + prod_keymap[code][key0 + ':' + parts[0]];
      stock_code = code = option_code;
      stock_location = parts[2];
    }
  }
  anchor.href = top_dir + 'admin_product.cgi?code=' + (stock_code || code);
  var pname_span = document.getElementById('right_click_product_name');
  if (pname_span) {
    pname_span.innerHTML = pname != null ? pname : 'Product Info';
  }
  the_div = document.getElementById('right_click_menu');
  the_div.style.width = '200px';
  info_span = document.getElementById('right_click_info');
  info_span.innerHTML = '<br />' + stock_code
    ? '<br />Stock Code: ' + stock_code
    : '';
  info_span.innerHTML += '<br />' + stock_location
    ? '<br />Location: ' + stock_location
    : '';
  popup(btn, 'right_click_menu', true);
}

function keys(o)
{
  var accumulator = [];
  for (var propertyName in o) {
    accumulator.push(propertyName);
  }
  return accumulator;
}

function AddContentEvent()
{
  var input_ele = document.getElementsByTagName('input');
  var btn_count = 0;
  for (var i=0; i<input_ele.length; i++) {
    var e = input_ele[i];
    if (e.id == null || e.id.substr(0, 10) != 'CartButton') continue;
    e.oncontextmenu = RightClickMenu;
    btn_count++;
  }
}
OnLoadFunctions.push(AddContentEvent);

// vi:ts=2 sw=2 expandtab

