
var isOpera = (navigator.userAgent.indexOf('Opera') != -1);
var isIE = (!isOpera && navigator.userAgent.indexOf('MSIE') != -1);

function getClientWidth() {
  if( typeof( window.innerWidth ) == 'number' )
    return window.innerWidth;
  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
    return document.documentElement.clientWidth;
  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
    return document.body.clientHeight;
}
function getClientHeight() {
  if( typeof( window.innerWidth ) == 'number' )
    return window.innerHeight;
  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
    return document.documentElement.clientHeight;
  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
    return document.body.clientHeight;
}


function unHSC(s) { //UnHtmlSpecialChars
  if(s)
  { 
    while(s.indexOf("&quot;")!=-1)
      s = s.replace("&quot;", '"');
    while(s.indexOf("&lt;")!=-1)
      s = s.replace("&lt;", '<');
    while(s.indexOf("&gt;")!=-1)
      s = s.replace("&gt;", '>');
    while(s.indexOf("&amp;")!=-1) // Deze als laatste!
      s = s.replace("&amp;", '&');
  }
  return s;
}
function HSC(s) { //HtmlSpecialChars 
  while(s.indexOf('"')!=-1)
    s = s.replace('"', "&quot;");
  while(s.indexOf('<')!=-1)
    s = s.replace('<', "&lt;");
  while(s.indexOf('>')!=-1)
    s = s.replace('>', "&gt;");

  return s;
}
function moveItem(from, to, item, select) {
  var o = new Option(item.innerHTML, item.value);
  o.className = item.className;
  if(typeof select != 'undefined')
  o.selected = "selected";
  try {
    to.add(o);
  }catch(e) {
    if(to.appendChild)
      to.appendChild(o);
  }
  
  from.remove(item.index);
  return false;
}

function moveSelectedItems(from, to, select) {
  for(i=from.length-1;i>=0;i--)
    if(from[i].selected)
      moveItem(from, to, from[i], select);

  return false;
}

// Move all item from selectlist 'from' to selectlist 'to'
function moveAll(from, to, select) {
  for(i=from.length-1;i>=0;i--)
    moveItem(from, to, from[i], select);
  return false;
}

function splitMoveAll(from, tos, select) {
  for(i=from.length-1;i>=0;i--)
    if(typeof tos[from[i].className] != 'undefined')
      moveItem(from, tos[from[i].className], from[i], select);

  return false;
}

function splitMoveSelectedItems(from, tos, select) {
  for(i=from.length-1;i>=0;i--)
    if(from[i].selected)
      if(typeof tos[from[i].className] != 'undefined')
        moveItem(from, tos[from[i].className], from[i], select);

  return false;
}
function moveSelectedItemUp(el)
{
  if(el && el.selectedIndex > 0)
  {
    i = el.selectedIndex;
    opt = el[i];
    el.remove(i);
    el.add(opt, i-1); 
  }
}
function moveSelectedItemDown(el)
{
  if(el && el.selectedIndex!=(el.length-1))
  {
    i = el.selectedIndex;
    opt = el[i];
    el.remove(i);
    el.add(opt, i+1); 
  }
}

function setHiddenOptionValue(hiddenfield, selectbox) {
  hiddenfield.value = getHiddenOptionValue(selectbox);
}

function getHiddenOptionValue(selectbox) {
  value = "";
  separator = "**";
  for(i=0;i<selectbox.length;i++)
    value += (value!=''?separator:'') + selectbox[i].value;

  return value;
}
xtraWin = null;
function openCenteredWindow(url, width, height) {
  var theHeight = height;
  var theWidth = width;
  var theTop=(screen.height/2)-(theHeight/2);
  var theLeft=(screen.width/2)-(theWidth/2);
  var features= 'height='+theHeight+
               ',width='+theWidth+
               ',top='+theTop+
               ',left='+theLeft+
               ",status=no,toolbar=no,menubar=no,location=no,directories=no,resizable=no,titlebar=no, scrollbars=yes";
  xtraWin = window.open(url, "extra_window", features);
  xtraWin.focus();
  return false;
}
function getById(divID, oDoc) {
  if( document.getElementById )
    return document.getElementById(divID);
  if( document.all )
    return document.all[divID];
  if( !oDoc ) { oDoc = document; }
  if( document.layers ) 
  {
    if( oDoc.layers[divID] ) 
      return oDoc.layers[divID]; 
    else 
    {
      //repeatedly run through all child layers
      for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) 
      {
        //on success, return that layer, else return nothing
        y = getRefToDiv(divID,oDoc.layers[x].document); 
      }
      return y; 
    } 
  }
  alert("(functions.js) : Invalid element: " + id);
  return null;
}
function hoverRow(el, on)
{
  if(on)
    el.className = el.className + "_hover";
  else
    el.className = el.className.replace("_hover", "");
}

