var wait = false;
function setTreeChildInfoFunctions()
{
	$(".treeChildInfo").hover(
	  function()
	  {
			if (!wait)
			{
				wait = true;
				$(this).parent().parent().next(".treeDiv2").slideDown("slow",function() { wait = false; setHelpPositions(); });
			}
	  },
		function()
		{
			$(this).parent().parent().next(".treeDiv2").slideUp("slow",function() { setHelpPositions(); });
		});
}

function setTreeDivFunctions()
{
	/* Change background on mouseover since div:hover doesn't work in IE */
  $(".treeDiv").hover(
	  function() { $(this).css("background","#c0c000"); },
		function() { $(this).css("background",""); }
	);
}

function key(e)
{
  if (!e) var e = window.event;
  if (e.keyCode) return e.keyCode;
  else if (e.which) return e.which;
}

function keyFunction(key,obj,id,level,type,hasChildren)
{
	$(".treeDiv").css("background","");
	obj.css("background","#c0c000");
	if (key==9) $(".treeDiv2").slideUp("slow");
	if (hasChildren==1)
	{
	  if       ((key==39 || key==40) && obj.next(".treeDiv2").next(".treeDiv3").length==0) expandTree(obj,id,level,type);
	  else if ((key==37 || key==38) && obj.next(".treeDiv2").next(".treeDiv3").length!=0) expandTree(obj,id,level,type);
	}
  if       (key==13 && type=="iso")  addISO(id);
  else if (key==13 && type=="cliq") addCLIQ(id);
  else if (key==73)
	{
		if (obj.next(".treeDiv2").css("display")=="none") obj.next(".treeDiv2").slideDown("slow",function() { setHelpPositions(); });
		else obj.next(".treeDiv2").slideUp("slow",function() { setHelpPositions(); });
	}
}

function keyFunction2(key,id,type)
{
	if (key==46)
	{
		if (type=="iso") delISO(id);
		else if (type=="cliq") delCLIQ(id);
	}
}

function callTreeFunctions()
{
	setTreeChildInfoFunctions();
	setTreeDivFunctions();
}

function expandTree(obj,top,level,treeType)
{
	if (obj.next(".treeDiv2").next(".treeDiv3").length==0)
	{
		var newDiv = $("<div>");
		newDiv.addClass("treeDiv3").load("ajax/editor/isoTree.jsp?top="+top+"&level="+level+"&treeType="+treeType, function() { callTreeFunctions(); setHelpPositions(); });
		obj.next(".treeDiv2").after(newDiv);
		obj.find("img.openicon").attr("src","images/minus.jpg");
	}
	else
	{
		obj.next(".treeDiv2").next(".treeDiv3").remove();
		obj.find("img.openicon").attr("src","images/plus.jpg");
		setHelpPositions();
	}
}

function addISO(id)
{
  var mayAdd = true;
  $(".isocode").each(function() { if ($(this).val()==id) mayAdd = false; });
  if (mayAdd)
  {
    var newInput = $("<input />");
    newInput.addClass("isocode").attr("type","hidden").attr("name","isocode").val(id);
    $("#isoselection").append(newInput);
    loadISOs();
  }
}

function delISO(id)
{
	var delDone = false;
  $(".isocode").each(function()
	{
		if ($(this).val() == id) 
	  {
			$(this).remove();
		  delDone = true;
	  }
	});
  if (delDone) loadISOs();
}

function getISOstring()
{
  var isoString = "";
  $(".isocode").each(function() { isoString += (isoString==""?"?":"&")+"isocode="+$(this).val(); });
	return isoString;
}

function loadISOs()
{
	var isoString = getISOstring();
	$("#isolist").load("ajax/editor/isoLoad.jsp"+isoString, function()
	{
	  loadProductGroups();
	  loadCLIQtree();
	  loadCLIQs();
	});
}

function loadProductGroups()
{
	var isoString = getISOstring();
  var groupString = $("#productgroup").val();
  if (groupString != "" && groupString != undefined) groupString = (isoString==""?"?":"&")+"productgroup="+groupString.join("&productgroup=");
  else groupString = "";
  $("#productgroupcontainer").load("ajax/editor/productgroupLoad.jsp"+isoString+groupString,function() { loadProperties(); });
}

