var IE = document.all ? true : false;
var objAjax3 = getXMLHTTPRequest();
var objAjax = getXMLHTTPRequest();
var MyAjax = getXMLHTTPRequest();

function Mod(X, Y) {
  return X - Math.floor(X / Y) * Y;
}

function switchLanguage(language) {
  $.cookie('language', language, { path: '/' });
  document.location = document.location.href;
}

$(document).ready(function() {
  $('.headerclick').click(function() {
    document.location = '/categorie/didi_collection/green_era_-_new.aspx';
  })

  $.cookie('hasjavascript', 'true', { path: '/' });

  $('#keyword').bind("keyup", function(e) {
    HandleSearch(e);
  });

  // JScript File
  // voor het openhouden van het menu
  var blue = null;

  $("#bestelbon").click(function() {
    location.href = '/shoppingbag.aspx';
  });

  // filter fixen
  $("input[name='optionz']").click(function() {
    $("select").attr("disabled", "disabled");
    $("label").addClass("grey");
    $("select").removeClass("optionchoose");

    var id = $(this).attr("id").replace("radio", "");

    $("#prop" + id).attr("disabled", "");
    $("#lbl" + id).removeClass("grey");
    $("#prop" + id).addClass("optionchoose");
  });

  addEventListenToObj($('#boxPassWord')[0], 'keyup', HandleLogin);

  $(".msgdiv").draggable({
    opacity: 0.70,
    handle: "div#popupTitel",
    containment: "document",
    cursor: "move"
  });

  /*login submit */
  $("#boxPassWord").keyup(function(event) {
    if (event.keyCode == 13) {
      $("#boxButtonLogin").trigger("click");
    }
  });

  //  /* stats */
  //  $.ajax({
  //    url: "/home.aspx?forstats=true",
  //    cache: false,
  //    success: function(data) {
  //      
  //    }
  //  });
  //  /* end stats */

  try {
    // Kleur menu item oranje als het huidige categorie is.
    menulink = window.location.href;

    $("#left ul a").each(function() {
      if (menulink.indexOf(this.href) > -1 || menulink.indexOf(this.href.replace(".aspx", "/overzicht.aspx")) > -1) {
        $(this).css("color", "#B54B3F");
        $(this).parent().parent().show();
      }
    });
  } catch (e) { }
});

function checkForm(id, passid) {
  var username = $("#" + id).val();
  var password = $("#" + passid).val();

  if (username == "" || password == "") {
    alert("U heeft sommige velden niet ingevuld. Controleer uw invoer.");
    return false;
  }
  return true;
}

function elf_proef(bankrekeningnummer) {
  // verwijder alle tekens die geen cijfers zijn
  bankrekeningnummer = bankrekeningnummer.replace(/\D/, "");
  aantal_tekens = bankrekeningnummer.length;
  var som = 0;
  // loop door de 9 cijfers met de 11 proef formule
  for (i = 1; i < 10; i++) {
    getal = bankrekeningnummer.charAt(i - 1);
    som += getal * (10 - i);
  }
  // geef resultaat van check terug
  if (som % 11 == 0 && aantal_tekens == 9) {
    return true
  } else {
    return false
  }
}

/*
* check of username al bestaat
*/
function checkUsername(id, passid) {
  var username = $("#" + id).val();
  var password = $("#" + passid).val();
  sRequestUrl = '/checkusername.aspx?forajax=true&username=' + username;

  if (username != "") {
    $.ajax({
      url: sRequestUrl.replace('%26', '&'),
      cache: false,
      success: function(data) {
        var message = "";
        $("#usernameMessage").removeClass("validationNegative");
        $("#usernameMessage").removeClass("validationPositive");
        if (data == "True") { //email bestaat al
          $("#usernameMessage").addClass("validationNegative");
          $(".btnNormal").attr('disabled', 'disabled');
          message = "Deze gebruikersnaam bestaat al, kies een andere a.u.b.";
        } else { //email is vrij
          $("#usernameMessage").addClass("validationPositive");
          $(".btnNormal").removeAttr('disabled');
          message = "Deze gebruikersnaam is beschikbaar.";
        }
        $("#usernameMessage").html(message);
      }
    });
  }
}

