/*
 * IBP_ViewModel
 *
 * (c)Copyright 2010, ICT Business Partners B.V.
 *
 */

var contentArray = [];
var searchDelayID = -1; // timerID
var hideInDelayID = -1;
var ibp_checkList_arrayID = -1; //timerID voor ibp_checkList_array
var FreeToSearch = false;

//========================================
function StringBuffer() {
    this.__strings__ = new Array;
}

StringBuffer.prototype.append = function (str) {
    this.__strings__.push(str);
};

StringBuffer.prototype.toString = function () {
    return this.__strings__.join("");
};
//========================================

function ibp_AddTypes(Type, Serienummer, Modellijst) {
  contentArray[contentArray.length] = [Type, Serienummer, Modellijst];
}

function dump() {
  for (var i=0; i<contentArray.length; i++) log("dump: "+ i + "=" + contentArray[i][0] + ", " + contentArray[i][1] + ", " +  contentArray[i][2]);
}

function ibp_checkList_array(searchString, brandFilter, limit) {
  clearTimeout(ibp_checkList_arrayID);
  
//  hide(document.getElementById('IBP_contentDivLimitTop'), true);
//  hide(document.getElementById('IBP_contentDivLimitBottom'), true);
  hide(document.getElementById('IBP_bezig_met_zoeken'), false);
  //hide(document.getElementById('IBP_zoeken'), true); // hide knop?
  
  ibp_checkList_arrayID = setTimeout(function(){ibp_checkList_array_(searchString, brandFilter, limit)}, 5);
}

function ibp_checkList_array_(searchString, brandFilter, limit) {
  if (!limit) limit = 250;
  
  ShowCount = 0;
  FreeToSearch = true;

  var ModelsContainerTbody = document.getElementById('ibp_model_content');

  brandFilter = brandFilter.toLowerCase();
  searchString = searchString.toLowerCase().replace(/ +/g, " "); // lowercase and get rid of multiple spaces
  var ssArray = searchString.split(" ", 5); // split in maximum 5 chunks
  
  var HTML = '';
  var sb = new StringBuffer();
  
  for (var i=0; i< contentArray.length; i++)
  {
    if (ShowCount >= limit) break;
    
    var found = true;
    if (searchString != "") {
      var modelTitle = contentArray[i][0].toLowerCase(); // ibp_modeltitle
      var modelRef = contentArray[i][1].toLowerCase(); // ibp_modelref
      var brand = contentArray[i][2].toLowerCase(); // ibp_modelbrands
      for (var j=0; j<ssArray.length; j++) {
        if (brandFilter != "" && brand.indexOf(brandFilter) == -1) { 
          found = false;
          break;
        }
        if (modelTitle.indexOf(ssArray[j]) == -1 && modelRef.indexOf(ssArray[j]) == -1) { 
          found = false;
          break;
        }
      }
    } else {
      // alleen op brand filteren indien gewenst
      var brand = contentArray[i][2].toLowerCase(); // ibp_modelbrands
      if (brandFilter != "" && brand.indexOf(brandFilter) == -1) found = false;    
    }
    
    if (found) {
      ShowCount++;
      sb.append("<span name=\"ibp_row\">"
      + "<span id=\"ibp_modeltitle\" style=\"float: left; width: 180px;\">"+contentArray[i][0]+"&nbsp;</span>"
      + "<span id=\"ibp_modelref\" style=\"float: left; width: 180px;\">"+contentArray[i][1]+"</span><br/>"
      + "<span id=\"ibp_modelbrands\" style=\"float: none; color:gray;padding-left:10px;\">"+contentArray[i][2]+"</span><br/>"
      + "</span>");
    }
  }
  
  HTML = sb.toString();
  ModelsContainerTbody.innerHTML = HTML;
  
  hide(document.getElementById('IBP_contentDivLimitTop'), (ShowCount < limit));
  hide(document.getElementById('IBP_contentDivLimitBottom'), (ShowCount < limit));
  hide(document.getElementById('IBP_bezig_met_zoeken'), true);
  //hide(document.getElementById('IBP_zoeken'), false); // knop
}



function getSelectedValue(oSelect) {
  if (oSelect.selectedIndex == 0) return "";
  return oSelect.options[oSelect.selectedIndex].innerHTML;
}

function ibp_checkListWhenEnter(e, searchString, brandFilter, limit) {
  var unicode=e.keyCode? e.keyCode : e.charCode;
  //alert("got a key = " + unicode);
  if (unicode == 13) {
    //ibp_checkListIn(searchString, brandFilter, limit, 1);
    ibp_checkList_array(searchString, brandFilter, limit);
  }
}

