/* BEGIN: This is Krom software.  Please see the accompanying license. */

mwk_profiling = false;

function mwkCollectText(node) { 
  if (node.nodeType == Node.TEXT_NODE) {  
  	return node.nodeValue.strip();
  } else if (node.hasChildNodes()) {
    return node.childNodes.map(function(s) {
		mwkCollectText(s)
	}).join(' ');
  } else {
	return "";
  }
}               
         
Element.addMethods({ 
 mwkCollectTextNodes: function(element) { 
	return $A($(element).childNodes).collect( function(node) { 
		return (node.nodeType==3 ? node.nodeValue : 
			(node.hasChildNodes() ? Element.collectTextNodes(node) : '')); 
			}).flatten().join(''); 
}                             
}); 

function mwk_update() {
   var search_chars = $F('search_chars').strip();
   var search_model = $F('search_model').strip();
   var search_category = $F('search_category').strip();
   var search_branch = $F('search_branch').strip();

	$$('.search_table .section_tbody').each(function(tbody_el) {
      tbody_match = false;
	  tbody_el.select('.searchable_row').each(function(el) {
		var res = mwk_match_row(el, search_chars, search_model, search_category, search_branch);
		if (res) {
			tbody_match = true;
		}
      });
	  if (tbody_match) {
		tbody_el.show();
      } else {
	    tbody_el.hide();
	  }
	})
	
}            
function collect_inputs(inps) {
  if ((inps == null) || (inps == "")) {
	return [];
  }
  var res = inps.map(function(v) {
      return v.strip();
    }).findAll(function(v) {
	  return (v != "");
    }).map(function(v) {
	  // return an array of 1, or of multiple
	  if (v.include(',')) {
		return v.split(',');
      } else {
		return [v];
      }
	});

  //possible to have same category selected twice: Itself, and in major category.
  return res.flatten().uniq();
}

// Cache DOM lookups
var mwk_inv_tbody_ids = [];
var mwk_inv_tbodies = {};
var mwk_inv_tbody_trs = {}
	//	mwk_inv_tbodies = $$('.search_table .section_tbody');
function mwk_inv_data_structure_prepare() {
	$$('.search_table .section_tbody').each(function(el) {
		var ar = [];
		mwk_inv_tbody_ids.push(el.id);
		mwk_inv_tbodies[el.id] = el;
		mwk_inv_tbody_trs[el.id] = ar;
		el.select('.searchable_row').each(function(el2) {
			ar.push(el2);
		});
	});
};

function mwk_searchlot_update() { 
   var search_chars = $F('search_serial_tag').strip();
   var search_models = collect_inputs($F('search_model'), true);
   var search_manufacturers = collect_inputs($F('search_manufacturer'));
   var search_categories = [];
   if ($('search_category')) {
	// Sometimes this is not on the page
     var search_categories = collect_inputs($F('search_category'));
   }

   var m_count = 0;
   $$('.searchable_row').each(function(el) { 
		var res = mwk_searchlot_match_row(el, search_chars, search_models, search_manufacturers,
     		search_categories);
		if (res) {
		    m_count += 1;
		    el.show();
		} else {
			el.hide();
		}
    });
	// var text = "";
	// if (m_count == 1) {
	// 	text = "1 machine";
	// } else {
	// 	text = m_count + " machines";
	// }
	// $('m_count').update(text);
	// $('m_count').highlight({'duration': 2.5, 'startcolor' : '#ffe400'});
	// mwk_inventory_report(); // update hidden form field with currently-visible items.
	return false;
}

function mwk_inv_update(evaluator_mode) { 
   h = new Hash();
   t = new Date().getTime();
   h.evaluator_mode = evaluator_mode;

   h.chars = $F('search_serial_tag').strip();
   h.models = collect_inputs($F('search_model'), true);
   h.categories = collect_inputs($F('search_category'));
   h.manufacturers = collect_inputs($F('search_manufacturer'));
   h.locations = collect_inputs($F('search_location'));

  if (evaluator_mode) {
	h.salesperson = $F('search_salesperson').strip();
  } else {
    h.status = '';  // never searching on it now
    h.age = $F('search_age').strip();
    h.max = $F('search_max').strip();
    h.on_lot = $F('search_on_lot');
    h.warranty = $F('search_warranty');
   }
   var m_count = 0;
  // mwk_inv_tbodies.each(function(tbody_el) {
   mwk_inv_tbody_ids.each(function(tbody_id) {
//	console.log("tbody_id:", tbody_id);
      tbody_el = mwk_inv_tbodies[tbody_id];
      tbody_match = false;
	 // tbody_el.select('.searchable_row').each(function(el) { 
	  mwk_inv_tbody_trs[tbody_id].each(function(el) {
		// var res = mwk_inv_match_row(el, search_chars, search_models, search_categories, search_manufacturers,
		// 	search_locations, search_status, search_age, search_max, search_on_lot, search_warranty);
		var res = mwk_inv_match_row(el, h)
		if (res) {
			tbody_match = true;
		    m_count += 1;
		}
      });
	  if (tbody_match) {
		tbody_el.show();
      } else {
	    tbody_el.hide();
	  }
	})  
	var to_highlight = null;
	if (m_count == 1) {
		to_highlight = $('m_count_singular');
		$('m_count_plural').hide();
		to_highlight.show();
	} else {
		$('m_count_number').update(m_count);
		to_highlight = $('m_count_plural');
		$('m_count_singular').hide();
		to_highlight.show();
	}
	to_highlight.highlight({'duration': 2.5, 'startcolor' : '#ffe400', 'endcolor' : '#ffffff'});
	mwk_inventory_report(); // update hidden form field with currently-visible items.
    if (mwk_profiling) {
		el1 = (new Date().getTime()) - t;
		alert("Elapsed inv_update: " + el1);
	}
}