function checkStockDivs(el)
{
  if(typeof stock == 'undefined') stock = new Array();
  nr_selected = 0;
  for(i=0;i<el.length;i++)
  {
    k = el[i].value.replace('stock[','').replace(']','');
    cur = !(!stock[k] || stock[k]==''); 

    if(cur && !el[i].selected)
    {
      stock[k] = '';
      tmp = getById('stock_'+k);
      tmp.parentNode.removeChild(tmp);
    }else if(!cur && el[i].selected)
    {
      tmp = document.createElement('div');
      tmp.setAttribute("id", 'stock_'+k);
      tmp.className = 'stock_div';

      tmp2 = document.createElement('div');
      tmp2.innerHTML = k;
      
      tmp3 = document.createElement('input');
      tmp3.className = 'input_small';
      tmp3.setAttribute("type", 'text');
      tmp3.setAttribute("name", 'stock['+k+']');
      tmp3.setAttribute("validate", 'required-numeric');
      tmp3.setAttribute("value", '0');

      tmp.appendChild(tmp2);
      tmp.appendChild(tmp3);
      
      parentEl = getById('stock_divs');

      old = null;
      if(parentEl.childNodes[nr_selected])
        old = parentEl.childNodes[nr_selected];
      parentEl.insertBefore(tmp, old);
      stock[k] = '0';
    }

    if(el[i].selected) nr_selected++;      
  }
}
var editedPage = false;
function checkChanges()
{
  return (typeof editedPage=='undefined' || !editedPage || confirm('Let op: U heeft uw wijzigingen nog niet bewaard!\n\nKlik op "OK" om verder te gaan (niet bewaren) of\nklik op "Annuleren" om de gegevens alsnog te kunnen bewaren.'));
}
function parse_PriceRange()
{   
   text = document.getElementById('price_range').options[document.getElementById('price_range').selectedIndex].value;
   str = new Array();
   if(text != '')
    str = text.split('-');
  
    
   if(typeof str[0] != 'undefined')
    document.getElementById('min_price').value = str[0];
   else
    document.getElementById('min_price').value = "";
   
   if(typeof str[1] != 'undefined')
    document.getElementById('max_price').value = str[1];
   else
    document.getElementById('max_price').value = "";
}

function getFilterString(sep, add)
{
  if(typeof sep =='undefined') sep = '/';
  if(typeof add =='undefined') add = '';
  var x=document.getElementById("filterFormDum");
  
  var info = "";
  for(var i=0;i<x.length;i++)
  {
    if(x.elements[i].name.match("i-") && x.elements[i].value != "")
    {
      if(x.elements[i].name=='i-brand-')
        info += x.elements[i].value + sep;
      else
        info += x.elements[i].name + add + x.elements[i].value + sep;
    }
  }
  return info;
}

function doFilterSubmit()
{
  var x=document.getElementById("filterForm");
  x.action = x.action+getFilterString();
  x.submit();
}

interval = null;
preloadImg = new Array();
lastShop = '';
function addEvent(el, ev, func)
{
  if(el.addEventListener)
  {
    el.addEventListener(ev, func, true);  
  }else if(el.attachEvent)
  {
    el.attachEvent('on'+ev, func2);
  }
}
function validString(s) {
  return encodeURIComponent(s);
}
opening = false;
function changeFilters(url, args, func, form, target)  {
  if(!opening)
  {
    parse_PriceRange();
    initiated = false;
    opening = true;
    async = (typeof async == "undefined");
    request_complete = false;
    try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (e) { try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); }
    catch (e) { try { http_request = new XMLHttpRequest(); }
    catch (e) { try { http_request = window.createRequest(); }
    catch (e) { http_request = false; }}}}
    
    if (!http_request) {
      // Throw error
      alert("Please upgrade browser. XMLHttp object can't be created...");
      return false;
    }
    post_args = getFilterString("&", "=");
    url = site_url + 'm-products/?getFilters=1';
    openedurl = url;

    http_request.open("POST", url, async);
    try {
      http_request.setRequestHeader("Method", "POST "+url+" HTTP/1.1");
      http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader('Connection', 'close');
    }catch(e){alert(e.message);}

    functie = function()
    {
      if ((http_request.readyState == 4 || http_request.readyState == "complete") && !request_complete) 
      { 
        request_complete = true;
        opening = false;
        doChangeFilters(http_request);
      }
    };
    set = false;
    try { http_request.onload             = functie; set = true; }catch(e) {}
    if(!set)
      try { http_request.onreadystatechange = functie; set = true;}catch(e) {}

    http_request.send(post_args);
  }
}
function doChangeFilters(res)
{
  if(res.responseText!='')
  {
    filters = res.responseText.split('****');
    form = document.forms['filterFormDum'];
    for(var i=0;i<filters.length;i++)
    {
      opts = filters[i].split("----");
      orikey = opts[0].substring(0, opts[0].length-1);
      key = 'i-'+orikey+'-';
      elm = form.elements[key];
      if(elm)
      {
        elm.disabled = "";
        selVal = elm[elm.selectedIndex].value;
        while(elm.length > 1)
          elm.remove(1);
  
        if(opts.length > 1)
        {
          for(var a=1;a<opts.length;a++)
          {
            opt = (opts[a]+"").split("++++");
            if(orikey=='type' || orikey=='size' || orikey=='color')
              opt[0] = (""+opt[1]).toLowerCase();
            o = new Option(opt[1], opt[0]);
            if(selVal==opt[0]) o.selected = "selected";
            //alert(opt[0] + "  "+  opt[1]);
            try {
              elm.add(o);
            }catch(e) {
              if(elm.appendChild)
                elm.appendChild(o);
            }
          }
        }
      }
    }
  }
}  