function loadCLIQtree()
{
  var isoString = getISOstring();
	$("#CLIQtree").load("ajax/editor/isoTree.jsp"+isoString+(isoString==""?"?":"&")+"treeType=cliq",function() { setHelpPositions(); });
}

function addCLIQ(id)
{
  var mayAdd = true;
  $(".cliqcode").each(function() { if ($(this).val()==id) mayAdd = false; });
  if (mayAdd)
  {
    var newInput = $("<input />");
    newInput.addClass("cliqcode").attr("type","hidden").attr("name","cliqcode").val(id);
    $("#cliqselection").append(newInput);
    loadCLIQs();
  }
}

function delCLIQ(id)
{
  var delDone = false;
  $(".cliqcode").each(function()
  {
    if ($(this).val()==id) 
    {
      $(this).remove();
      delDone = true;
    }
  });
  if (delDone) loadCLIQs();
}

function loadCLIQs()
{
	var isoString = getISOstring();
	if (isoString==null || isoString==undefined) isoString = "";
  var cliqString = "";
  $(".cliqcode").each(function() { cliqString += (isoString==""&&cliqString==""?"?":"&")+"cliqcode="+$(this).val(); });
  $("#cliqlist").load("ajax/editor/cliqLoad.jsp"+isoString+cliqString,function() { setHelpPositions(); });
}

function priceCheck()
{
  var val = $("#price").val().replace(",",".");
  if (isNaN(val))
  {
    alert("Geen geldig getal ingevoerd!");
    if (val.length>1)
    {
      var count = 0;
      while (count<=val.length)
      {
        if (isNaN(val.substring(0,val.length-count).replace(",","."))) count++;
        else
        {
          $("#price").val(val.substring(0,val.length-count));
          break;
        }
      }
    }
    else $("#price").val("");
  }
}

function checkVAT()
{
	if ($("#priceUnknown:checked").val()!=null)
	{
	  $("#price,#includeVAT,#VAT").val("").attr("disabled","disabled");
		$(".priceField").hide();
	}
	else 
	{
    $("#price,#includeVAT,#VAT").removeAttr("disabled");
		$(".priceField").show();
		if ($("#includeVAT").val()=="inclusief") 
		{
			if ($("#VAT").val()=="onbekend" || $("#VAT").val()=="geen") $("#VAT").val("");
			$("#noVAT").remove();
			$("#unknownVAT").remove();
		}
		else 
		{
			if ($("#noVAT").length==0) 
			{
				var newOption = $("<option>");
				newOption.attr("id","noVAT").val("geen").text("geen");
				$("#VAT").append(newOption);
			}
			if ($("#unknownVAT").length==0) 
			{
				var newOption = $("<option>");
				newOption.attr("id","unknownVAT").val("onbekend").text("onbekend");
				$("#VAT").append(newOption);
			}
		}
	}
}

function loadProperties()
{
  var isoString = getISOstring();
  var groupString = $("#productgroup").val();
  if (groupString!="" && groupString!=undefined) groupString = (isoString==""?"?":"&")+"productgroup="+groupString.join("&productgroup=");
  else groupString = "";
  $("#propertycontainer").load("ajax/editor/propertyLoad.jsp"+isoString+groupString,function() { setPropertyValues(); setHelpPositions(); });
}

function setPropertyValues()
{
  //for each active property search for a hidden property field and if present set the value
  $("#propertycontainer .property").each(function()
  {
    var hiddenProperty = $("#"+($(this).attr("name"))+"-hidden").val();
    if (hiddenProperty!=null && hiddenProperty!=undefined && hiddenProperty!="null")
    {
      if ($(this).attr("type")=="radio" && $(this).val()==hiddenProperty) $(this).attr("checked","checked");
      else if ($(this).attr("type")=="checkbox" && (","+hiddenProperty+",").indexOf(","+$(this).val()+",")>-1) $(this).attr("checked","checked");
      else if ($(this).attr("type")=="text") $(this).val(hiddenProperty);
    };
  });

  // remove all hidden property fields that are no longer active
  $("#hiddenpropertycontainer .hiddenproperty").each(function()
  {
    var removeMe = true;
    var outerid = $(this).attr("id");
    $("#propertycontainer .property").each(function()
    {
      if (outerid.indexOf($(this).attr("name"))!=-1)
      {
        removeMe = false;
        return;
      }
    });
    if (removeMe) $(this).remove();
  });
  checkForErrors();
}

