/* vim: set ts=2 sw=2 sts=2 et: */
/**
 * Functions for product options module
 * 
 * @category   X-Cart
 * @package    X-Cart
 * @subpackage JS Library
 * @author     Ruslan R. Fazlyev <rrf@x-cart.com> 
 * @version    $Id: func.js,v 1.2.2.1 2010/12/08 14:44:45 ferz Exp $
 * @link       http://www.x-cart.com/
 * @see        ____file_see____
 */

/**
 * Rebuild page if some options is changed
 */
function check_options(itemid) {
	var product_thumbnail = document.getElementById('product_thumbnail' + itemid);
	var availObj = document.getElementById('product_avail' + itemid);
  var local_taxes = [];
  var is_rebuild_wholesale = false;
  var variantid = false;

  if (typeof(taxes[itemid]) != 'undefined') {
    for (var t in taxes[itemid]) {
      if (hasOwnProperty(taxes[itemid], t))
        local_taxes[t] = taxes[itemid][t][0];
    }
  }
  price[itemid] = default_price[itemid];

  /* Find variant */
  for (var x in variants[itemid]) {
    if (!hasOwnProperty(variants[itemid], x) || variants[itemid][x][1].length == 0)
      continue;

    variantid = x;
    for (var c in variants[itemid][x][1]) {
      if (!hasOwnProperty(variants[itemid][x][1], c))
        continue;

      if (getPOValue(c, itemid) != variants[itemid][x][1][c]) {
        variantid = false;
        break;
      }
    }

    if (variantid)
      break;
  }

  /* If variant found ... */
  if (variantid) {
    var max_avail = variants[itemid][variantid][0][1];
    price[itemid] = variants[itemid][variantid][0][0];
    orig_price[itemid] = variants[itemid][variantid][0][4];
    avail[itemid] = variants[itemid][variantid][0][1];

    /* Get variant wholesale prices */
    if (variants[itemid][variantid][3]) {
      product_wholesale[itemid] = [];
      for (var t in variants[itemid][variantid][3]) {
        if (!hasOwnProperty(variants[itemid][variantid][3], t))
          continue;

        var _tmp = modi_price(variants[itemid][variantid][3][t][2], cloneObject(variants[itemid][variantid][3][t][3]), variants[itemid][variantid][3][t][4], itemid);
        product_wholesale[itemid][t] = [
          variants[itemid][variantid][3][t][0], 
          variants[itemid][variantid][3][t][1], 
          _tmp[0],
          []
        ];

        /* Get variant wholesale taxes */
        for (var c in _tmp[1]) {
          if (hasOwnProperty(_tmp[1], c))
            product_wholesale[itemid][t][3][c] = _tmp[1][c];
        }
      }
      is_rebuild_wholesale = true;
    }

    /* Get variant taxes */
    for (var t in local_taxes) {
      if (hasOwnProperty(local_taxes, t) && variants[itemid][variantid][2][t])
        local_taxes[t] = parseFloat(variants[itemid][variantid][2][t]);
    }

    if (!product_thumbnail)
      product_thumbnail = document.getElementById('product_thumbnail' + itemid);

    /* Change product thumbnail */
    if (product_thumbnail) {
      if (variants[itemid][variantid][0][2].src && variants[itemid][variantid][0][2].width > 0 && variants[itemid][variantid][0][2].height > 0) {
        if (getImgSrc(product_thumbnail) != variants[itemid][variantid][0][2].src) {

          if (getImgSrc(product_thumbnail) == product_image[itemid].src && typeof(product_image[itemid].isPNG) == 'undefined') {
            product_image[itemid].isPNG = isPngFix(product_thumbnail);
            product_image[itemid].width = product_thumbnail.width;
            product_image[itemid].height = product_thumbnail.height;
          }

          product_thumbnail.src = variants[itemid][variantid][0][2].src;
          product_thumbnail.width = variants[itemid][variantid][0][2]._x;
          product_thumbnail.height = variants[itemid][variantid][0][2]._y;
          if (typeof(window.saved_product_thumbnail) != 'undefined' && saved_product_thumbnail)
            saved_product_thumbnail = false;

          if (variants[itemid][variantid][0][6] && $.browser.msie)
            pngFix(product_thumbnail);
        }

      } else if (getImgSrc(product_thumbnail) != product_image[itemid].src) {
        product_thumbnail.src = product_image[itemid].src;
        if (product_image[itemid].width > 0 && product_image[itemid].height > 0) {
          product_thumbnail.width = product_image[itemid].width;
          product_thumbnail.height = product_image[itemid].height;
          if (typeof(window.saved_product_thumbnail) != 'undefined' && saved_product_thumbnail)
            saved_product_thumbnail = false;
        }

        if (product_image[itemid].isPNG)
          pngFix(product_thumbnail);
      }

      if (max_image_width > 0 && product_thumbnail.width > max_image_width) {
        product_thumbnail.height = Math.round(product_thumbnail.height*max_image_width/product_thumbnail.width);
        product_thumbnail.width = max_image_width;
      }
      if (max_image_height > 0 && product_thumbnail.height > max_image_height) {
        product_thumbnail.width = Math.round(product_thumbnail.width*max_image_height/product_thumbnail.height);
        product_thumbnail.height = max_image_height;
      }
    }

    /* Change product weight */
    if (document.getElementById('product_weight' + itemid))
      document.getElementById('product_weight' + itemid).innerHTML = price_format(variants[itemid][variantid][0][3]);

    if (document.getElementById('product_weight_box' + itemid))
      document.getElementById('product_weight_box' + itemid).style.display = parseFloat(variants[itemid][variantid][0][3]) > 0 ? "" : "none";

    /* Change product code */
    if (document.getElementById('product_code' + itemid))
      document.getElementById('product_code' + itemid).innerHTML = variants[itemid][variantid][0][5];

  }

  if (pconf_price[itemid] > 0)
    price[itemid] = pconf_price[itemid];

  /* Find modifiers */
  var _tmp = modi_price(price[itemid], local_taxes, orig_price[itemid], itemid);
  price[itemid] = _tmp[0];
  local_taxes = _tmp[1];
  if (!variantid) {
    product_wholesale[itemid] = [];
    for (var t in _product_wholesale[itemid]) {
      if (!hasOwnProperty(_product_wholesale[itemid], t))
        continue;

      _tmp = modi_price(_product_wholesale[itemid][t][2], _product_wholesale[itemid][t][3].slice(0), _product_wholesale[itemid][t][4], itemid);
      product_wholesale[itemid][t] = [
        _product_wholesale[itemid][t][0],
        _product_wholesale[itemid][t][1],
        _tmp[0],
        _tmp[1]
      ];
    }
    is_rebuild_wholesale = true;
  }

  /* Update taxes */
  for (var t in local_taxes) {
    if (!hasOwnProperty(local_taxes, t))
      continue;

    if (document.getElementById('tax_' + t + itemid)) {
      document.getElementById('tax_' + t + itemid).innerHTML = price_format(Math.max(local_taxes[t], 0));
    }
    current_taxes[itemid][t] = local_taxes[t];
  }

  if (is_rebuild_wholesale)
    rebuild_wholesale(itemid);

  /* Update form elements */
  /* Update price */
  if (document.getElementById('product_price' + itemid))
    document.getElementById('product_price' + itemid).innerHTML = price_format(Math.max(price[itemid], 0));

  /* Update alt. price */
  if (alter_currency_rate > 0 && document.getElementById('product_alt_price' + itemid)) {
    var altPrice = price[itemid]*alter_currency_rate;
    document.getElementById('product_alt_price' + itemid).innerHTML = price_format(Math.max(altPrice, 0));
  }

  /* Update Save % */
  if (document.getElementById('save_percent' + itemid) && document.getElementById('save_percent_box' + itemid) && list_price[itemid] > 0 && dynamic_save_money_enabled) {
    var save_percent = Math.round(100 - (price[itemid] / list_price[itemid]) * 100);
    if (save_percent > 0) {
      document.getElementById('save_percent_box' + itemid).style.display = '';
      document.getElementById('save_percent' + itemid).innerHTML = save_percent;

    } else {
      document.getElementById('save_percent_box' + itemid).style.display = 'none';
      document.getElementById('save_percent' + itemid).innerHTML = '0';
    }
  }

  /* Update product quantity */
  $('.product-quantity-text').html(avail[itemid] > 0 ? substitute(txt_items_available, "items", (variantid ? avail[itemid] : product_avail[itemid])) : lbl_no_items_available);
  $('.product-quantity-number').html(avail[itemid] > 0 ? (variantid ? avail[itemid] : product_avail[itemid]) : 0);

  if ((mq[itemid] > 0 && avail[itemid] > mq[itemid] + min_avail[itemid]) || !is_limit)
    avail[itemid] = mq[itemid] + min_avail[itemid] - 1;

  avail[itemid] = Math.min(mq[itemid], avail[itemid]);

  var select_avail = min_avail[itemid];

  /* Update product quantity selector */
  availObj = document.getElementById(quantity_input_box_enabled[itemid] ? 'product_avail_input' + itemid : 'product_avail' + itemid);

  if (availObj && availObj.tagName.toUpperCase() == 'SELECT') {

    // Select box
    if (!isNaN(min_avail[itemid]) && !isNaN(avail[itemid])) {
      var first_value = -1;
      if (availObj.options[0])
        first_value = availObj.options[0].value;

      if (first_value == min_avail[itemid]) {

        /* New and old first value in quantities list is equal */
        if ((avail[itemid] - min_avail[itemid] + 1) != availObj.options.length) {
          if (availObj.options.length > avail[itemid] - min_avail[itemid] + 1) {
            var cnt = availObj.options.length;
            for (var x = (avail[itemid] - min_avail[itemid] + 1 < 0 ? 0 : avail[itemid] - min_avail[itemid] + 1); x < cnt; x++)
              availObj.options[availObj.options.length-1] = null;

          } else {
            var cnt = availObj.options.length;
            for (var x = cnt + min_avail[itemid]; x <= avail[itemid] - min_avail[itemid] + 1; x++)
              availObj.options[cnt++] = new Option(x, x);
          }
        }
      } else {

        /* New and old first value in quantities list is differ */
        var cnt = availObj.options.length - 1;
        while (cnt >= 0)
          availObj.options[cnt--] = null;

        cnt = 0;
        for (var x = min_avail[itemid]; x <= avail[itemid]; x++)
          availObj.options[cnt++] = new Option(x, x);
      }
      if (availObj.options.length == 0 || min_avail[itemid] > avail[itemid])
        availObj.options[0] = new Option(txt_out_of_stock, 0);
    }
    select_avail = availObj.options[availObj.selectedIndex].value;

  } else if (availObj && availObj.tagName.toUpperCase() == 'INPUT' && availObj.type.toUpperCase() == 'TEXT') {

    // Input box
        if (!isNaN(min_avail[itemid]) && !isNaN(avail[itemid])) {
      availObj.minQuantity = min_avail[itemid];
      availObj.maxQuantity = max_avail;
    }

    if (isNaN(parseInt(availObj.value)) || availObj.value == 0) 
       availObj.value = min_avail[itemid];
    
      select_avail = availObj.value;
  }



  check_wholesale(select_avail, itemid);

  if (alert_msg == 'Y' && min_avail[itemid] > avail[itemid])
    alert(txt_out_of_stock);
  
  /* Check exceptions */
  var ex_flag = check_exceptions(itemid);
  if (!ex_flag && (alert_msg == 'Y'))
    alert(exception_msg);

  if (document.getElementById('exception_msg' + itemid)) {
    if (ex_flag) {
      document.getElementById('exception_msg' + itemid).style.display = 'none';

    } else {
      document.getElementById('exception_msg' + itemid).innerHTML = exception_msg_html;
      document.getElementById('exception_msg' + itemid).style.display = '';
    }
  }

  return true;
}