function toggleDiv(el, onoff)
{
  if(el = getById(el))
  {
    if(el.className.indexOf('nodisplay')!=-1)
    {
      el.className = el.className.replace('nodisplay','');
      onoff = true;
    }
    if(typeof onoff == 'undefined')
      onoff = el.style.display=='none';
    el.style.display = (onoff?'block':'none');
  }
}
startScroll = 0;
function doAjaxSearch(v)
{
  if(v!='')
  {
    url = 'stock.php';
    makeRequest(url, 'search=' + escape(v), didSearch);
  }else
  {
    el = getById('searchRes');
    if(el) el.innerHTML = 'Specificeer eerst een zoekterm';
  }
}
function didSearch(result, target, url)
{
  if(result.status==200)
  {
    el = getById('searchRes');
    if(el) el.innerHTML = result.responseText;
  }
}
lastStockRow = null;
function getStockName(row)
{
  tdsFound = 0;
  txt = '';
  for(i=0;i<row.childNodes.length;i++)
  {
    node = row.childNodes[i];
    if(node && node.tagName && (node.tagName.toLowerCase()=='td'))
    {
      tdsFound++;
      if(tdsFound == 3)
      {
        txt = node.innerHTML; 
      }else if(tdsFound == 4)
      {
        return txt + ' - ' + node.innerHTML
      }
    }
  }
  return 'niet gevonden';
}
function setStockRow(row, id)
{
  document.forms['stockForm'].elements['product_id'].value = id;
  el = getById('productName');
  lastStockRow = row;
  if(el)
  {
    el.innerHTML = getStockName(row);
    el.style.color = 'blue';
  }
}


function addStockRows()
{
  p     = m = a = '';

  pid   = document.forms['productForm'].elements['product_id'].value;
  m     = document.forms['productForm'].elements['size'][document.forms['productForm'].elements['size'].selectedIndex].value;
  a     = document.forms['productForm'].elements['nr'].value;
  rac   = document.forms['productForm'].elements['rack'].value;
  rw    = document.forms['productForm'].elements['row'].value;
  com   = document.forms['productForm'].elements['compartment'].value;
  cost  = document.forms['productForm'].elements['cost'].value;
  
  var err = '';
  
  els   = document.getElementsByName('stockRows[size][]');
  for(c=0;c<els.length;c++){
    sel = els[c].selectedIndex;
    if(sel == document.forms['productForm'].elements['size'].selectedIndex){
      err = "Voorraad verhogen voor deze maat bestaat al. Verhoog aub via \"Voorraad\"\n";
    }
  }
  if(m=='')
    err += "Vul een maat in!\n";
  if(a=='')
    err += "Vul een hoeveelheid in!\n";
  if((a*2)/2!=a)
    err += "Het aantal moet wel numeriek zijn!\n";
  
  if(err=='') {
    el = getById('someBody');
	  r = el.insertRow(el.rows.length);
	  
	  c2 = r.insertCell(0);
	  h = document.forms['productForm'].elements['size'].innerHTML;
    h = h.replace(eval('/value=["]?'+m+'["]?/'), 'value="'+m+'" selected="selected"');
    c2.innerHTML = '<select name="stockRows[size][]" onchange="editedPage = true">'+h+'</select>';
	  c3 = r.insertCell(1);
	  c3.innerHTML = "<input type='text' class='input_small' name='stockRows[nr][]' value='"+a+"' />";
	  c4 = r.insertCell(2);
	  c4.innerHTML = "<input type='text' class='input_small' name='stockRows[rack][]' value='"+rac+"' />";
	  c5 = r.insertCell(3);
	  c5.innerHTML = "<input type='text' class='input_small' name='stockRows[compartment][]' value='"+com+"' /><input type='hidden' class='input_small' name='stockRows[stock_id][]' value='' />";
	  c6 = r.insertCell(4);
	  c6.innerHTML = "<input type='text' class='input_small' name='stockRows[row][]' value='"+rw+"' /><input type='hidden' name='stockRows[product][]' value='"+pid+"' />";
	  c7 = r.insertCell(5);
	  c7.innerHTML = "<input type='text' class='input_small' name='stockRows[cost][]' value='"+cost+"' />";
	  c8 = r.insertCell(6);
	  c8align = "right";
	  c8.innerHTML = "<span onclick='removeStockRow(this)' class='link'>verwijder</span>";
	  
	  setStockButtons(el.rows.length>0);
    return false;
    
  } else {
    alert(err);
  }
}

