
// oemschematic.js

$(document).ready(function() {

  // Check availability for multiple items.
  //  Loop each item row, save valid ones, display invalid.
  //  If all valid, display spinner and submit.
  //  Callback returns xml results.
  //  Loop each result, update corresponding image.
  // Note: Several selectors below use a suffix approach, since id is mangled.
  $('a.OemCheckAvail').live("click", function() {     // Use live() to survive postbacks.
    var formRequests = [];        // new array, literal syntax.
    var areAllValid = true;
    
    // Get the machine and schematic id. Use container control too, since there are several schematic ids on the page.
    var machineID = $('input[id$="_ucOemSchProductList_hidMachineID"]').val();     // Suffix approach.   
    var schematicID = $('input[id$="_ucOemSchProductList_hidSchematicID"]').val();     // Suffix approach.   
    
    // Start in table just to reduce the search.
    //  Look for a qty box to avoid disabled rows (and avoids the header row). Could select other ways also, e.g., not disabled, or an input textbox.
    var rows = $('#tblOemProdList tr:has("input[id$=\"_txtQty\"]")')    

    rows.each(function() {
      var isRowFullyValid = false;        // Flag if valid and > 0 (i.e., submitting it).
      var qtyVal = $(this).find('input[id$="_txtQty"]').val();       // Suffix approach.
      if (qtyVal.length > 0)          // Distinguishing invalid from qty 0.
      {
        // Validate qty.
        //  This gets a little too nested; there's no jquery 'continue'.
        //  ASSUME: Reusing ajax validator's error message. A little hacky, but didn't want to repeat it.
        //  ASSUME: Match ajax validator conditions so the message matches.
        //  Consider the validation plugin.
        if (isNumeric(qtyVal) && (qtyVal >= 0) && (qtyVal <= 99) && (qtyVal == parseInt(qtyVal, 10)))      // Numeric (our function), 0 to 99, integer.
        {
          if (qtyVal > 0)             // If 0, just skip it without an error.
          {
            // Valid. Get bsin, and image reference for below.
            var bsinVal = $(this).find('input[id$="_hidBsin"]').val();     // Suffix approach.
            var img = $(this).find('img[id$="_imgAvail"]');     // Suffix approach. Probably could assume the only image, but that's fragile.

            // Push an object literal of various properties.
            formRequests.push({ Bsin: bsinVal, Qty: qtyVal, MachineID: machineID, SchematicID: schematicID, Img: img });
            isRowFullyValid = true;
          }
        }
        else
        {
          // Invalid.
          $(this).find('span[id$="_revQty"]').css("display", "inline");    // Suffix approach.
          areAllValid = false;
        }
        
        // If row is not fully valid (invalid or 0), hide the image in case previous call displayed it.
        if (!isRowFullyValid)
        {
          var img = $(this).find('img[id$="_imgAvail"]');     // Suffix approach. Probably could assume the only image, but that's fragile.
          img.css("display", "none");
        }
      }
    });   // rows.each()
    
    // If all valid, continue.
    if (areAllValid)
    {
      for (var i = 0; i < formRequests.length; i++)
      {
        // Display progress spinner.
        var img = formRequests[i].Img;
        img.attr("src", "/img/loading_20.gif");
        img.css("display", "inline");
      }

      // Map the form values to the array to post. Get the properties without the img.
      var availRequests = $.map(formRequests, function(formRequest) {
        return { Bsin: formRequest.Bsin, Qty: formRequest.Qty, MachineID: formRequest.MachineID, SchematicID: formRequest.SchematicID};
      });

      // Service's parameter name, and the array corresponding to List of OemAvailabilityRequest.
      var postData = { oemAvailabilityRequests: availRequests };

      // Post.
      //  ajax instead of post method worked for list of OemAvailabilityRequest objects.
      //  See subrandomactsofcoding.blogspot.com/2009/03/jquery-json-and-asmx-20-services.html
      $.ajax({
        url: '/partsbandit/ext/OemService.asmx/GetOemAvailability',
        type: 'POST',
        data: JSON.stringify(postData),
        contentType: 'application/json; charset=utf-8',
        dataType: 'xml',
        success: function(xml) {
          // Response.
          //  Loop requests, display corresponding result image.
          //    If no result, display unknown (blank) image.
          //  Don't assume results are in the same order.
          for (var i = 0; i < formRequests.length; i++)
          {
            var img = formRequests[i].Img;

            // filter function lets us look in child elements and their text() contents. Can't seem to get to text with a simple selector. :contains() matches subsets.
            var xmlResult = $(xml).find('OemAvailabilityResult').filter(function() {
              return $(this).find('Bsin').text() == formRequests[i].Bsin;
            });
            
            if (xmlResult.length > 0)       // Test if there is a result for this request. length is the count of the returned 'set' of jquery objects.
            {
              var rankID = $(xmlResult).find('RankID').text();
              var rank = $(xml).find('ProductAvailabilityRank').filter(function() {
                return $(this).find('ID').text() == rankID;
              });
              
              // Set image to result.
              img.attr("src", "/img/" + $(rank).find('ImageName').text().replace("_", "_md_"));   // ASSUME: Duplicates ProductAvailabilityRank.MediumUrl
              img.attr("alt", $(rank).find('RankDescription').text());
              img.attr("title", $(rank).find('RankDescription').text());
            }
            else
            {
              img.attr("src", "/img/spacer.gif");     // ASSUME: Match unknown availability. LATER: If a specific unknown rank gets added to the list, use it.
              img.attr("alt", "Unknown");
              img.attr("title", "Unknown");
            }
            
            img.css("display", "inline");           // Should be visible already (spinner or previous result), but just in case.
          }
        }
      });   // .ajax()
    }
    
    return false;     // Cancel calling link.
  });   // .live()
  

  // UNUSED: Single availability request and result.
  //  Kept here for reference for now.
  $('a.OemCheckAvailUnused').live("click", function() {     // Use live() to survive postbacks.
    var thisLinkID = $(this).attr("id");      // Keep it for the callback. It has a repeater index on the id.
    var tr = $(this).parent().parent();       // Up to the row, for a common starting point. ASSUME: This is a little fragile; prefer id, but it's mangled.
    var bsinVal = tr.find('input[id$="_hidBsin"]').val();     // Suffix approach, since id is mangled, and we're down in one repeater item.
    var qtyVal = tr.find('input[id$="_txtQty"]').val();       // Suffix approach, ditto.

    // Validate qty.
    //  ASSUME: Reusing ajax validator's error message. A little hacky, but didn't want to repeat it.
    //  Consider the validation plugin.
    if ((qtyVal <= 0) || (qtyVal > 99))             // ASSUME: Match ajax validator conditions.
    {
      tr.find('span[id$="_revQty"]').css("display", "inline");    // Suffix approach, ditto.
      return false;
    }
    
    // Display progress spinner; hide link.
    $(this).css("display", "none");
    var img = $(this).siblings('img');   // The only one is the avail image.
    img.attr("src", "/img/loading_20.gif");
    img.css("display", "inline");
    
    $.post("/partsbandit/ext/OemService.asmx/GetOemAvailability", { bsin: bsinVal, qty: qtyVal },
      function(xml) {
        // Set image to result.
        var thisLink = $('#' + thisLinkID);
        var img = thisLink.siblings('img');   // The only one is the avail image.
        img.attr("src", $("MediumUrl", xml).text());
        img.attr("alt", $("Description", xml).text());
      },
      "xml"
    )
    return false;
  })});