/**
 * Calculate product price with price modificators 
 */
function modi_price(_price, _taxes, _orig_price, itemid) {
  var return_price = round(_price, 2);

  /* List modificators */
  for (var x2 in modifiers[itemid]) {
    if (!hasOwnProperty(modifiers[itemid], x2))
      continue;

    var value = getPOValue(x2, itemid);
    if (!value || !modifiers[itemid][x2][value])
      continue;

    /* Get selected option */
    var elm = modifiers[itemid][x2][value];
    return_price += parseFloat(elm[1] == '$' ? elm[0] : (_price*elm[0]/100));

    /* Get tax extra charge */
    for (var t2 in _taxes) {
      if (hasOwnProperty(_taxes, t2) && elm[2][t2])
        _taxes[t2] += parseFloat(elm[1] == '$' ? elm[2][t2] : (_orig_price*elm[2][t2]/100));
    }
  }

  return [return_price, _taxes];
}

/**
 * Check product options exceptions
 */
function check_exceptions(itemid) {
  if (typeof(exceptions[itemid]) === 'undefined')
    return true;

  /* List exceptions */
  for (var x in exceptions[itemid]) {
    if (!hasOwnProperty(exceptions[itemid], x) || isNaN(x))
      continue;

    var found = true;
        for (var c in exceptions[itemid][x]) {
      if (!hasOwnProperty(exceptions[itemid][x], c))
        continue;

      var value = getPOValue(c, itemid);
      if (!value)
        return true;

            if (value != exceptions[itemid][x][c]) {
        found = false;
        break;
      }
    }
    if (found)
      return false;
  }

  return true;
}