function addStockRow()
{
  p = pid = m = a = '';
  el = getById('productName');
  if(el)
    p = el.innerHTML;

  err = '';
  pid = document.forms['stockForm'].elements['product_id'].value;
  m = document.forms['stockForm'].elements['size'][document.forms['stockForm'].elements['size'].selectedIndex].value;
  a = document.forms['stockForm'].elements['nr'].value;
  rac = document.forms['stockForm'].elements['rack'].value;
  rw = document.forms['stockForm'].elements['row'].value;
  com = document.forms['stockForm'].elements['compartment'].value;
  cost = document.forms['stockForm'].elements['cost'].value;
  if(p=='' || pid=='')
    err += "Selecteer eerst een product!\n";
  if(m=='')
    err += "Vul een maat in!\n";
  if(a=='')
    err += "Vul een hoeveelheid in!\n";
  if((a*2)/2!=a)
    err += "Het aantal moet wel numeriek zijn!\n";
  
  if(err=='')
  {
    el = getById('someBody');
    r = el.insertRow(el.rows.length);
    c1 = r.insertCell(0);
    c1.innerHTML = p + "<input type='hidden' name='stockRows[product][]' value='"+pid+"' />";
    c2 = r.insertCell(1);
    c2.innerHTML = m + "<input type='hidden' name='stockRows[size][]' value='"+m+"' />";
    c3 = r.insertCell(2);
    c3.innerHTML = a + "<input type='hidden' name='stockRows[nr][]' value='"+a+"' />";
    c4 = r.insertCell(3);
    c4.innerHTML = rac + "<input type='hidden' name='stockRows[rack][]' value='"+rac+"' />";
    c5 = r.insertCell(4);
    c5.innerHTML = com + "<input type='hidden' name='stockRows[compartment][]' value='"+com+"' />";
    c6 = r.insertCell(5);
    c6.innerHTML = rw + "<input type='hidden' name='stockRows[row][]' value='"+rw+"' />";
    c7 = r.insertCell(6);
    c7.innerHTML = cost + "<input type='hidden' name='stockRows[cost][]' value='"+cost+"' />";
    c8 = r.insertCell(7);
    c8align = "right";
    c8.innerHTML = "<a href='#' onclick='removeStockRow(this)'>verwijder</a>";
    
    setStockButtons(el.rows.length>0);
  }else
    alert(err);
} 
function doRemoveRow(r)
{
  tr = r;
  while(tr && tr.tagName && tr.tagName.toLowerCase()!='tr')
    tr = tr.parentNode;
  table = tr;
  while(table && table.tagName && table.tagName.toLowerCase()!='tbody')
    table = table.parentNode;
  
  ind = null;
  for(var i=0;i<table.rows.length;i++)
  {
    if(table.rows[i] == tr)
    {
      ind = i;
      break;
    }
  }
  if(ind != null)
    table.deleteRow(ind);
}
function removePriceRow(r)
{
  doRemoveRow(r);

  el = getById('availprices');
  found = false;
  for(var i=0;i<el.childNodes.length;i++)
  {
    if(el.childNodes[i].tagName.toLowerCase()=='tr')
      found = true;
  }
  el2 = getById('noprices');
  el2.style.display = (found?'none':'block');
}
function addPricesRow()
{
  m = document.forms['productForm'].elements['tmp_price[size]'][document.forms['productForm'].elements['tmp_price[size]'].selectedIndex].value;
  mt = (m==''?'Standaard':m);
  //i = document.forms['productForm'].elements['tmp_price[cost]'].value;
  a = document.forms['productForm'].elements['tmp_price[sell]'].value;
  v = document.forms['productForm'].elements['tmp_price[offer]'].value;
  b = document.forms['productForm'].elements['tmp_price[vat]'][document.forms['productForm'].elements['tmp_price[vat]'].selectedIndex].value;
  
  el = getById('availprices');
  row = el.insertRow(el.rows.length);
  c = row.insertCell(0);
  h = document.forms['productForm'].elements['tmp_price[size]'].innerHTML;
  h = h.replace(eval('/value=["]?'+m+'["]?/'), 'value="'+m+'" selected="selected"');
  c.innerHTML = '<select name="prices[size][]" onchange="editedPage = true">'+h+'</select>';
  c = row.insertCell(1);
  //c.innerHTML = '&euro; <input type="text" name="prices[cost][]" error="Kostprijs '+mt+'" validate="required-numeric" class="input_small" value="'+i+'"/>';
  //c = row.insertCell(2);
  c.innerHTML = '&euro; <input type="text" name="prices[sell][]" error="Adviesprijs '+mt+'" validate="required-numeric" class="input_small" value="'+a+'"/>';
  c = row.insertCell(2);
  c.innerHTML = '&euro; <input type="text" name="prices[offer][]" error="Verkoopprijs '+mt+'" validate="required-numeric" class="input_small" value="'+v+'"/>';
  c = row.insertCell(3);
  c.innerHTML = '&nbsp;';
  if((b*2)/2 == b)
  {
    h = document.forms['productForm'].elements['tmp_price[vat]'].innerHTML;
    h = h.replace(eval('/value=["]?'+b+'["]?/'), 'value="'+b+'" selected="selected"');
    c.innerHTML = '<select name="prices[vat][]" onchange="editedPage = true">'+h+'</select>';
  }
  c = row.insertCell(4);
  c.innerHTML = '<a href="#" onclick="removePriceRow(this);return false;">verwijder</a>';

  el2 = getById('noprices');
  el2.style.display = 'none';
}
function removeStockRow(r)
{
  doRemoveRow(r);

  setStockButtons(table.rows.length>0);
}
function setStockButtons(on)
{
  el = getById('someBody');
  if(el) el.style.display = on?'block':'none';
  el = getById('noneBody');
  if(el) el.style.display = on?'none':'block';  
  el = getById('submitButton');
  if(el) el.style.display = on?'block':'none';  
}
  

