var IE = document.all ? true : false;
var objAjax3 = getXMLHTTPRequest();
var objAjax = getXMLHTTPRequest();
var MyAjax = getXMLHTTPRequest();

function checkForm() {
  //voorwaarden gelezen?
  if (!$("#chkVoorwaarden").is(':checked')) {
    alert("U moet akkoord gaan met de algemene voorwaarden voordat uw verder kunt gaan.");
    return false;
  } else {
    //$("#orderplaatsen").attr('disabled', 'disabled');
    $("#orderplaatsen").hide();
  }
  return true;
}

function Mod(X, Y) {
  return X - Math.floor(X / Y) * Y;
}

$(document).ready(function() {
  $.cookie('hasjavascript', 'true', { path: '/' });
  addEventListenToObj($('#keyword')[0], 'keyup', HandleSearch);
  //$('#focusdiv').fadeTo(0, 0);

  $("#tblInline tbody tr").mouseover(function() {
    $(this).css("background-color", "#CEDEEA");
  }).mouseout(function() {
    $(this).css("background-color", "#FFFFFF");
  });

  // Disable muis op afbeeldingen
  $("img").each(function() {
    this.oncontextmenu = function() {
      return false;
    }
  });

  // Controleer of unit uitgeschoven moet worden.
  if (gup('v') == 'y') {
    var productnr = gup('p');
    $("#lichtbron_vervangen").hide();
    $("#divProductVervangen").slideDown();
    $("#txtBoolProps" + productnr).val("True");
    $("#txtAmount" + productnr).val(gup('a'));
    AjaxCalcPrice(productnr);
  }

  // Kleur menu item oranje als het huidige categorie is.
  menulink = window.location.href;
  if (window.location.href.indexOf("product") > -1) {
    // Gaat om een product, krijg 2de link van kruimel.
    menulink = $(".crumbHead a")[1].href;
  }

  $("#dsMenu a").each(function() {
    if (menulink.indexOf(this.href) > -1) {
      $(this).css("color", "#f98e26");
    }
  });

  try {
    onloadglobal();
  }
  catch (err) {
    //alert(err);
  }

  try {
    UpdateCrumbCounter();
  }
  catch (err) {
    //gewoon niks uitvoeren
  }

  $(".msgdiv").draggable({
    opacity: 0.70,
    handle: "div#popupTitel",
    containment: "document",
    cursor: "move"
  });
});

function gup(name) {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if (results == null)
    return "";
  else
    return results[1];
}
var timeoutID;
function AjaxCalcPrice(productnr) {
  window.clearTimeout(timeoutID);
  timeoutID = setTimeout(('AjaxCalcPriceNow("' + productnr + '");'), 1000);
}
function AjaxCalcPriceNow(productnr) {
  var aantal = $('#txtAmount' + productnr).val();

  if (aantal == '') {
    aantal = 0;
  }
  //$('#txtAmount' + productnr).attr("disabled", true)
  $('#prijstotaal' + productnr).html('<b>Updating..</b>');
  $.ajax({
    type: "GET",
    url: "/product/getCost.aspx",
    data: "product=" + productnr + "&aantal=" + aantal + "&forajax=true&forxml=true",
    success: function(returnValue) {

      var price = $(returnValue).find('prijs').text()

      //$('#txtAmount' + productnr).attr("disabled", false)
      $('#prijstotaal' + productnr).html('&euro; ' + price);
    }
  });
}

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;

}

window.onunload = function() {
  try {
    onunloadglobal();
  } catch (err) {
    //Do nothing
  }
}

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 HandleSearch(oEvent) {
  switch (oEvent.keyCode) {
    case 13:
      handlesearch();
      break;
  }
}

function handlesearch() {
  var sSearchWord = escape($('#keyword').val()).replace("/", "_");
  window.location = '/search/search/' + sSearchWord + '.aspx';
}

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);
  }
}

function calcPrijs(iProductNo, sProperties) {
  var aProp = sProperties.split("**");
  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(',', '.'));
    }

  }
  document.getElementById('prijstotaal' + iProductNo).innerHTML = formatCurrency(iPrijs.toString());
}

function HandleCart(iProductNo, iMode, fCallBack) {
  var imgCartImage = null;
  var sRequest = '/winkelwagen/';
  var oAmount;
  var iAmount = 1;

  /*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; }

  if ((IsNumeric(iAmount) == true) && (iAmount > 0)) {
    sRequest += '?productnr=' + iProductNo + '&aantal=' + iAmount + '&forajax=true&forxml=true&forshowproducts=true';

    $.ajax({
      url: sRequest,
      cache: false,
      success: function(data) {
        PopUpMsg(data);
        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);
  }
}

function HandleCartCustom(iProductNo, iMode, sProperties) {
  if ($("#txtBoolProps" + iProductNo).val() == "True") {
    if ($("#txtTypeBundel").val() == "Contact") {
      location.href = "/contact.aspx?product=" + iProductNo;
      return;
    }
    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") {
    $("#lichtbron_vervangen").show()
    $("#divProductVervangen").slideUp()
    $("#txtBoolProps" + id).val("False");
  } else {
    $("#lichtbron_vervangen").hide()
    $("#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);
    }
  }
  //if (sNew == "") sNew = "1";
  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) {
  var sImage = "";
  var iPageHeight;
  var iPageWidth;
  var sProductImage = '';

  // Disable/hidden de selectboxes
  $("select").css("display", "none");

  iPageHeight = $('#page')[0].offsetHeight;
  iPageWidth = $('#page')[0].offsetWidth;
  sProductImage = document.getElementById('urlroot').value + '/pictures/' + sXML.getElementsByTagName("ImgPartner")[0].firstChild.data + '/90x90/' + sXML.getElementsByTagName("newimage")[0].firstChild.data;

  /*Determine image:*/
  if (sXML.getElementsByTagName("tender")[0].firstChild.data == 1) {
    sImgName = 'naarofferte';
    /*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';

    /*Set popup content:*/
    $('#popupTitel').html(sXML.getElementsByTagName("popuptitle")[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("popupgotoshopcart")[0].firstChild.data);
  }

  /*Popup links:*/
  $('#popupcart').click(function() {
    document.location = '/' + sXML.getElementsByTagName("target")[0].firstChild.data + '.aspx'
  });

  $('#popupcontinue').click(function() {
    $("select").css("display", "inline");
    $('#msgdiv').css({ display: 'none' });
    fadePage("in");
    gCartClosed = true; // for callback
  });

  /*Popup div */
  $('#focusdiv').css({ display: 'inline', height: iPageHeight, width: iPageWidth });
  $('#msgdiv').css({ display: 'inline' });
  fadePage("out");
  gCartClosed = false; // for callback
}

function fadePage(sMod) {
  if (sMod == "out") {
    $('#left').fadeTo(300, 0.33, checkStatus);
    $('#right').fadeTo(300, 0.33, checkStatus);
    $('#header').fadeTo(300, 0.33, checkStatus);
    $('#footer').fadeTo(300, 0.33, checkStatus);
    $('#headerLinks').fadeTo(300, 0.33, checkStatus);
  } else {
    $('#left').css({ opacity: '1' });
    $('#right').css({ opacity: '1' });
    $('#header').css({ opacity: '1' });
    $('#footer').css({ opacity: '1' });
    $('#headerLinks').css({ opacity: '1' });
  }
}
var gCartClosed = false;
function checkStatus() {
  if (gCartClosed)
    fadePage("in");
}

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);
}
