$(document).ready(function()
{
  var imageCount = 1;
  $(".mainImage").each(function()
  {
    if (imageCount == 1){
      $(this).addClass("currentImage");
      }
    else
      $(this).hide();

    imageCount++;
  });

  //beschrijvingen op homepage
  TrimDescriptions();

  //beschrijvingen op categorie pagina
  TrimCategoryDescriptions();

  $("#helpWindow").hide();
  $("#helpWindow").click(function()
  {
    toggleShopHelp();
  })
  
  $("#shopForm").bind("submit",function(){	
	var countrySelect = document.getElementById("country");	
	  if(countrySelect)
	  {
		var selectedOption = countrySelect.options[countrySelect.selectedIndex];
		$("#shippingdestination").attr("value",selectedOption.value);
		selectedOption.value = selectedOption.text;
	  }
  });

  $("#nextStep").click(function()
  {
    var submitButton = document.getElementById("submitShopForm")
    if (submitButton)
    {      
	  submitButton.click();
      return false;
    }
  });

});

var shoppingBagTimeOut;

function updateForm(lang) {
  if (shoppingBagTimeOut != null)
    clearTimeout(shoppingBagTimeOut);
  shoppingBagTimeOut = setTimeout(function() {
    submitFormToStep(2,lang)
   },400);
}

function setCurrentVersion(id, imageId)
{
  document.getElementById('versionId').value = id;


  $(".version").each(function(index)
  {
    this.className = 'version';
  });

  $(".thumbImage").each(function(index)
  {
    this.className = 'thumbImage';
  });

  var selector = $("#version-" + id);
  selector.addClass("selectedVersion");
  selector.find("input").attr("checked", "checked");

  $(".mainImage").each(function()
  {
    if (this.id == "mainImage-" + id)
    {
      $(this).addClass("currentImage");
      $(this).fadeIn(200);
      $("#mainImageLink").attr("href","/images/shop/product/" + id);
	 // alert(id);
    }
    else if (this.className.indexOf("currentImage") > 0)
    {
      $(this).removeClass("currentImage");
      $(this).fadeOut(200);
    }    
  });
  
  $("#thumb-" + id).addClass("selectedThumb");
  $("#mainImage-" + id).fadeIn("slow");
/*
  document.getElementById('mainImageLink').href = 'http://www.rijksmuseum.nl/images/' + imageId;
  document.getElementById('mainImage').src = 'http://www.rijksmuseum.nl/images/' + imageId + '?shop/detail_new';
*/
}

function TrimDescriptions()
{
  $(".categories .description").each(function()
  {
    if (this.clientHeight > 40)
      this.innerHTML = this.innerHTML.substring(0, 50) + "...";
  });
}

function TrimCategoryDescriptions()
{
  $(".products .productdescription").each(function(index)
  {
    if (this.clientHeight > 40)
      this.innerHTML = this.innerHTML.substring(0, 25) + "...";
  });
}

//  <option value="0">Kies bestemming</option>
//  <option value="NL">Nederland</option>
//  <option value="EU_IN">Europa binnen de EU</option>
//  <option value="EU_OUT">Europa buiten de EU</option>
//  <option value="OTHER">Andere bestemming</option>
var shippingCosts = {
  destination: "NL",
  method: "standard",
  finalcost: "370",
  weightL: 0,
  weightN: 0,
  weightV: 0,
  weightK: 0,
  amountL: 0,
  amountN: 0,
  amountV: 0,
  amountK: 0
}

function setShippingMethod(optionValue)
{
  shippingCosts.method = optionValue;
  //calculateAllShippingCosts();
}

function calculateAllShippingCosts()
{
  var totalL = calculateShippingCosts(shippingCosts.weightL, shippingCosts.amountL, 'L');  
  var totalN = calculateShippingCosts(shippingCosts.weightN, shippingCosts.amountN, 'N');  
  var totalV = calculateShippingCosts(shippingCosts.weightV, shippingCosts.amountV, 'V');
  var totalK = calculateShippingCosts(shippingCosts.weightK, shippingCosts.amountK, 'K');

  shippingCosts.finalcost = parseFloat(totalL) + parseFloat(totalN) + parseFloat(totalV) + parseFloat(totalK)

  
  var tidyCost = tidyCosts(shippingCosts.finalcost);
  $("#totalShipping").text(tidyCost);
  $("#shippingSummary").text(tidyCost);
  var totalFinal = parseFloat(tidyCost) + parseFloat($("#subtotalSummary").html());  
  $("#totalFinal").text(tidyCosts(totalFinal * 100));
}

function tidyCosts(cost)
{
  var tidyCost = parseInt(cost) / 100;
  var cents = (tidyCost + "").split('.')[1];
  if (!cents)
    tidyCost += ".00";
  else if (cents.length == 1)
    tidyCost += "0";
  return tidyCost;
}