request_complete = false;
last_url = http_request = null;
opening = false;
function makeRequest(url, args, func, form, target, doload, async)  
{
  if(!opening)
  {
    initiated = false;
    opening = true;
    async = (typeof async == "undefined");
  //  async = true;
    request_complete = false;
    try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (e) { try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); }
    catch (e) { try { http_request = new XMLHttpRequest(); }
    catch (e) { try { http_request = window.createRequest(); }
    catch (e) { http_request = false; }}}}
    
    if (!http_request) {
      // Throw error
      doAlert("Please upgrade browser. XMLHttp object can't be created...");
      return false;
    }
    method = "GET";
    post_args = "ref=1";

      openedurl = url;
      if(url=="") return false;
      if (method == "GET") 
      {
        openedurl += args;
        http_request.open(method, url + "?" + args, async);
      }else {
        http_request.open(method, url, async);
        try {
          http_request.setRequestHeader("Method", "POST "+url+" HTTP/1.1");
          http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
          http_request.setRequestHeader('Connection', 'close');
        }catch(e){doAlert(e.message);}
      }

      if(typeof func == "undefined")
        func = doOpenPagina;

      functie = function()
      {
        if ((http_request.readyState == 4 || http_request.readyState == "complete") && !request_complete) 
        { 
          request_complete = true;
          opening = false;
          func(http_request, target, openedurl);
          window.scrollTo(0,0);
        }
      };
      set = false;
      try { http_request.onload             = functie; set = true; }catch(e) {}
      if(!set)
        try { http_request.onreadystatechange = functie; set = true;}catch(e) {}
  
      http_request.send(post_args);
  //  }  catch(z) { doAlert(z.description);return false; }
  }
}
function changePeriod(el, s, e)
{
  if(typeof s != "undefined" && typeof e != "undefined")
  {
    el1 = getById(s);
    el2 = getById(e);
    val = (""+el[el.selectedIndex].value).split(" ");
    if(val.length == 2)
    {
      el1.value = val[0];
      el2.value = val[1];
    }
  }else
  { 
    a = getById("date_selector");
    b = getById("month_selector");
    a.style.display = (el[el.selectedIndex].value=='p')?"block":"none";
    b.style.display = (el[el.selectedIndex].value=='month')?"block":"none";
  }
}