function reloadFilter() {
//  //product page reload filter
//  try {
//    if (typeof filter == 'function') { //check if the filter function is present
//      if ($.cookie('filter') != null) {
//        //disable searchbox in menu, scheeres maatwerk
//        //$(".filler input").hide();

//        var currentpath = "";
//        if ((document.location.pathname).split("/").length > 2) {
//          var length = document.location.pathname.split("/").length;
//          for (var x = 0; x <= length - 1; x++) {
//            currentpath += (document.location.pathname).split("/")[x];
//            if (x == length - 1) {
//              //currentpath += ".aspx"
//            } else {
//              currentpath += "/";
//            }
//          }
//          currentpath = currentpath.replace(".aspx", "");
//        } else {
//          currentpath = "home"
//        }
//        path = $.cookie('filter');
//        //alert(path + " " + currentpath + " " + path.indexOf(currentpath))
//        if (path.indexOf(currentpath) > -1) {

//          sRequestUrl = path + ".aspx?forajax=true&sort=" + sSortMode + "&order=" + sOrderMode;
//          $.ajax({
//            url: sRequestUrl.replace('%26', '&'),
//            cache: false,
//            success: function(data) {
//              DoRefreshProducts(data, path);
//            }
//          });
//        } else {
//          path = document.location.pathname;
//        }
//      } else {
//        path = document.location.pathname;
//      }
//    }
//  } catch (err) { alert(err) }
}

/*
build list of recent viewed products
*/
function setRecentViewed() {
  var cookieVal = $.cookie('recentViewed');
  if (cookieVal != null) {
    currentProducts = $.cookie('recentViewed').split("||");
    //add header
    $("#recent_viewed").append("<div class='blok_header property'>Onlangs door u bekeken</div>");

    if (currentProducts.length > 3) {
      //add arrow up
      $("#recent_viewed").append("<div class='arrow' onclick='moveRecent(-1)'><img src='/Images/arrow_up.jpg'/></div>");
    }

    for (x = currentProducts.length - 1; x >= 0; x--) {
      if (currentProducts[x].length > 0) {
        var productnr = currentProducts[x].split("++")[0];
        var imgurl = (currentProducts[x].split("++")[1]).split("^^")[0];
        var title = currentProducts[x].split("^^")[1];
        var style = ""
        //        if ((x == 0 || x == 1))
        //          style = " style='display:none' "
        $("#recent_viewed").append("<div class='recentProduct' " + style + "id='product" + productnr + "'><div class='border'> \
          <a href='/product/" + productnr + "/" + title + ".aspx'><img src='" + imgurl + "' \
          title='" + title + "'/></a></div><div class='button'>" + title + "</div></div>");
      }
    }
    if (currentProducts.length > 3) {
      $("#recent_viewed").append("<div class='arrow' onclick='moveRecent(1)'><img src='/Images/arrow_down.jpg'/></div>");
      $("#recent_viewed").attr("start", "0");
    }
    moveRecent(0);
  }
}

function moveRecent(direction) {
  var startindex = parseInt($("#recent_viewed").attr("start"));
  if (startindex + direction >= 0 && startindex + direction <= 2) {
    if (direction == -1) { //naar boven
      $("#recent_viewed div.recentProduct:eq(" + (startindex + 2) + ")").hide();
      $("#recent_viewed div.recentProduct:eq(" + (startindex - 1) + ")").fadeIn("fast");
    } else if (direction == 1) { //naar onder
      $("#recent_viewed div.recentProduct:eq(" + (startindex) + ")").hide();
      $("#recent_viewed div.recentProduct:eq(" + (startindex + 3) + ")").fadeIn("fast");
    } else { //eerste render
      $("#recent_viewed div.recentProduct:eq(" + (startindex + 3) + ")").hide();
      $("#recent_viewed div.recentProduct:eq(" + (startindex + 4) + ")").hide();
    }
    $("#recent_viewed").attr("start", startindex + direction);
  }
}

/*
function adds product to recent viewed, if not already there
*/
function addProductToRecentViewed(productnr, imgurl, title) {
  var cookieVal = $.cookie('recentViewed');
  var add = true;
  if (cookieVal == null)
    cookieVal = "";
  if ($.cookie('recentViewed') != null) {
    var currentProducts = new Array();
    currentProducts = $.cookie('recentViewed').split("||");
    for (x in currentProducts) {
      if (currentProducts[x].length > 0 && productnr == (currentProducts[x].toString()).split("++")[0]) { //check of ie al bestaat
        add = false;
        break;
      }
    }
    if (currentProducts.length >= 6 && add) { //een opschuiven
      cookieVal = "";
      for (x in currentProducts) {
        if (x > 0) {
          if (currentProducts[x].length > 0) {
            cookieVal += currentProducts[x] + "||";
          }
        }
      }
    }
  }
  if (add) {
    cookieVal += productnr + "++" + imgurl + "^^" + title + "||";
  }
  $.cookie('recentViewed', cookieVal, { path: '/', expires: 14 });
}

