$(function() {
  $(".shopSubmit").each(function() {
    // replace button with a link
    var b = $(this);
    var f = b.parents("form");
    var link =  $("<a/>", {
      "class" : "button cartButton",
      "html"  : "<span>+</span>Legg i handlekurv",
      "click" : function() {
        f.submit();
        return false;
      }
    });
    b.replaceWith(link);
  });
  
  // Make the small shopping cart follow when scrolling
  if ($("#shoppingCart").length) {
    var originalCartPosition = $("#shoppingCart").position().top;
        
    $(window).scroll(function() {
      var s = $(window).scrollTop();
      var cartBox = $("#shoppingCart");
      if (s > originalCartPosition) {
        cartBox.css({
          "position" : "fixed",
          "top"      : 0
        });
      } 
      else {
        cartBox.css({
          "position" : "static"
        });
      }
    });
  }
      
  $(".thumb").click(function() {
    var bigImg = $(this).attr("rel");
    $("#mainImage").html("<img src='"+bigImg+"'>");
  });

  
});

//-------------------------------------------------------------------------------------------------
function getUserPriceList() {
  ajaxCall({
    setClass          : 'Shop-Cart',
    setMethod         : 'getUserPriceList',
    setDispatcherPath : 'o2',
    onError           : 'ignore',
    handler           : 'updateUserPrices'
  });
}
//-------------------------------------------------------------------------------------------------
function updateCartContent(templateName) {
  templateName = templateName || "";
  var ajaxTarget = templateName == "bigCart" ? "mainCartContent" : "cartContent";
  
  ajaxCall({
    setClass          : 'Shop-Cart',
    setMethod         : 'updateCartContent',
    setDispatcherPath : 'o2',
    target            : ajaxTarget,
    where             : 'replace',
    onError           : 'ignore',
    setParams         : "templateName="+templateName
  });
}
//-------------------------------------------------------------------------------------------------
function updateUserPrices(response) {
  // Will update the user pricelist if missing
  if (response && response.reloadNeeded) {
    
    // In order to update any products being viewed we need to reload the page
    var url = new String(window.location);
    if ( url.match('/nettbutikk/') ) {
      window.location.reload();
    }
    
  }
}
//-------------------------------------------------------------------------------------------------
function updateVariants(form, selectMenuName) {
  if (!window.firstSelectMenuName) {
    window.firstSelectMenuName = selectMenuName;
  }
  else if (window.firstSelectMenuName && !window.secondSelectMenuName) {
    window.secondSelectMenuName = selectMenuName;
  }
  // called when customer selects variant options
  var productId = form.id.split("_")[1];
  
  if (productId) {
    var variantOptionSelects = document.getElementById('variantOptions_' + productId).getElementsByTagName('SELECT');
    if (variantOptionSelects.length > 0) {
      var optionString = '';
      for (var i = 0; i < variantOptionSelects.length; i++) {
        var object = variantOptionSelects[i];
        if (object.tagName) {
          optionString += object.name + ':' + object.value + ';';
        }
      }
    }
  }
  
  // Update image url if needed
  updateProductImage(productId, optionString);

  // Update variantOptions as well
  updateVariantOptions(productId, optionString);
}
//-------------------------------------------------------------------------------------------------
function updateProductImage(productId, optionString) {
  // Placing this in its own function in an attempt to make things a little easier on the eye
  // We want to get an updated version of the variant options - GR wants to filter the options
  // based on what is selected
  
  // call an update of the variant options via AJAX
  ajaxCall({
    setClass          : "Shop-Cart",
    setMethod         : "updateProductImage",
    setDispatcherPath : "o2",
    handler           : "handleProductImageUpdate",
    onError           : "ignore",
    setParams         : "productId="+productId+"&optionString="+optionString
  });
}
//-------------------------------------------------------------------------------------------------
function updateVariantOptions(productId, optionString) {
  // Placing this in its own function in an attempt to make things a little easier on the eye
  // We want to get an updated version of the variant options - GR wants to filter the options
  // based on what is selected
  
  // call an update of the variant options via AJAX
  ajaxCall({
    setClass          : "Shop-Cart",
    setMethod         : "updateVariantOptions",
    setDispatcherPath : "o2",
    target            : 'variantOptions_' + productId,
    where             : "replace",
    onError           : "ignore",
    setParams         : "productId="+productId+"&optionString="+optionString+"&firstSelectMenuName="+window.firstSelectMenuName+"&secondSelectMenuName="+window.secondSelectMenuName
  });
}
//-------------------------------------------------------------------------------------------------
function resetVariantOptions(productId) {
  // Called when user wants to reset the variant options
  ajaxCall({
    setClass          : "Shop-Cart",
    setMethod         : "resetVariantOptions",
    setDispatcherPath : "o2",
    target            : 'variantOptions_' + productId,
    where             : "replace",
    onError           : "ignore",
    setParams         : "productId="+productId
  });
  
  updateProductImage(productId, '');
}
//-------------------------------------------------------------------------------------------------
function handleProductImageUpdate(response) {
  if (response.imageUrl) {
    // We have a new image url
    if (response.productId) {
      // We know where to place it
      var image = $('#image_' + response.productId);
      if (image.length > 0) {
        image.src = response.imageUrl;
      }
    }
  }
}
//-------------------------------------------------------------------------------------------------
function handleAddProduct(response) {
  if (response.errorMsg) {
    // Display the alert message
    alert(response.errorMsg);
  }
  else {
    if (response.redirectURL) {
      // If we get a redirectURL back after adding a product to the cart we just redirect here
      window.location.href = response.redirectURL;
    }
    else {
      // No URL, we can continue as normal
      // Update the small cart to display changes
      updateCartContent("smallCart");
      $("#shoppingCart").stop(true,true).animate({ backgroundColor: "#fff9b8" }, 200).delay(2000).animate({ backgroundColor: "#e8e7e2" }, 800) //Fade background to yellow, wait 1.2s, fade back
    }
  }
}
//-------------------------------------------------------------------------------------------------
function resetProductForms() {
  // Resets variant options - might be useful if we need to get back to initial values
  var resetButtons = document.getElementsByName('resetButton');
  for (var i = 0; i < resetButtons.length; i++) {
    resetButtons[i].click();
  }
}
//-------------------------------------------------------------------------------------------------
function updateItem(itemId) {
  var amountVal = parseInt($('#amount_'+itemId).val());
  if (amountVal > 0) {
    ajaxCall({
      setClass          : "Shop-Cart",
      setMethod         : "updateItem",
      setDispatcherPath : "o2",
      onError           : "ignore",
      setParams         : "itemId="+itemId+"&amount="+amountVal,
      handler           : "cartHandler"
    });
  }
  else {
    ajaxCall({
      setClass          : "Shop-Cart",
      setMethod         : "removeItem",
      setDispatcherPath : "o2",
      setParams         : "itemId="+itemId,
      target            : "item_"+itemId,
      where             : "delete",
      handler           : "cartHandler"
    });
  }
}
//-------------------------------------------------------------------------------------------------
function cartHandler() {
  updateCartContent("smallCart");
  updateCartContent("bigCart");
}
//-------------------------------------------------------------------------------------------------
function getInstructorProductCategories() {
  ajaxCall({
    setClass          : "Shop-Cart",
    setMethod         : "getInstructorProductCategories",
    setDispatcherPath : "o2",
    handler           : "updateProductCategoryMenu"
  });
}
//-------------------------------------------------------------------------------------------------
function updateProductCategoryMenu(response) {
  if (response.categories) {
    if (document.URL.indexOf("nettbutikk") >= 0) {
      var categories = eval("(" + response.categories + ")");
      var categoryMenu = $($('#header ul.nav')[1]);
      if (categoryMenu.length > 0) {
        for (var index in categories) {
          var category = categories[index];
          categoryMenu.append('<li><a href="' + category.url + '">' + category.title + '</a></li>');
        }
      }
    }
  }
}
//-------------------------------------------------------------------------------------------------
window.onload = function() {
  getInstructorProductCategories();
  getUserPriceList();
};
//-------------------------------------------------------------------------------------------------
function disableButton(element) {
  $(element).hide();
  setTimeout(function() {
      $(element).show();
  }, 1000)
}