function mwk_search_chars_match(element, search_chars) {
  return element.select('.searchable').any(function(el2) {
		  var cs = el2.childNodes;
		  if (cs.length == 0) {
			return false;
          } else {  
	        if (cs[0].nodeType == Node.TEXT_NODE) {
     	    	return (cs[0].nodeValue.toLowerCase().include(search_chars.toLowerCase()));
			} else {  
				// hack!   FIXME
				return cs[0].childNodes[0].nodeValue.toLowerCase().include(search_chars.toLowerCase());
			}
//            return $(cs).mwkCollectTextNodes();
          }
	    }) 	
}

function mwk_inv_match_row(el, h) {
	    // var rrr = Math.floor(Math.random()*2);
	    // return (rrr == 0);
	
	    var evaluator_mode = h.evaluator_mode;
	    match = true;
		if (match && (h.chars.length > 0)) {
    	    match = mwk_search_chars_match(el, h.chars);
        }
    	if (match && (h.models.length > 0)) {
			var mmm = el.readAttribute("search_model");
			match = h.models.any(function(search_model) {
				return (mmm == search_model);
			})
       	}
    	if (match && (h.categories.length > 0)) {
			var ccc = el.readAttribute("search_category");
			match = h.categories.any(function(search_category) {
				return (ccc == search_category);
			})
       	}
    	if (match && (h.manufacturers.length > 0)) {
			var mmm = el.readAttribute("search_manufacturer");
			match = h.manufacturers.any(function(search_manufacturer) {
				return (mmm == search_manufacturer);
			})
       	}
        if (match && (h.locations.length > 0)) {
			var lll = el.readAttribute("search_location");
			match = h.locations.any(function(search_location) {
				return (lll == search_location);
			})
        }
        if (evaluator_mode) {
			if (match && (h.salesperson != "")) {
				
				var sss = el.readAttribute("search_salesperson");
				match = (sss == h.salesperson);
			}
	
		} else {
			if (match && (h.status != "")) {
				var lll = el.readAttribute("search_status");
				match = (lll == h.status);
			}
			if (match && (h.age != "")) {
				var lll = el.readAttribute("search_age");
				match = (lll == h.age);
			}
			if (match && (h.max != "")) {
				var selection_split = h.max.split('_');
				var attr_key = selection_split[0].toUpperCase();
				var sense = (selection_split[1] == 'yes');
				//alert(attr_key + sense.to_s);
				var res = (el.readAttribute("MAX_" + attr_key) == 'y');
				if (sense) {
					match = res;
				} else {
					match = (! res);
				}
			}
			if (match && (h.on_lot != "")) {
				match = (h.on_lot == el.readAttribute("search_on_lot"));
			}
			if (match && (h.warranty != "")) {
				match = (h.warranty == el.readAttribute("search_warranty"));
			}
		}
		// if (match && (search_category != "")) {
		//    match = (el.readAttribute("search_category") == search_category)
		// }
	    if (match) {
	      el.show();
		  return true;
	    } else {
	      el.hide();  
		  return false;
	   	}
}

function mwk_searchlot_match_row(el, search_chars, search_models, search_manufacturers, search_categories) {
        match = true;
		if (match && (search_chars.length > 0)) {
    	    match = mwk_search_chars_match(el, search_chars);
        }
    	if (match && (search_models.length > 0)) {
			var mmm = el.readAttribute("search_model");
			match = search_models.any(function(search_model) {
				return (mmm == search_model);
			})
       	}
    	if (match && (search_manufacturers.length > 0)) {
			var mmm = el.readAttribute("search_manufacturer");
			match = search_manufacturers.any(function(search_manufacturer) {
				return (mmm == search_manufacturer);
			})
       	}
    	if (match && (search_categories.length > 0)) {
			var ccc = el.readAttribute("search_category");
			match = search_categories.any(function(search_category) {
				return (ccc == search_category);
			})
       	}
	    if (match) {
	      el.show();
		  return true;
	    } else {
	      el.hide();  
		  return false;
	   	}
}

function mwk_match_row(el, search_chars, search_model, search_category, search_branch) {
	    match = mwk_search_chars_match(el, search_chars);
	 	if (match && (search_model != "")) {
		   match = (el.readAttribute("search_model") == search_model)
    	}
		if (match && (search_category != "")) {
		   match = (el.readAttribute("search_category") == search_category)
		}
		if (match && (search_branch != "")) {
		   match = (el.readAttribute("search_branch") == search_branch)
		}
	    if (match) {
	      el.show();
		  return true;
	    } else {
	      el.hide();  
		  return false;
	   	}
}


                 
/* END: This is Krom software.  Please see the accompanying license. */