/**
 * Rebuild wholesale tables
 */
function rebuild_wholesale(itemid) {
  var div = document.getElementById('wl-prices' + itemid);
  var wl_table = $('table', div).get(0);
  var wl_taxes = $('div', div).get(0);

  if (!div || !wl_table || !wl_taxes)
    return false;

  /* Clear wholesale span object if product wholesale prices service array is empty */
  var i = wl_table.rows.length - 1;
  while (i > 0)
    wl_table.deleteRow(i--);

  if (!product_wholesale[itemid] || product_wholesale[itemid].length == 0) {
    div.style.display = 'none';
    return false;
  }

  /* Display wholesale prices table */
  var str = '';
  var r;
  for (i in product_wholesale[itemid]) {
    if (!hasOwnProperty(product_wholesale[itemid], i) || product_wholesale[itemid][i][0] == 0)
      continue;

    r = wl_table.insertRow(-1);
    insert_text = (product_wholesale[itemid][i][1] == 0) ? product_wholesale[itemid][i][0] + '+' : (product_wholesale[itemid][i][1] - product_wholesale[itemid][i][0] > 0 ? product_wholesale[itemid][i][0] + '-' + product_wholesale[itemid][i][1] : product_wholesale[itemid][i][0]);
    r.insertCell(-1).innerHTML = insert_text + '&nbsp;' + (product_wholesale[itemid][i][0] == 1 ? lbl_item : lbl_items);
    r.insertCell(-1).innerHTML = price_format(product_wholesale[itemid][i][2] < 0 ? 0 : product_wholesale[itemid][i][2], false, false, false, true);
  }

  if (wl_table.rows.length <= 1) {
        div.style.display = 'none';
    return false;
  }

    /* Display wholesale prices taxes */
    var display_taxes = false;
  if (taxes[itemid].length > 0) {
        for (i in taxes[itemid]) {
            if (hasOwnProperty(taxes[itemid], i) && current_taxes[itemid][i] > 0)
        display_taxes = true;
        }
    }

  if (!display_taxes) 
     wl_taxes.style.display = 'none';
  else
    wl_taxes.style.display = '';

    div.style.display = '';

  return true;
}