function submitFilters(parent)
{
  f = document.forms['filterForm'];
  tg = '';
  url = '';
  
  if(parent){
    var cb  = getById(parent);
    cb.checked = false;
    
    range2 = parent.split('_');
    range  = range2[1].split('-');
    
    nChecked  = 0;
    nAantal   = -1;
    area = document.getElementsByTagName('input');
    for(a=0;a<area.length;a++){
      if(area[a].name=='size' && area[a].value >= range[0] && area[a].value <= range[1]){
        if(area[a].checked == true){
          if(area[a].id != cb.id){
            nChecked++;
          }
        }
        nAantal++;
      }
    }
    if(nAantal == nChecked){
      cb.checked = true;
    }
  }
  
  for(i=0;i<f.elements.length;i++)
  {
    el = f.elements[i];
 
    if(el.checked)
    {
      val = el.value;
      if(el.name=='doelgroep')
      {
        tg += (tg!=''?'/':'') + el.value;
        continue;
      }else if(el.name=='size' || el.name=='price' || el.name=='soort' || el.name=='color' && el.value == 'overige')
      {
        val = 'i-'+el.name+'-'+val;
      }
      url += escape(val) + "/";
    }
  }
  if(tg != "")
    url = tg + "/" + url;
  
  if(url=='') url = 'index.php';
  f = document.forms['filterFormDum'];
  f.action = site_url + url;
  f.submit();
}
function setChangeProduct(r, id)
{
  if(true)//!getById("retourProduct_"+id))
  {
    code = r.cells[0].innerHTML;
    brand = r.cells[1].innerHTML;
    desc = r.cells[2].innerHTML;
    size = r.cells[3].innerHTML;
    color = r.cells[4].innerHTML;
    price = r.cells[5].innerHTML;
    
    txt = desc + " - " + code + ", kleur: "+color+", maat: " + size + " t.w.v. "+ price;
    el = getById('prodResultDiv');
    el.innerHTML += '<div id="retourProduct_'+id+'"><input type="checkbox" checked="checked" class="noborder" name="retour[product][]" error="Retour product" validate="ifvalueof(retourType,product,required)" value="'+id+'" />' + txt + '</div>';
  }else
    alert("Product al toegevoegd");
}

function toggleMenu(el, k)
{
  toggleDiv(k);
  c = null;
  for(var i=0;i<el.childNodes.length;i++)
  {
    if(el.childNodes[i].tagName.toLowerCase()=='img')
      c = el.childNodes[i];
  }
  if(c!==null)
  {
    newSrc = c.src.replace("icon_min", "icon_tmp");
    newSrc = newSrc.replace("icon_plus", "icon_min");
    newSrc = newSrc.replace("icon_tmp", "icon_plus");
    c.src = newSrc;
  }
}

function toggleReviews(thisname) 
{
	tr=document.getElementsByTagName('tr')
	for (i=0;i<tr.length;i++)
	{
		if (tr[i].getAttribute(thisname))
		{
			if ( tr[i].style.display=='none' )
			{
				tr[i].style.display = '';
			}
			else 
			{
				tr[i].style.display = 'none';
			}
		}
	}
}

function resetColor(el, syscode)
{
  sizes = getById('maat_'+syscode);
  selsize = sizes[sizes.selectedIndex].value;

  while(sizes.length > 0)
    sizes.remove(0);

  selEl = el[el.selectedIndex];
  if(selEl)
  {
    newsizes = selEl.getAttribute('sizes').split(',');
    for(var i=0;i<newsizes.length;i++)
    {
      var o = new Option(newsizes[i], newsizes[i]);
      if(newsizes[i] == selsize)
        o.selected = "selected";
      try {
        sizes.add(o);
      }catch(e) {
        if(sizes.appendChild)
          sizes.appendChild(o);
      }
    }
  }
  recalcPrice(sizes, syscode);
}
function recalcPrice(el, syscode)
{
  s = el[el.selectedIndex].innerHTML;
  var pr = prDef = null;
  if(PRICES)
  {
    for(var i=0;i<PRICES.length;i++)
    {
      if(PRICES[i][0]==syscode && PRICES[i][1]==s)
        pr = PRICES[i];
      if(PRICES[i][0]==syscode && PRICES[i][1]=='')
        prDef = PRICES[i];
    }
  }
  if(pr == null) pr = prDef;
  prEl = getById('price_' + syscode);
  ofEl = getById('offer_' + syscode);
  if(pr != null)
  {
    prEl.className = (pr[2] != pr[3])?'invalidPrice':'priceTxt';
    ofEl.style.display = (pr[2] != pr[3])?'inline':'none';
    prEl.innerHTML = '&euro; ' + pr[2];
    ofEl.innerHTML = '&euro; ' + pr[3];      
  }
}

