var currentInitial = null;
var result = null;
var headerLabels = null;
var showAll = false;

/*
 * 一行分のテンプレート(protoType.Template)。#{変数}が置換されます。
 */
var templateStr = '<tr>';
templateStr += '<td class="thumbnail">';
templateStr += '<a href="/product/item.jsp?productId=#{id}"><img src="#{image}" width="48" height="48" /></a>';
templateStr += '</td>';
templateStr += '<td class="productId" nowrap="nowrap">';
templateStr += '<a href="/product/item.jsp?productId=#{id}">#{id}</a>'
templateStr += '</td>';
templateStr += '<td class="properties">';
templateStr += '<div class="name">#{name} #{icon}</div>';
templateStr += '<div class="price">#{price}</div>';
templateStr += '</td>';
templateStr += '<td class="bool hasCad">#{hasCad}&nbsp;</td>';
templateStr += '<td class="bool hasPhoto">#{hasPhoto}&nbsp;</td>';
templateStr += '<td class="bool hasSimulation">#{hasSimulation}&nbsp;</td>';
templateStr += '<td class="bool hasSet none">#{hasSet}&nbsp;</td>';
templateStr += '</tr>';
var template = new Template(templateStr);

Event.observe(window, 'load', function() {
  new Ajax.Request(
    "/professionals/productListJson.do",
    {
      onComplete: function(req) {
        result = eval("(" + req.responseText + ")");
        currentInitial = getFirstInitial(result.products);
        fillInitials();
        headerLabels = $("labels");
        fillTable(currentInitial);
      },
      onException: function(req, e) { throw e; }
    }
  );
});

  function toggleFilter() {
    if (showAll) {
      showAll = false;
      $("filterSwitch").innerHTML = "全件表示";
      $("filterSwitchFoot").innerHTML = "全件表示";
    } else {
      showAll = true;
      $("filterSwitch").innerHTML = "廃盤品・データのない製品を非表示";
      $("filterSwitchFoot").innerHTML = "廃盤品・データのない製品を非表示";
    }
    refillTable(currentInitial);
  }

  function fillInitials() {
    execFillInitials($("initials"));
    execFillInitials($("footerInitials"));
  }

  function execFillInitials(parent) {
    for (var i=0; i<result.initials.length; i++) {
      if (i > 0) {
        parent.appendChild(document.createTextNode(" | "));
      }
      var a = document.createElement("a");
      a.innerHTML += result.initials[i];
      a.href = "javascript:refillTable('" + result.initials[i] + "')";
      parent.appendChild(a);
    }
  }

  function refillTable(initial) {
    if (initial != null) {
      currentInitial = initial;
    }
    clearTable();
    fillTable(currentInitial);
  }

  function clearTable() {
    // setting innerHTML to null value should be faster, but does not work on win/ie.
    var children = $("productContainer").childNodes;
    for (var i = children.length - 1; i >= 0; i--) {
      Element.remove(children[i]);
    }
  }

  function fillTable(initial) {
    activateInitial(initial);
    products = filterProducts(result.products[initial]);
    setupMiscSign(initial, products.length);
    var html = "";
    for (var i=0; i<products.length ;i++) {
      if (i > 0 && i % 10 == 0) {
        new Insertion.Bottom($("productContainer"), headerLabels.cloneNode(true));
      }
      fillRow(products[i]);
    }
    $("loadingSign").style.display = "none";
  }

  function filterProducts(products) {
    if (showAll) {
      return products;
    }
    var result = new Array();
    for (var i=0; i<products.length; i++) {
      var p = products[i];
      if (p.state != "discontinued"
          && (p.hasCad || p.hasDrawing || p.hasPhoto || p.hasSimulation || p.hasSetCera || p.hasSetToto)) {
        result.push(p);
      }
    }
    return result;
  }

  function activateInitial(initial) {
    execActivateInitial($("initials"), initial);
    execActivateInitial($("footerInitials"), initial);
  }

  function execActivateInitial(parent, initial) {
    var initials = parent.childNodes;
    for (var i=0; i<initials.length; i++) {
      if (initials[i].nodeType != 1 || initials[i].nodeName != "A") {
        continue;
      }
      var value = initials[i].firstChild.nodeValue;

      if (value == initial) {
        Element.addClassName(initials[i], "active");
      } else {
        Element.removeClassName(initials[i], "active");
      }
    }
  }

  function setupMiscSign(initial, hit) {
    $("totalSign").innerHTML = result.total;
    $("currentCountSign").innerHTML = hit;
    $("summary").style.display = "inline";

    $("summary2").innerHTML ="";
    var children = $("summary").childNodes;
    for (var i=0; i<children.length; i++) {
      $("summary2").appendChild(children[i].cloneNode(true));
    }
    $("summary2").style.display = "inline";
  }

  function fillRow(product) {
    var price = product.minPriceWithTax;
    if (product.maxPriceWithTax != null) {
      price += "〜" + product.maxPriceWithTax;
    }
    var hasCad = "";
    var hasPhoto = "";
    var hasSimulation = "";
    var hasSet = "";
    if (product.hasCad || product.hasDrawing) {
      hasCad = '<a href="/product/item.jsp?productId=' + product.id + '#cad_data">●';
    }
    if (product.hasPhoto) {
      hasPhoto = '<a href="/product/item.jsp?productId=' + product.id + '#photo_data">●</a>';
    }
    if (product.hasSimulation) {
      hasSimulation = '<a href="/product/item.jsp?productId=' + product.id + '#simulation">●</a>';
    }
    if (product.hasSetCera || product.hasSetToto) {
      hasSet = '<a href="/product/item.jsp?productId=' + product.id + '#set">●</a>';
    }
    var name = product.name;
    if (product.seriesName) {
      name = product.seriesName + " " + name;
    }
    if (product.state != null && product.state != "") {
      name += '<img src="/product/images/icon_' + product.state + '.gif" valign="middle" style="margin-left:.5em;" />';
    }

    html = template.evaluate(
      {
        image: "/product/images/thumbnail/" + product.image,
        id: product.id,
        name: name,
        price: price,
        hasCad: hasCad,
        hasPhoto: hasPhoto,
        hasSimulation: hasSimulation,
        hasSet: hasSet
      }
    );
    // setting innerHTML should be faster, but does not work on win/ie.
    new Insertion.Bottom($("productContainer"), html);
  }

  function getFirstInitial(map) {
    for (key in map) {
      return key;
    }
  }