/**
 * Display current wholesale price as product price
 */
function check_wholesale(qty, itemid) {

  if ((typeof(product_wholesale) == 'undefined') ||  typeof(product_wholesale[itemid]) == 'undefined' ||  product_wholesale[itemid].length == 0)
    return true;

  var wl_taxes = current_taxes[itemid].slice(0);
  var wl_price = price[itemid];
  for (var x = 0; x < product_wholesale[itemid].length; x++) {
    if (product_wholesale[itemid][x][0] <= qty && (product_wholesale[itemid][x][1] >= qty || product_wholesale[itemid][x][1] == 0)) {
      wl_price = product_wholesale[itemid][x][2];
      wl_taxes = product_wholesale[itemid][x][3].slice(0);
    }

    if (document.getElementById('wp' + itemid + x)) {
      var wPrice = price[itemid] - default_price[itemid] + product_wholesale[itemid][x][2];
      document.getElementById('wp' + itemid + x).innerHTML = price_format(Math.max(wPrice, 0));
    }
  }

  if (document.getElementById('product_price' + itemid))
    document.getElementById('product_price' + itemid).innerHTML = price_format(Math.max(wl_price, 0));

  if (alter_currency_rate > 0 && document.getElementById('product_alt_price' + itemid)) {
    document.getElementById('product_alt_price' + itemid).innerHTML = price_format(Math.max(wl_price * alter_currency_rate, 0));
  }

  /* Update Save % */
  if (document.getElementById('save_percent' + itemid) && document.getElementById('save_percent_box' + itemid) && list_price[itemid] > 0 && dynamic_save_money_enabled) {
    var save_percent = Math.round(100 - (Math.max(wl_price, 0) / list_price[itemid]) * 100);
    if (save_percent > 0) {
      document.getElementById('save_percent_box' + itemid).style.display = '';
      document.getElementById('save_percent' + itemid).innerHTML = save_percent;

    } else {
      document.getElementById('save_percent_box' + itemid).style.display = 'none';
      document.getElementById('save_percent' + itemid).innerHTML = '0';
    }
  }


  for (var x in taxes[itemid]) {
    if (hasOwnProperty(taxes[itemid], x) && document.getElementById('tax_' + x + itemid) && wl_taxes[x] && current_taxes[itemid][x]) {
      document.getElementById('tax_' + x + itemid).innerHTML = price_format(Math.max(wl_taxes[x], 0));
    }
  }

  return true;
}