function array_length(arr) {  var length = 0; for(val in arr) {   length++; } return length;}


function checkDefaultPrices() /* kopie (+ wijziging) van checkDefaultPrice */
{
  var el  = document.forms['productForm'].elements['prices[size][]'];
  if(el){
	  if(el.selectedIndex === 0){
	    return true;
	  }
	  for(var i=0; i < el.length; i++)
	  {
	    if(el[i].selectedIndex === 0)
	      return true;
	  }
  }
  alert("Voeg ALTIJD een standaard prijs toe aan dit product!");
  return false;
}

function checkDefaultPrice()
{
  el = document.forms['productForm'].elements['prices[size][]'];
  if(el)
  for(var i=0; i < el.length; i++)
  {
    if(el[i].value == '')
      return true;
  }
  alert("Voeg ALTIJD een standaard prijs toe aan dit product!");
  return false;
}


var reviewOptions = ['Slecht','Onvoldoende','Gemiddeld','Goed','Zeer goed'];

function rateStars(val,id,onmouse){
  el = getById('star'+id);
  if(el && el.value == ''){
	  if(onmouse == 'over'){
		  for(x=1;x<=val;x++){
			  var elm = getById('star'+id+'_'+x);
			  if(elm) elm.src = elm.src.replace('star_empty', 'star_full');
		  }
      getById('txtStar_'+id).innerHTML = reviewOptions[(val-1)];
	  } else {
	      var elm = getById('star'+id+'_'+val);
        if(elm) elm.src = elm.src.replace('star_full', 'star_empty');
	      el = getById('txtStar_'+id);
        if(el) el.innerHTML = '';
	  }
  }
}

function hideStars(row){
  el = getById('star'+row);
  if(el && el.value == ''){
		for(x=1;x<=5;x++){
		  var elm = getById('star'+row+'_'+x);
		  if(elm) elm.src = elm.src.replace('star_full', 'star_empty');
		}
	}
}

function clickRate(id,val){
  el = getById('star'+id);
  if(el) el.value = '';
  hideStars(id);
  rateStars(val,id,'over');
  if(el) el.value = val;
  
  el = getById('txtStar_'+id);
  if(el) el.innerHTML = reviewOptions[(val-1)];
}

function validateReview(){
  var error = "";
  for(var x=1;x<=5;x++){
    var el = getById('star'+x).value;
    if(error == ""){
	    if(el < 1 || el > 5){
	      error += "- Beoordeel aub alle onderdelen door op de sterren te klikken\n";
	    }
    }
  }
  var el = getById('review').value;
  if(el.length < 10){
    error += "- Bericht dient minimaal 10 karakters te bevatten\n";
  }
  if(error == ""){
    return true;
  } else {
    alert("Foutmelding:\n"+error);
    return false;
  }
}

function confirmDelete(confirmMessage,url,confirmMessage2){
  if(confirm(confirmMessage)){
    if(confirmMessage2){
	    if(confirm(confirmMessage2)){
			  window.location=url;
			} else {
			  return false;
			}
		} else {
      window.location=url;
		}
  } else {
    return false;
  }
}

function submitForm(confirmMessage,formName){
  if(confirm(confirmMessage)){
      document.forms[formName].submit();
  } else {
    return false;
  }
}