function ibp_checkListIn(searchString, brandFilter, limit, Delay) {
  clearTimeout(searchDelayID);
  hide(document.getElementById('ibp_wait'), false);
  searchDelayID = setTimeout(function(){ibp_checkList(searchString, brandFilter, limit)}, 1000);
}

function ibp_checkList(searchString, brandFilter, limit) {
//  hide(document.getElementById('ibp_wait'), false);
  try {
    
    if (!limit) limit = 250;
    ShowCount = 0;
	  FreeToSearch = true;
	  var ModelsContainerTbody = document.getElementById('ibp_model_content');
    var ModelRows = ModelsContainerTbody.children;
	  //var ModelRows = document.getElementsByName('ibp_row');
    var contentDivLimit = document.getElementById('IBP_contentDivLimit');
    if (contentDivLimit) contentDivLimit.style.display = 'none';

    brandFilter = brandFilter.toLowerCase();
	  searchString = searchString.toLowerCase().replace(/ +/g, " "); // lowercase and get rid of multiple spaces
	  var ssArray = searchString.split(" ", 5); // split in maximum 5 chunks

    for (var i=0; i< ModelRows.length; i++)
	  {
      if (ShowCount>= limit) {
        found = false;
      } else {
		    var found = true;
        var Spans = ModelRows[i].getElementsByTagName("SPAN");
        if (searchString != "") {
          var modelTitle = Spans[0].innerHTML.toLowerCase(); // ibp_modeltitle
          var modelRef = Spans[1].innerHTML.toLowerCase(); // ibp_modelref
          var brand = Spans[2].innerHTML.toLowerCase(); // ibp_modelbrands
		      for (var j=0; j<ssArray.length; j++) {
            if (brandFilter != "" && brand.indexOf(brandFilter) == -1) { 
              found = false;
              break;
            }
            if (modelTitle.indexOf(ssArray[j]) == -1 && modelRef.indexOf(ssArray[j]) == -1) { 
              found = false;
              break;
            }
          }
        } else {
          // alleen op brand filteren indien gewenst
          var brand = Spans[2].innerHTML.toLowerCase(); // ibp_modelbrands
          if (brandFilter != "" && brand.indexOf(brandFilter) == -1) found = false;    
        }
      }

		  if (found) {
			  hide(ModelRows[i], false);
		  } else {
			  hide(ModelRows[i], true);
		  }
      
      if (shown(ModelRows[i])) ShowCount++; 
	  }
    if (ShowCount>= limit) {
      if (contentDivLimit) contentDivLimit.style.display = '';
    }
    
  } finally {
//    alert("hide again");
    hide(document.getElementById('ibp_wait'), true); 
  }
}

function shown(tag) {
  if (tag != null) {
    return (tag.style.display != 'none');
  }
  return False;
}

function hideIn(tag, flag, Delay) {
  clearTimeout(hideInDelayID);
  hideInDelayID = setTimeout(function(){hide(tag, flag)}, Delay);
}

function hide(tag, flag) {
	if (tag != null) {
		if (flag) {
			tag.style.display = 'none';
		} else {
			tag.style.display = '';
		}
	}
}

function extractFileName(fullPath){
	var m = fullPath.match(/(.*)[\/\\]([^\/\\]+\.\w+)$/);
	return {path: m[1], file: m[2]}
}

function swapId(tagId, imageTagId) {
	var tag = document.getElementById(tagId);
	if (tag != null) {
		if (tag.style.display == 'none') {
			tag.style.display = '';
		} else {
			tag.style.display = 'none';
		}
	}
	var imageTag = document.getElementById(imageTagId);
	if (imageTag != null) {
		//var currentSrc = extractFileName(imageTag.src);
		if (imageTag.getAttribute('fold') == '1') {
			imageTag.src = imageTag.getAttribute('srcUnfolded');
			imageTag.setAttribute('fold', '');
		} else {
			imageTag.src = imageTag.getAttribute('srcFolded');
			imageTag.setAttribute('fold', '1');
		}
	}
}

function setup() {
	contentEntry("Erwin");
	contentEntry("tOm");
	contentEntry("tiM");
	contentEntry("RiChArD");
	contentEntry("lENnart");
	for (var i=0; i<1000; i++) contentEntry("item "+ i);
	//dump();
	//checkList(""); // hides or shows all entries
}

function log(text, clear) {
	var tag = document.getElementById("log");
	if (tag) {
		text = "<xmp>" + text+ "</xmp>";
		if (!clear) {
			text = tag.innerHTML + "" + text;
		}
		tag.innerHTML = text;
	}
}