function toggleSubMenu(id) {
  $('#menu_top li.sub ul').css("display", "block");
}

function goTo(url) {
  window.location.href = url;
}

function ChangeAmount(oTxtBox, sMode) {
  oTxtBox = document.getElementById(oTxtBox);

  if (IsNumeric(trim(oTxtBox.value)) == false) { oTxtBox.value = 0; }

  if (sMode == '-') {
    if (oTxtBox.value > 1) { oTxtBox.value--; }
  } else {
    if (oTxtBox.value < 999999) { oTxtBox.value++; }
  }
}

function IsNumeric(sText) {
  var ValidChars = "0123456789";
  var IsNumber = true;
  var Char;

  for (i = 0; i < sText.length && IsNumber == true; i++) {
    Char = sText.charAt(i);
    if (ValidChars.indexOf(Char) == -1) {
      IsNumber = false;
    }
  }
  return IsNumber;

}

function addToMail() {
  //document.location = '/' + $('#domain').val() + '/' + $('#language').val() + '/mailing.aspx?name=' + $('#mailingName').val() + '&email=' + $('#mailingEmail').val();
  document.location = '/mailing.aspx?name=' + $('#mailingName').val() + '&email=' + $('#mailingEmail').val();
}

function ViewPort() {
  this.windowX = (document.documentElement && document.documentElement.clientWidth) || window.innerWidth || self.innerWidth || document.body.clientWidth;
  this.windowY = (document.documentElement && document.documentElement.clientHeight) || window.innerHeight || self.innerHeight || document.body.clientHeight;
  this.scrollX = (document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft;
  this.scrollY = (document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop;
  this.pageX = (document.documentElement && document.documentElement.scrollWidth) ? document.documentElement.scrollWidth : (document.body.scrollWidth > document.body.offsetWidth) ? document.body.scrollWidth : document.body.offsetWidth;
  this.pageY = (document.documentElement && document.documentElement.scrollHeight) ? document.documentElement.scrollHeight : (document.body.scrollHeight > document.body.offsetHeight) ? document.body.scrollHeight : document.body.offsetHeight;
}

function FixFooter() {
  //Change footer pos (IE Only):
  var oCurrentViewport = new ViewPort();
  /*
  var iBannerOffset = $('#header')[0].offsetHeight
  var iMenuOffset = $('#menu')[0].offsetHeight + iBannerOffset; 
  var iMenuRightOffset = $('#right')[0].offsetHeight + iBannerOffset;
  var iProductsOffset = $('#content_locked')[0].offsetHeight + $('.logoDirectshop')[0].offsetHeight + iBannerOffset;
  var iMaxHeight = 0;
  
  //Determine maximum height:
  iMaxHeight = iMenuOffset + 30;
  if(iMenuRightOffset > iMaxHeight){iMaxHeight = iMenuRightOffset; document.title = 'Sized on right menu';}
  if(iProductsOffset > iMaxHeight){iMaxHeight = iProductsOffset - 20; document.title = 'Sized on center content';}
  iMaxHeight += 2;
  
  document.title = 'Sized on left menu (max: ' + iMaxHeight + ') (doc-c: ' + oCurrentViewport.pageY + ')';
  */

  $('#footer').css({ top: oCurrentViewport.pageY + 'px' });
}

function addEventListenToObj(oObj, sEvent, sFunction) {
  if (oObj) {
    if (IE) {
      oObj.attachEvent('on' + sEvent, sFunction);
    } else {
      oObj.addEventListener(sEvent, sFunction, false);
    }
  }
}

function HandleCallMeBack(oEvent) {
  switch (oEvent.keyCode) {
    case 13:
      handlecallmeback();
      break;
  }
  return false;
}

function handlecallmeback() {
  var url = "/callmeback.aspx?name=" + escape($("#callmeback_name").val()) + "&number=" + escape($("#callmeback_number").val()) + "&url=" + window.location.href.toString();
  $.ajax({
    url: url,
    cache: false,
    success: function(data) {
      $("#callmeback_content").html(data)
    }
  });
  return false;
}

function HandleLogin(oEvent) {
  switch (oEvent.keyCode) {
    case 13:
      handlelogin();
      break;
  }
  return false;
}

function handlelogin() {
  var url = "/globallogin.aspx?username=" + escape($("#boxUserName").val()) + "&password=" + escape($("#boxPassWord").val());
  $.ajax({
    url: url,
    cache: false,
    success: function(data) {
      if (data.indexOf("url=") > -1) {
        window.location = "/" + data.split("=")[1]
      } else {
        $("#login_data").html(data);
      }
    }
  });
  return false;
}

function HandleSearch(oEvent) {
  switch (oEvent.keyCode) {
    case 13:
      handlesearch();
      break;
  }
  return false;
}

//function handlesearch() {
//  sSearchWord = escape(trim($('#keyword').val()));
//  if (sSearchWord == "") {
//    sSearchWord = $('#keyword2').val()
//  }
//  window.location = '/zoeken/zoek/' + sSearchWord + '.aspx';
//}
function handlesearch() {
	sSearchWord = $('#keyword').val();
	if (sSearchWord == "")
	  sSearchWord = $('#keyword2').val()
	sSearchWord = encodeSearch($('#keyword').val());
	window.location = '/zoeken/zoek/' + sSearchWord + '.aspx';
}
function encodeSearch(sSearchWord) {
	return trim(sSearchWord.replace(/[^a-zA-Z0-9 ]{1}/g, function (c) { return "{" + c.charCodeAt() + "}"; }));
}
function decodeSearch(sSearchWord) {
	return sSearchWord.replace(/\{([0-9]{1,})\}/g, function (x, c) { return String.fromCharCode(c); });
}

function ChangeAmount(oTxtBox, sMode) {
  oTxtBox = document.getElementById(oTxtBox);

  if (IsNumeric(trim(oTxtBox.value)) == false) { oTxtBox.value = 0; }

  if (sMode == '-') {
    if (oTxtBox.value > 1) { oTxtBox.value--; }
  } else {
    if (oTxtBox.value < 999) { oTxtBox.value++; }
  }
}

function emptySearch() {
  document.getElementById('keyword').value = '';
}

function formatCurrency(strValue) {
  strValue = strValue.toString().replace(/\$|\,/g, '.');
  dblValue = parseFloat(strValue);

  blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
  dblValue = Math.floor(dblValue * 100 + 0.50000000001);
  intCents = dblValue % 100;

  strCents = intCents.toString();
  dblValue = Math.floor(dblValue / 100).toString();
  if (intCents < 10)
    strCents = "0" + strCents;
  for (var i = 0; i < Math.floor((dblValue.length - (1 + i)) / 3); i++)
    dblValue = dblValue.substring(0, dblValue.length - (4 * i + 3)) + '.' +
		dblValue.substring(dblValue.length - (4 * i + 3));
  return (((blnSign) ? '' : '-') + dblValue + ',' + strCents);
}

function getXMLParser(sXmlInput) {
  var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");
  return xmlobject;
}

function getXMLHTTPRequest() {
  var objXML = false;
  try {
    //Object voor firefox compitabele browsers:
    objXML = new XMLHttpRequest();
  }
  catch (err1) {
    //Object voor sommige versies van IE
    try { objXML = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (err2) {
      //Object voor sommige versies van IE
      try { objXML = new ActiveXObject("Microsoft.XMLHTTP"); }
      catch (err3) {
        objXML = false;
      }
    }
  }

  return objXML;
}

function removeFromTender(iProductNo, sMode) {
  var sRequestUrl = '/tender/removefromtender/' + iProductNo + '/.aspx?forajax=true&forxml=true&mode=' + sMode;

  $.ajax({ url: sRequestUrl, cache: false, success: function(data) {
    var sMode = (data.getElementsByTagName("type"))[0].firstChild.data;
    var sProduct = (data.getElementsByTagName("product"))[0].firstChild.data;

    //Actually remove the row:
    oTable = document.getElementById('tbl' + sMode);
    oRow = document.getElementById(sMode + sProduct);

    if (oRow) {
      oRow = oRow.rowIndex;
      oTable.deleteRow(oRow);
    }
  }
  });
}

function HandleTender(iProductNo, sMode) {
  var sRequestUrl = '/tender/addtotender/' + iProductNo;
  var oAmount;
  var iAmount = 1;

  if (sMode == 'koop') { sMode = 1; } else { sMode = 0; }

  oAmount = document.getElementById('txtAmount' + iProductNo);
  if (oAmount) { iAmount = oAmount.value; }

  if ((IsNumeric(iAmount) == true) && (iAmount > 0)) {
    sRequestUrl += '/' + iAmount + '.aspx?forajax=true&forxml=true&mode=' + sMode;

    $.ajax({ url: sRequestUrl, cache: false, success: function(data) {
      PopUpMsg(data);
    }
    });
  } else if (IsNumeric(oAmount.value) == false) {
    alert(document.getElementById('notnumericmsg').value);
  } else if (oAmount.value <= 0) {
    alert(document.getElementById('invalidnumber').value);
  }
}


/*
* functie herschreven, optiegedeelte
*/
function calcPrijs(str) {
  $(".btnNormal").show();
  $("#message").hide();
  var iPrijs = parseFloat($("#price").val().replace(',', '.'));
  $(".optionchoose").each(function(i) {
    var optiemeerprijs = parseFloat(($(this).val()).split("**")[1].replace(',', '.'));
    iPrijs += optiemeerprijs;
  });

  if (iPrijs != "")
    $("#priceshow").html((iPrijs.toFixed(2).toString()).replace('.', ',')); //toonprijs

  //if ($(".optionchoose option:selected").attr("image") != "NULL" && $(".optionchoose option:selected").attr("image") != "") {
    var oldPath = $('#main_image').attr('src').split('/');
    var fileName = null;
    var newPath = '';

    for (i = 0; i < (oldPath.length - 2); i++) {
      newPath += oldPath[i] + '/';
    }

    //Determine new path:
    if (str)
      fileName = str;
    else if ($(".optionchoose option:selected").attr("image") != "NULL" && $(".optionchoose option:selected").attr("image") != "")
      fileName = $(".optionchoose option:selected").attr("image");

    if (fileName) {
      newPath += '300x450/' + fileName;

      $('#main_image').attr({ src: newPath });
    }
  //}
//  
//  var propLangId, propValueId;

//  var propLang, propValue, propValueObj;
//  var iPrijs = parseFloat($("#prijs" + iProductNo).html().replace(',', '.'));
//  //var iPrijs = parseFloat(document.getElementById('prijs' + iProductNo).innerHTML.replace(',', '.'));

//  for (var x = 0; x < aProp.length; x++) {
////    propLangId = aProp[x] + "-" + iProductNo + "-lang";
////    propValId = aProp[x] + "-" + iProductNo;

////    if (document.getElementById(propLangId)) propLang = document.getElementById(propLangId).value;

////    if (document.getElementById(propValId)) {
////      propValueObj = document.getElementById(propValId);
////      iPrijs = iPrijs + parseFloat(propValueObj.options[propValueObj.selectedIndex].value.replace(',', '.'));
//    //    }
//    iPrijs += parseFloat(

//  }
  //document.getElementById('prijstotaal' + iProductNo).innerHTML = formatCurrency(iPrijs.toString());
  }

function abtesting(type)
{
	sRequestUrl = '/measure-abtest.aspx?type=' + type + '&forajax=true';
  $.ajax({ url: sRequestUrl, cache: false, success: function(data) {
    //nothing
		}
	});
}

function HandleCart(iProductNo, iMode, fCallBack, crosssellid, eventsource) {
  var imgCartImage = null;
  var sRequest = '/winkelwagen/';
  var oAmount;
  var iAmount = $('#numberProducts').val();
  if (iAmount == null) {
    iAmount = 1;
  }

  var options = "";
  if (crosssellid == undefined) { //normaal product
    var object = $(".optionchoose")[0];
    if (object != undefined) {
      if (object) {
        var oOption = object.options[object.selectedIndex];
        if ($(oOption).is('.lightgrey')) {
          $("#message").html("Deze maat is op het moment uitverkocht!");
          $(".btnNormal").hide();
          $("#message").show();
          return 0;
        } else {
          $("#message").hide();
          /* get choosen options */
          $(".optionchoose").each(function(i) {
            options += ($(this).val()).split("**")[0] + "**";
          });
          $(".btnNormal").show();
        }
      } else {
        $("#message").html("Dit product is op het moment uitverkocht!");
        $(".btnNormal").hide();
        $("#message").show();
        return;
      }
    }
  } else { //optie gekozen van crosssell
    var object = $("#prop-" + iProductNo)[0];
    if (object != undefined) {
      if (object) {
        var oOption = object.options[object.selectedIndex];
        if ($(oOption).is('.lightgrey')) {
          $("#message").html("Deze maat is op het moment uitverkocht!");
          $("#message").show();
          return 0;
        } else {
        $("#message").hide();
        /* get choosen options */
        $("#prop-" + iProductNo).each(function(i) {
          options += ($(this).val()).split("**")[0] + "**";
        });
        }
      } else {
        $("#message").html("Dit product is op het moment uitverkocht!");
        $("#message").show();
        return;
      }
    }
  }

  /*Now check wich mode we would like to use: 0=rent,1=purchase*/
  if (iMode == 1) {
    sRequest += 'addkoopproduct.aspx';
  } else {
    sRequest += 'addhuurproduct.aspx';
  }

  /*Function sends request to server to update shopcart*/
  if (iMode == 1) {
    oAmount = document.getElementById('txtAmount' + iProductNo);
  } else {
    oAmount = document.getElementById('txtRentalAmount' + iProductNo);
  }

  if (oAmount) { iAmount = oAmount.value; }

  //speed fix
  PopUpMsg(null, $("#main_image").attr("src"));
  if (eventsource) {
    var title = $('td:eq(1) a', $(eventsource).parents('tr')).html();
    $('.boxy-content #popupproductimg').remove();
    $('.boxy-content #popupProductTitel').html('<strong>Titel: </strong>' + title);
  }

  if ((IsNumeric(iAmount) == true) && (iAmount > 0)) {
    sRequest += '?productnr=' + iProductNo + '&aantal=' + iAmount + '&options=' + options + '&forajax=true&forxml=true&forshowproducts=true';

    $.ajax({
      url: sRequest,
      cache: false,
      success: function(data) {
        //PopUpMsg(data, $("#main_image").attr("src"));
        getAantalProducts();
        imgCartImage = $('#shoppingCartImage')[0];
        if (imgCartImage != null) imgCartImage.setAttribute('src', '/images/shopcart_full.gif');

        if (fCallBack) {
          fCallBack();
        }
      }
    });
  } else if (IsNumeric(oAmount.value) == false) {
    alert(document.getElementById('notnumericmsg').value);
  } else if (oAmount.value <= 0) {
    alert(document.getElementById('invalidnumber').value);
  }
  //updateRightMenu();
}

function updateRightMenu() {
  // get right menu to update bestelbon
  $.ajax({
    url: "/getrightmenu.aspx",
    cache: false,
    success: function(data) {
    $("#rm_shopcart").html(data);
      //setRecentViewed();
    }
  });
}

function checkKeyCode(evt) {
  evt = (evt) ? evt : ((event) ? event : null);
  if (evt.keyCode == '13') { return false; }
}

function checkInput(obj) {
  if (!IsNumeric($(obj).val())) {
    $(obj).val('1');
  }
}

function HandleCartCustom(iProductNo, iMode, sProperties) {
  if ($("#txtBoolProps" + iProductNo).val() == "True") {
    var aProp = sProperties.split("**");
    var propLangId, propValueId;
    var propLang, propValue, propValueObj;
    var customOrderLine = "";
    for (var x = 0; x < aProp.length; x++) {
      propLangId = aProp[x] + "-" + iProductNo + "-lang";
      propValId = aProp[x] + "-" + iProductNo;
      if (document.getElementById(propLangId)) {
        propLang = document.getElementById(propLangId).value;
      }
      if (document.getElementById(propValId)) {
        propValueObj = document.getElementById(propValId);
        propValue = propValueObj.options[propValueObj.selectedIndex].text;
      }
      customOrderLine += propLang + ":" + propValue + "^";
    }
    HandleCartInternal(iProductNo, iMode, customOrderLine);
  } else {
    HandleCart(iProductNo, iMode);
  }
}
function HandleCartInternal(iProductNo, iMode, sOrderLine) {
  var imgCartImage = null;
  var sRequest = '/winkelwagen/';
  var oAmount;
  var iAmount = 1;

  /*Now check which mode we would like to use: 0=rent,1=purchase*/
  if (iMode == 1) {
    sRequest += 'addkoopproduct.aspx';
  } else {
    sRequest += 'addhuurproduct.aspx';
  }

  /*Function sends request to server to update shopcart*/
  if (iMode == 1) {
    oAmount = document.getElementById('txtAmount' + iProductNo);
  } else {
    oAmount = document.getElementById('txtRentalAmount' + iProductNo);
  }

  if (oAmount) { iAmount = oAmount.value; }

  if ((IsNumeric(iAmount) == true) && (iAmount > 0)) {
    sRequest += '?productnr=' + iProductNo + '&aantal=' + iAmount + '&forajax=true&forxml=true&forshowproducts=true';
    if (sOrderLine.length > 0) sRequest += '&orderline=' + sOrderLine;

    $.ajax({
      url: sRequest,
      cache: false,
      success: function(data) {
        PopUpMsg(data);
        getAantalProducts();
        imgCartImage = $('#shoppingCartImage')[0];
        if (imgCartImage != null) imgCartImage.setAttribute('src', '/images/shopcart_full.gif');
      }
    });
  } else if (IsNumeric(oAmount.value) == false) {
    alert(document.getElementById('notnumericmsg').value);
  } else if (oAmount.value <= 0) {
    alert(document.getElementById('invalidnumber').value);
  }
}

function setProps(id) {
  var bool = $("#txtBoolProps" + id).val()
  if (bool == "True") {
    $("#divProductVervangen").slideUp()
    $("#txtBoolProps" + id).val("False");
  } else {
    $("#divProductVervangen").slideDown()
    $("#txtBoolProps" + id).val("True");
  }
}

function trim(sInput) {
  return sInput.replace(' ', '');
}

function IsNumeric(sText) {
  var ValidChars = "0123456789";
  var IsNumber = true;
  var Char;

  for (i = 0; i < sText.length && IsNumber == true; i++) {
    Char = sText.charAt(i);
    if (ValidChars.indexOf(Char) == -1) {
      IsNumber = false;
    }
  }
  return IsNumber;
}

function makeNumeric(sText) {
  var ValidChars = "0123456789";
  var sNew = "";
  var Char;

  for (i = 0; i < sText.length; i++) {
    Char = sText.charAt(i);
    if (ValidChars.indexOf(Char) != -1) {
      sNew += sText.charAt(i);
    }
  }
  return sNew;
}

function getAantalProducts() {
  sRequestUrl = '/winkelwagen/getaantalproducts.aspx' + '?forajax=true&forxml=true';
  sRequestUrl = sRequestUrl.replace('%26', '&');

  $.ajax({
    url: sRequestUrl,
    cache: false,
    success: function(data) {
      $('#shopcartaantal').html(data.getElementsByTagName("aantal")[0].firstChild.data);
      $('#shopcartprice').html(data.getElementsByTagName("prijs")[0].firstChild.data);
    }
  });
}

formElements = function(formId, type) {
  var formObject = document.getElementById(formId);
  if (!formObject) return;

  var ele = formObject.getElementsByTagName(type);
  if (ele) return ele;
}

function MergeArray(aArray1, iStart1, aArray2, iStart2) {
  var aResult = new Array();

  for (var i = iStart1; i < aArray1.length; i++) {
    aResult.push(aArray1[i]);
  }

  for (var i = iStart2; i < aArray2.length; i++) {
    aResult.push(aArray2[i]);
  }

  return aResult;
}

function PopUpMsg(sXML, image) {
  var sImage = "";
  var iPageHeight;
  var iPageWidth;
  var sProductImage = "";
  if (image) {
     sProductImage = image.replace("300x450", "90x135");
  }

  // Disable/hidden de selectboxes
  //$("select").css("display", "none");

  //iPageHeight = $('#page')[0].offsetHeight;
 //iPageWidth = $('#page')[0].offsetWidth;

//  if (sXML.getElementsByTagName("imagename")[0].firstChild != undefined) {
//    var img = "";
//    if (image) {
//      img = image.toString().replace("300x450","90x135");
//    } else {
//      img = '/pictures/' + sXML.getElementsByTagName("ImgPartner")[0].firstChild.data + '/90x135/' + sXML.getElementsByTagName("imagename")[0].firstChild.data;
//    }
//    sProductImage = document.getElementById('urlroot').value + img;
//  }

//  var title = "";
//  /*Determine image:*/
//  if (sXML.getElementsByTagName("tender")[0].firstChild.data == 1) {
//    sImgName = 'naarofferte';
//    title = sXML.getElementsByTagName("popuptendertitle")[0].firstChild.data;
//    /*Set popup content:*/
//    $('#popupTitel').html(sXML.getElementsByTagName("popuptendertitle")[0].firstChild.data);
//    $('#popupProductTitel').html("<strong>" + sXML.getElementsByTagName("stitel")[0].firstChild.data + " </strong>" + sXML.getElementsByTagName("title")[0].firstChild.data);
//    $('#popupProductOmschrijving').html("<strong>" + sXML.getElementsByTagName("somschrijving")[0].firstChild.data + " </strong>" + sXML.getElementsByTagName("shortdesc")[0].firstChild.data);
//    $('#popupProductAmount').html("<strong>" + sXML.getElementsByTagName("number")[0].firstChild.data + " </strong>" + +sXML.getElementsByTagName("amount")[0].firstChild.data);
//    $('#popupproductimg').attr({ src: sProductImage });
//    $('#popupcart').val(sXML.getElementsByTagName("popupgototender")[0].firstChild.data);
//  } else {
//    sImgName = 'naarwinkelwagen';

//    var sOmschrijving = "";
//    if (sXML.getElementsByTagName("failed")[0] == undefined) {
//      sOmschrijving = "<strong>" + sXML.getElementsByTagName("somschrijving")[0].firstChild.data + " </strong>" + sXML.getElementsByTagName("shortdesc")[0].firstChild.data
//      /*Set popup content:*/
//      title = sXML.getElementsByTagName("popuptitle")[0].firstChild.data;
//      $('#popupTitel').html(sXML.getElementsByTagName("popuptitle")[0].firstChild.data);
//      $('#popupProductTitel').html("<strong>" + sXML.getElementsByTagName("stitel")[0].firstChild.data + " </strong>" + sXML.getElementsByTagName("title")[0].firstChild.data);
//      $('#popupProductAmount').html("<strong>" + sXML.getElementsByTagName("number")[0].firstChild.data + " </strong>" + +sXML.getElementsByTagName("amount")[0].firstChild.data);
//    } else {
//      $('#popupProductTitel').html('');
//      $('#popupProductAmount').html('');
//      sOmschrijving = sXML.getElementsByTagName("failed")[0].firstChild.data;
//    }
  //  }
  //speed fix
  var title = "";
  title = $(".productright h1").html();
  $('#popupTitel').html("Het product is toegevoegd aan de shoppingbag");
  $('#popupProductTitel').html("<strong>Titel:</strong> " + title);
  $('#popupProductAmount').html("<strong>Aantal:</strong> 1");

 // $('#popupProductOmschrijving').html(sOmschrijving);
  $('#popupproductimg').attr({ src: sProductImage });
  $('#popupcart').html("Naar de winkelwagen");
  $('#popupcontinue').html("Verder");

  /*Popup links:*/
  // $('#popupcart').attr("onclick", "document.location = 'https://www.didiwebshop.nl/" + sXML.getElementsByTagName('target')[0].firstChild.data + ".aspx'");

  fadePage("out", $("#msgdiv").html(), title);
}

function fadePage(sMod, text, title) {
  if (sMod == "out") {
    getBoxy(text, title);
  }
}

function getBoxy(text, title) {
  //modalform = new Boxy(text, { title: title, modal: true, closeable: false, draggable: true });
  modalform = new Boxy(text, { modal: true, closeable: false, draggable: true });
}

function ShowShopCart(sTargetTr) {
  document.location = document.getElementById('urlroot').value + '/' + sTargetTr + '.aspx';
}

function UpdateCrumbCounter() {
  if (document.getElementById('crumbcounter')) { document.getElementById('crumbcounter').innerHTML = '(' + document.getElementById('productcount').value + ')' };
}

document.getElementsByClassName = function(needle) {
  var s, i, r = [], l = 0, e;
  var re = new RegExp('(^|\\s)' + needle + '(\\s|$)');

  if (navigator.userAgent.indexOf('Opera') > -1) {
    s = [document.documentElement || document.body], i = 0;

    do {
      e = s[i];

      while (e) {
        if (e.nodeType == 1) {
          if (e.className && re.test(e.className)) r[l++] = e;

          s[i++] = e.firstChild;
        }
        e = e.nextSibling;
      }
    }
    while (i--);
  }
  else {
    s = document.getElementsByTagName('*'), i = s.length;

    while (i--) {
      try {
        e = s[i];
        if (e.className && re.test(e.className)) r[l++] = e;
      } catch (e) {
      }
    }
  }

  return r;
}

function openWindow(url, title, prop) {
  window.open(url, title, prop);
}

//type 1: dropdown
//type 2: input type=text
function ChangeAmountOfProduct(id, amount, type) {
  if (type == 1) {
    if ((document.getElementById(id).selectedIndex + amount) > -1 && (document.getElementById(id).selectedIndex + amount) < $("#" + id + " option").length) {
      document.getElementById(id).selectedIndex = document.getElementById(id).selectedIndex + amount;
    }
  } else if (type == 2) {
    if ((parseInt($("#" + id).val()) + amount) > 0) {
      $("#" + id).val(parseInt($("#" + id).val()) + amount);
    }
  }
}

function setPaymentType(text,value) {
  if (value == 'op factuur') {
    //afwijkend factuuradres in kunnen vullen, als op factuur gekozen is.
    $("#paymentadress_container").show();
  } else {
    $("#paymentadress_container").hide();
  }
  $("#paymentmethod").html(text);
}

function toggleFacContainer() {
  $("#neworexistingadress").toggle();
}

function toggleNewFacAddress() {
  $("#newadress").toggle();
  $("#fac_existing_addresses").toggle();
  $("#fac_existing_addresses").val("-1");
  
}
function trim(value) {
  value = value.replace(/^\s+/, '');
  value = value.replace(/\s+$/, '');
  return value;
}

function GoogleTrackShoppingCart(step) {
	if (step == 1) {
		_gaq.push(["_trackPageview", "/bezorging.aspx"]);
	} else if (step == 4) {
		_gaq.push(["_trackPageview", "/afronden.aspx"]);
	}
}