function calculateShippingCosts(weight, amount, packing)
{
  if (amount == 0)
    return 0;

  var finalcost = 0;

  if (packing == "L")
    weight += 70;
  else if (packing == "N")
    weight += 279;
  else if (packing == "V")
  {
    weight += 462;
  }
  else if (packing == "K")
  {
    weight += 320;
  }

  if (shippingCosts.method == "standard")
  {
    switch (shippingCosts.destination)
    {
      case "NL":
        if (weight < 501)
        {
          if (packing == "L")
            finalcost = 370;
          else
            finalcost = 825;
        }
        else if (weight > 500 && weight < 2001)
        {
          if (packing == "L")
            finalcost = 415;
          else
            finalcost = 825;
        }
        else if (weight > 2000)
          finalcost = 825;
        break;

      case "EU_IN":
        if (weight < 501)
          finalcost = 765;
        else if (weight > 500 && weight < 2001)
          finalcost = 1305;
        else if (weight > 2000)
          finalcost = 2100;
        break;

      case "EU_OUT":
        if (weight < 501)
          finalcost = 1195;
        else if (weight > 500 && weight < 2001)
          finalcost = 2145;
        else if (weight > 2000)
          finalcost = 2650;
        break;

      case "OTHER":
        if (weight < 501)
          finalcost = 1195;
        else if (weight > 500 && weight < 2001)
          finalcost = 2145;
        else if (weight > 2000)
          finalcost = 3570;
        break;

      default:
        break;
    }
  }

  if (shippingCosts.method == "registered")
  {
    switch (shippingCosts.destination)
    {
      case "NL":
        finalcost = 850;
        break;

      case "EU_IN":
        if (weight < 501)
          finalcost = 1460;
        else if (weight > 500 && weight < 2001)
          finalcost = 1460;
        else if (weight > 2000)
          finalcost = 2100;
        break;

      case "EU_OUT":
        if (weight < 501)
          finalcost = 2030;
        else if (weight > 500 && weight < 2001)
          finalcost = 2145;
        else if (weight > 2000)
          finalcost = 2650;
        break;

      case "OTHER":
        if (weight < 501)
          finalcost = 2560;
        else if (weight > 500 && weight < 2001)
          finalcost = 2560;
        else if (weight > 2000)
          finalcost = 3570;
        break;

      default:
        break;
    }
  }
  return finalcost;
}




function handleBillingAddress(checked)
{
  $("#billingAddress input").each(function()
  {
    if (checked)
      $(this).attr("disabled", "disabled");
    else
      $(this).removeAttr("disabled");
  });

  if (checked)
    $("#billingAddress select").attr("disabled", "disabled");
  else
    $("#billingAddress select").removeAttr("disabled");
}

function toggleShopHelp()
{
  var helpWindow = $("#helpWindow")
  if (helpWindow.css("display") == "none")
    helpWindow.show();
  else
    helpWindow.hide();
}

function removeProduct(id,lang)
{
  $("#productCount-" + id).attr("value", "0");
  $("#shopProduct-" + id).hide();
  document.getElementById("shopForm").action = "?step=2&lang=" + lang;
  document.getElementById("shopForm").submit();
}

function submitFormToStep(step, lang)
{
  document.getElementById("shopForm").action = "?step=" + step + "&lang=" + lang;
  $("#shopForm").submit();
}


/*  language strings */
var nl = {
  beginmsg: "De volgende velden zijn niet of niet goed ingevuld:\n\n",
  endmsg: "Gelieve deze velden alsnog in te vullen\n"
};
var en = {
  beginmsg: "Please enter the following fields correctly: \n\n",
  endmsg: "Thank you\n"
};
language = { "nl": nl, "en": en };

function checkGegevens(tform, lang, alertme)
{
  if (!alertme) alertme = true;
  if (!lang) lang = "nl";
  bool = true;
  msg = language[lang]["beginmsg"];
  RegExp.multiline = true;

  if (document.getElementById('removeid'))
  {
    if (document.getElementById('removeid').value != '') return true;
  }

  var msgstrs = {};
  for (var i = 0; i < tform.elements.length; i++)
  {
    var el = tform.elements[i];
    var value = el.value;
    parentname = el.getAttribute('parentname');

    // don't check disabled fields.
    if (el.disabled + "" == "true") continue;

    if (rid = el.getAttribute('referid'))
    {
      label = document.getElementById(rid).innerHTML;
      var reg = new RegExp(/\*/);
      label = label.replace(reg, '');
    } else if (nicename = el.getAttribute('nicename'))
      label = nicename;
    else
      label = el.getAttribute('name');

    var elname = '';

    if (el.getAttribute('required') + "" == "true")
    {
      switch (el.tagName.toLowerCase())
      {
        case 'input':
          if (depid = el.getAttribute('depends'))
          { // dependent
            if (document.getElementById(depid).checked) continue;
          }
          if (el.getAttribute('validate') == "email")
          { // isemail
            if (!isEmail(el.value))
            {
              elname = label;
            }
          }
          if (value.replace(/ /g, '').length < 1)
          {  // uberhaupt iets in staat
            elname = label;
          }
          if (el.getAttribute('type') == 'checkbox')
          { //checkbox moet checked zijn
            if (!el.checked) elname = label;
          }
          break;
        case 'select':
          if (el.value == el.getAttribute("defaultvalue"))
          {
            elname = label;
          }
          break;
        case 'checkbox':
          if (true)
          {
            elname = label;
            //alert(el.checked + ":" + el.value);
          }
          break;

        default:
          break;
      }
    }
    if (el.getAttribute('validate') == "friendcode")
    {
      if (!isFriendCode(el.value))
      {
        elname = label;
      }
    }

    if (elname != '')
    {
      if (!msgstrs[parentname])
        msgstrs[parentname] = [];
      msgstrs[parentname].push(elname);
      bool = false;
    }
  } // end forloop
  // build message
  test = "";

  for (var name in msgstrs)
  {
    // if(name != null)msg += name+":\n";
    for (var i = 0; i < msgstrs[name].length; i++)
    {
      msg += "  - " + msgstrs[name][i] + "\n";
    }
    msg += "\n";
  }
  msg += language[lang]["endmsg"];
  if (!bool && alertme == true)
  {
    //alert(msg);
  }
  return bool;
}

function isEmail(email)
{
  if (email.length > 1)
  {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
  }
  return false;
}