function printGraph(url, type)
{
  r = Math.random();
  df = escape(site_url+url);
  url = site_url+'img/graphs.swf';
  w = '100%';
  h = 250;
  if(type=='wide')
  {
    url = site_url+'img/graphs.swf';
    w = '100%';
    h = 200;
  }else if(type=='small')
  {
    w = '100%';
    h = 200;
  }
  document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="'+w+'" height="'+h+'">');
  document.write('<param name="movie" value="'+url+'?dataFile='+df+'&var='+r+'" />');
  document.write('<param name="quality" value="high" />');
  document.write('<param name="allowTransparency" value="true" />');
  document.write('<param name="wmode" value="opaque" />');
  document.write('<embed src="'+url+'?dataFile='+df+'&var='+r+'" quality="high" allowTransparency="true" wmode="opaque" width="'+w+'" height="'+h+'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
  document.write('</object>');
}

function setImageId(value){
  getById('pic_id').value = value;
}
function openPopup(){
  var id = getById('pic_id').value;
  window.open('popup/?id='+id,'Image','width=540,height=580,toolbar=0,menubar=0,direcoties=0,resizable=0,status=0,scrollbars=0,location=0');
}

function addCombiID(id,filename,titel){
  var openr     = window.opener.document;
  var div       = openr.getElementById('combis');
  var title     = "<h1>"+titel.substr(0,14)+"...</h1>\n";
  var newitem   = "<input type='hidden' value='"+id+"' name='combi_id[]' id='combi_id_"+id+"'>\n";
  var img       = "<img src='"+site_url+"img/image.php?fn=products%2F"+id+"%2F"+filename+"&w=100&h=100&c=1' alt='"+titel+"' />\n";
  var delLink   = "<br /><span onclick='removeCombiID(\""+id+"\");' class='link'>verwijder</span>\n";
  var newnode   = openr.createElement("span");
                  newnode.setAttribute('id','combID_'+id);
                  newnode.setAttribute('className','combiProduct');
                  newnode.innerHTML=newitem+title+img+delLink;
  div.appendChild(newnode);
  window.close();
}

function removeCombiID(id){
  var div   = getById('combis');
  var el    = getById('combID_'+id);
  div.removeChild(el);
}

function clearBorders(){
  var imgs  = document.getElementsByTagName('img');
  for(x=0;x<imgs.length;x++){
    imgs[x].style.border='0px';
    imgs[x].style.padding='3px';
  }
}

function addLoadEvent(func) {   
   var oldonload = window.onload;   
   if (typeof window.onload != 'function') {   
     window.onload = func;   
   } else {   
     window.onload = function() {   
       if (oldonload) {   
         oldonload();   
       }   
       func();   
     }   
   }   
 }
 
 function addUnLoadEvent(func) {   
   var oldonunload = window.onunload;   
   if (typeof window.onunload != 'function') {   
     window.onunload = func;   
   } else {   
     window.onunload = function() {   
       if (oldonunload) {   
         oldonunload();   
       }   
       func();   
     }   
   }   
 }
 
 function ksort(array, sort_flags) {
    // http://kevin.vanzonneveld.net
    // +   original by: GeekFG (http://geekfg.blogspot.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: The examples are correct, this is a new way
    // *     example 1: data = {2: 'van', 3: 'Zonneveld', 1: 'Kevin'};
    // *     example 1: ksort(data);
    // *     results 1: data == {1: 'Kevin', 2: 'van', 3: 'Zonneveld'}
    // *     returns 1: true
 
    var tmp_arr={}, keys=[], sorter, i, key;
 
    switch (sort_flags) {
        case 'SORT_STRING': // compare items as strings
            sorter = function (a, b) {
                return strnatcmp(a, b);
            };
            break;
        case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with  i18n_loc_set_default() as of PHP6)
            sorter = function (a, b) {
                return(a.localeCompare(b));
            };
            break;
        case 'SORT_NUMERIC': // compare items numerically
            sorter = function (a, b) {
                return(a - b);
            };
            break;
        case 'SORT_REGULAR': // compare items normally (don't change types)
        default:
            sorter = function (a, b) {
                if (a > b)
                    return 1;
                if (a < b)
                    return -1;
                return 0;
            };
            break;
    }
 
    // Make a list of key names
    for (key in array) {
        keys.push(key);
    }
 
    keys.sort(sorter);
 
    // Rebuild array with sorted key names
    for (i = 0; i < keys.length; i++) {
        key = keys[i];
        tmp_arr[key] = array[key];
        delete array[key];
    }
    for (i in tmp_arr) {
        array[i] = tmp_arr[i]
    }
 
    return true;
}
 
function openPaasPopup(page) 
{ 
	openCenteredWindow(site_url + "pasen/?simple=1&extra=" + page, 420, 610); 
} 
function paasCode(code) 
{ 
	win = window; 
 	if(window.opener) 
 		win = window.opener; 
 	win.document.location = site_url + "m-bestellingen/?doThis=addCoupon&force=1&nextStep=1&couponcode="+code;
 	if(window.opener) window.close();
} 
 
function openSintPopup(page) 
{ 
	openCenteredWindow(site_url + "sinterklaas/?simple=1&extra=" + page, 420, 610); 
} 
function sintCode(code) 
{ 
	win = window; 
	if(window.opener) 
		win = window.opener; 
	win.document.location = site_url + "m-bestellingen/?doThis=addCoupon&force=1&nextStep=1&couponcode="+code;
	if(window.opener) window.close();
} 