/**
 * Get product option value
 */
function getPOValue(c, itemid) {
  if (!document.getElementById('po' + itemid + c) || document.getElementById('po' + itemid + c).tagName.toUpperCase() != 'SELECT')
    return false;

  return document.getElementById('po' + itemid + c).options[document.getElementById('po' + itemid +c).selectedIndex].value;
}

/**
 * Get product option object by class name / class id
 */
function product_option(classid, itemid) {
  if (!isNaN(classid))
     return document.getElementById("po" + itemid + classid);

  if (!names[itemid])
    return false;

  for (var x in names[itemid]) {
    if (!hasOwnProperty(names[itemid], x) || names[itemid][x]['class_name'] != classid)
      continue;

    return document.getElementById('po' + itemid + x);
    }

  return false;
}

/**
 * Get product option value by class name / or class id
 */
function product_option_value(classid, itemid) {
  var obj = product_option(classid, itemid);
  if (!obj)
    return false;

  if (obj.type != 'select-one')
    return obj.value;

  var classid = parseInt(obj.id.substr(2));
  var optionid = parseInt(obj.options[obj.selectedIndex].value);
  if (names[itemid][classid] && names[itemid][classid]['options'][optionid])
    return names[itemid][classid]['options'][optionid];

  return false;
}

/**
 * Hide the "Options are expired message" and update product in the cart
 */
function close_opts_expire_msg(cartid) {

  var post_params = 'target=cart&mode=update&product_options=1&id=' + cartid;
  var cart_message_box = document.getElementById('cart_message_' + cartid);

  $.ajax({type: 'POST', url: 'popup_poptions.php', data: post_params});
  if (cart_message_box) {
    cart_message_box.style.display = 'none';
  }

  return false;
}