function setHiddenProperties()
{
	$("#hiddenpropertycontainer .hiddenproperty").remove();
	$("#propertycontainer .property").each(function()
	{
		if ($(this).attr("type")=="radio")
		{
			if ($(this).attr("checked"))
			{
				var newInput = $("<input />");
				newInput.attr("type","hidden").attr("id",($(this).attr("name"))+"-hidden").addClass("hiddenproperty").val($(this).val());
				$("#hiddenpropertycontainer").append(newInput);
			}
		}
		else if ($(this).attr("type")=="text")
		{
      var newInput = $("<input />");
      newInput.attr("type","hidden").attr("id",($(this).attr("name"))+"-hidden").addClass("hiddenproperty").val($(this).val());
      $("#hiddenpropertycontainer").append(newInput);
		}
	});
}

function checkForErrors()
{
	$("#errorField").html("");

	var hasErrors = false;

  var id     = $("#id").val();
	var brand  = $("#brand").val();
	var isos   = $(".isocode").val();
	var groups = $("#productgroup").val();
	var type   = $("#model").val();
	var itemNr = $("#itemNumber").val();

  if (brand==null || brand=="" || brand==undefined)
  {
    hasErrors = true;
    var newDiv = $("<div>");
    newDiv.css({ "width":"100%","float":"left","color":"red" }).text("- kies een merk");
    $("#errorField").append(newDiv);
  }
  if (isos==null || isos=="" || isos==undefined)
  {
    hasErrors = true;
    var newDiv = $("<div>");
    newDiv.css({ "width":"100%","float":"left","color":"red" }).text("- kies een ISO code");
    $("#errorField").append(newDiv);
  }
  if (groups==null || groups=="" || groups==undefined)
  {
    hasErrors = true;
    var newDiv = $("<div>");
    newDiv.css({ "width":"100%","float":"left","color":"red" }).text("- kies een soort hulpmiddel");
    $("#errorField").append(newDiv);
  }
  if (type==null || type=="" || type==undefined)
  {
    hasErrors = true;
    var newDiv = $("<div>");
    newDiv.css({ "width":"100%","float":"left","color":"red" }).text("- vul een type/model in");
    $("#errorField").append(newDiv);
  }

	if (!hasErrors)
	{
		$.get("ajax/editor/checkCombination.jsp?id="+id+"&brand="+brand+"&type="+type+"&itemNr="+itemNr+"&productgroup="+groups.join("&productgroup="), function(data)
		{
			if (data=="true") { doAfterCombinationCheck(true); }
			else doAfterCombinationCheck(false);
	  });
	}
}

function doAfterCombinationCheck(combinationExists)
{
	if (combinationExists) 
	{
    var newDiv = $("<div>");
    newDiv.css({ "width":"100%","float":"left","color":"red" }).text("- deze combinatie van merk, soort hulpmiddel, type/model en artikelnummer bestaat al");
    $("#errorField").append(newDiv);
	}
	else
	{
		var newInput = $("<input />");
		newInput.attr("type", "button").val("Opslaan").addClass("purple_button").css({ "width":"120px","float":"right" }).click(function() { $("#saveObj").submit(); });
		$("#errorField").append(newInput);
	}
}

var keyUpDelay = null;
function delayedErrorCheck()
{
  if (keyUpDelay!=null) clearTimeout(keyUpDelay);
  keyUpDelay = setTimeout("checkForErrors()",1000);
}

function setHelpPositions()
{
  $(".helpTextBalloon").each(function()
  {
    var baseID = $(this).attr("id");
    if (baseID!=null && baseID!="")
    {
      var posX = $("#"+baseID+"Position").offset().left;
      var posY = $("#"+baseID+"Position").offset().top;
      $("#"+baseID+"Btn").css({ left:posX-10,top:posY+10 });
      $(this).css({ left:posX+1,top:posY+5 });
    }
  });
}

function printSelection(id)
{
  var content = $("#"+id).html();
  var pwin = window.open("","print_content","width=700,height=700");
  pwin.document.open();
  pwin.document.write("<html><body onload='window.print()' style='text-align:center;'><style>body,div,span,p { font-family:verdana;font-size:12px;color:#000; }</style><div style='width:600px;margin:0 auto;text-align:left;'>"+content+"</div></body></html>");
  pwin.document.close();
  setTimeout(function(){pwin.close();},1000);
}
