/*
************************************************************
- THE STUFF THAT IS MORE ADVANCED
- IMPORTANT: Uses teaCommerce_Simple.js functionality
- This is the advanced stuff where you can make the nice things
************************************************************
*/
/*
************************************************************
- GLOBAL VARIABLES
************************************************************
*/
var updateCounter = 0,
    submitTimer = null;

/*
************************************************************
- CLEAN UP PAGE FROM NO JAVASCRIPT FALLBACK
************************************************************
*/
jQuery(function () {
  jQuery('#changeCurrency').remove();
});

/*
************************************************************
- SUBSCRIBE TO THE TEA COMMERCE GENERAL EVENTS
************************************************************
*/

/*
We hook on to the onCartUpdated event.
This way we can change the UI everytime the Cart/order has been changed
*/
TeaCommerce.subscribeToOnCartUpdated(function (data) {
  if (data.Order) {
    //Update the carts of the site
    updateMiniCart(data.Order);
    if (jQuery('#cart')[0]) {
      //We only want to update the cart UI if we are on the cart
      updateCartUI(data.Order);
    }
  }
});

/*
We hook on to the onCartUpdating event.
*/
TeaCommerce.subscribeToOnCartUpdating(function () {
  /*
  Set the start time of the submitTimer if it has not yet been set.
  This way we only set it on the first call in a series off calls
  */
  if (submitTimer === null) {
    submitTimer = new Date().getTime();
  }

  //Set the cart to updating mode
  jQuery('#miniCart').addClass('updating');

  //Increment the updatecounter
  updateCounter++;
});

/*
We hook on to the onCartUpdateError event.
*/
TeaCommerce.subscribeToOnCartUpdateError(function (error) {
  /*
  The errortext is thrown right at the user in the
  ugliest possible way.
  It is only called when something went very wrong
  and the server through an exception. This should
  never happen as the system is perfect ;)
  */
  teaCommerceError(error);
  //The update counter is decremented as this call has returned.
  updateCounter--;
});

/*
************************************************************
- SERVICE METHODS
************************************************************
*/

/// <summary>
/// Updates all carts on the page.
/// </summary>
function updateMiniCart(order) {
  /*
  We use a timer to secure that the user will see our update graphics.
  The caching on the server makes the server calls very fast and
  the user might just se the page blink and will not realise that
  something changed.
  It's important for me to say that i have not yet tested this on
  a live shop. It does though work very well on our test setup.
  */
  submitTimerEnd = new Date().getTime() - submitTimer;

  //Check the timeout to see if it took at least half a second
  if (submitTimerEnd < 750) {

    //If the return call was too fast we delay the call for
    window.setTimeout(function () {
      updateMiniCart(order);
    }, submitTimerEnd);
    return false;
  }

  /*
  We keep track of the updates made with a counter.
  This way we only need to update the carts when all
  changes have taken place.
  */
  updateCounter--;
  if (updateCounter < 1) {
    //All calls have returned. Now we can start the update of the UI
    var miniCart = jQuery("#miniCart");

    //If the data holds an order object, we can update the top cart
    if (order) {

      //Information in the order object is used to update det UI
      updateMiniCartUI(miniCart, order);

    }

    //If the Total quantity has changed we may need to change the class of the top cart
    if (!order || order.TotalQuantity < 1) {
      miniCart.addClass('isEmpty');
    } else {
      miniCart.removeClass('isEmpty');
    }

    //All updates have been made and we can now remove the "updating" class on the top cart.
    miniCart.removeClass("updating");

    //the timer is reset and is now ready for the next run
    submitTimer = null;
  }
}

/*
When the currency is changed we need to update product prices
all over the page.
To do this, we need to know what xslt's to run to get the desired html.
We have written the name of the xslt's in each xslt, and can fetch it from the html.
*/
function updatePageUI() {
  /*
  All xslt's that can be invoked in this way have information in a div
  with the class "invokeXSLT". For every one of them we update the UI.
  */
  jQuery('div.invokeXSLT').each(function () {
    var invokeXSLT = jQuery(this),
        parent = invokeXSLT.parent(),
        htmlFromServer = TeaCommerce.invokeXSLT(invokeXSLT.text(), _nodeId,
        {
          umbracoLanguageId: _languageId,
          async: false
        });
    parent.before(htmlFromServer).remove();
  });
}

/*
**************************************************
- JQUERY LIVE EVENTS
**************************************************
*/

/*
When an add to cart button is clicked
*/
jQuery('input.productAddToCart').live('click', function () {
  var jQEle = jQuery(this);

  /*
  If the product allready have a pending add to cart running
  we do not want to make another one.
  in principle you could easily make the call again. This
  is just for demo purposes. You can make as many calls to
  the server as you like.
  */
  if (!jQEle.hasClass('updating')) {
    jQEle.addClass('updating');

    //Get the various elements and variables
    var product = jQEle.closest('.product'),
        quantityInput = product.find('.quantity input'),
        quantity = quantityInput[0] ? quantityInput.val() : 1,
        variant = product.find('.productVariants select'),
        productid = variant[0] ? variant.val() : product.attr('productid'),
        localSubmitTimer = new Date().getTime();

    /*
    Add orderline is called using the Tea Commerce javascript API
    We subscribe to the return events to be able to update the
    css class of the button.
    */
    TeaCommerce.addOrderLine(productid, quantity,
      {
        async: true,
        successfn: function (data) {
          //A timeout is set to show the user that the product has been added
          removeAddButtonUpdate(jQEle, localSubmitTimer)
        },
        errorfn: function (data) {
          //Something went wrong. We should handle it here
          removeAddButtonUpdate(jQEle, localSubmitTimer)
        }
      });
  }
  return false;
});

function removeAddButtonUpdate(jQEle, localSubmitTimer) {
  localSubmitTimerEnd = new Date().getTime() - localSubmitTimer;

  //Check the timeout to see if it took at least half a second
  if (localSubmitTimerEnd < 750) {

    //If the return call was too fast we delay the call for
    window.setTimeout(function () {
      removeAddButtonUpdate(jQEle, localSubmitTimer);
    }, localSubmitTimerEnd);
    return false;
  }
  jQEle.removeClass('updating');
}

/*
PRODUCT VARIANTS CHANGE
*/
jQuery('.productVariants select').live('change', function () {
  //Update a single product in the UI
  updateProduct(jQuery(this).closest('.product'));
});

/*
CURRENCY CHANGE
*/
jQuery('#currency').live('change', function () {
  var newCurrency = jQuery(this).val(),
      productPrices = jQuery('.product .productPrice');
  //Change the currency on the server
  TeaCommerce.setCurrentCurrency(newCurrency,
  {
    async: true,
    successfn: function (data) {
      //In the return we update the pages UI
      updatePageUI();
    }
  });
});

/*
EMPTY CART
*/
jQuery('#emptyCart').live('click', function () {
  TeaCommerce.removeAllOrderLines(
  {
    async: true,
    successfn: function (data) {
      if (jQuery('#cart')[0]) {
        //If we are on the cart page we update the entire cart
        updatePageUI();
      }
    }
  });
  return false;
});
/*
UPDATE ORDERLINE QUANTITY
*/
jQuery('.minus, .plus').live('click', function () {
  var button = jQuery(this),
      orderlineEle = button.closest('.orderLine'),
      productId = orderlineEle.attr('nodeid'),
      changeQuantity = 1;
  //Plus and minus will increase or decrease the quantity by one
  if (button.hasClass('minus')) {
    changeQuantity = -1;
  }
  //Using addOrderLine we count the orderline quantity up or down
  TeaCommerce.addOrderLine(productId, changeQuantity,
  {
    async: true,
    successfn: function (data) {
      //When the server answers we update the specific orderline
      if (data.OrderLinesUpdated[0]) {
        updateOrderLineInUI(orderlineEle, data.OrderLinesUpdated[0]);
      }
    }
  });
  return false;
});
/*
REMOVE ORDERLINE
*/
jQuery('.remove').live('click', function () {
  var button = jQuery(this),
      orderlineEle = button.closest('.orderLine'),
      productId = orderlineEle.attr('nodeid');
  //We use removeOrderLine to remove the orderline on the server
  TeaCommerce.removeOrderLine(productId,
  {
    async: true,
    successfn: function (data) {
      //When the server answers we update the orderline in the UI
      removeOrderLineFromUI(orderlineEle);
    }
  });
  return false;
});

/*
ON QUANTITY BLUR
*/
jQuery('div#cart.stepProgress1 .productQuantity').live('blur', function () {
  var input = jQuery(this),
      orderlineEle = input.closest('.orderLine'),
      productId = orderlineEle.attr('nodeid'),
      newQuantity = parseInt(input.val());
  newQuantity = !isNaN(newQuantity) ? newQuantity : 0;
  if (newQuantity === 0) {
    /*
    On blur we only need to check to see if the quantity is zero
    If this is the case the order line should be removed
    */
    TeaCommerce.removeOrderLine(productId,
    {
      async: true,
      successfn: function (data) {
        //When the server answers we update the orderline in the UI
        removeOrderLineFromUI(orderlineEle);
      }
    });
  }
});
/*
OVERWRITE ORDERLINE QUANTITY
*/
jQuery('div#cart.stepProgress1 .productQuantity').live('keyup', function () {
  var input = jQuery(this),
      orderlineEle = input.closest('.orderLine'),
      productId = orderlineEle.attr('nodeid'),
      newQuantity = parseInt(input.val());
  //If the quantity is more than zero we update it on key up
  if (!isNaN(newQuantity) && newQuantity > 0) {
    //We use removeOrderLine to remove the orderline on the server
    TeaCommerce.overwriteQuantity(productId, newQuantity,
    {
      successfn: function (data) {
        //When the server answers we update the specific orderline
        if (data.OrderLinesUpdated[0]) {
          updateOrderLineInUI(orderlineEle, data.OrderLinesUpdated[0]);
        }
      }
    });
  }
});

/*
STEP 2 NEXT: The next step event on step 2 of the cart
*/
jQuery('#cart.stepProgress2 #next').live("click", function () {
  var validate = sendCustomerInformation();
  if (validate) {
    window.location.href = jQuery(this).attr('link');
  }
  return false;
});

/*
STEP 3 NEXT: The next step event on step 3 of the cart
*/
jQuery('#cart.stepProgress3 #next').live("click", function () {
  var shippingMethod = jQuery('input[name="shippingMethod"]:checked').val(),
      paymentMethod = jQuery('input[name="paymentMethod"]:checked').val();
  /*
  We change the shipping and payment methods of the order on the server.
  This is only necessary because the user desides what methods to use.
  The order will have standard shipping and payment methods depending on
  the selected country.
  */
  if (jQuery('input[name="shippingMethod"]')[0]) {
    if (!shippingMethod) {
      alert('Please choose a shipping method');
      return false;
    }
    TeaCommerce.setShippingMethod(shippingMethod, { async: false });
  }

  if (!paymentMethod) {
    alert('Please choose a payment method');
    return false;
  }
  TeaCommerce.setPaymentMethod(paymentMethod, { async: false });

  window.location.href = jQuery(this).attr('link');
  return false;
});

/*
STEP 4 NEXT: The next step event on step 4 of the cart
*/
jQuery('#cart.stepProgress4 #cartBottom input#next').live("click", function () {
  //We check if the terms has been acceptet
  var jQEle = jQuery('#acceptTermsCheck');
  if (!jQEle.is(':checked')) {
    alert(jQEle.attr('alt'));
    return false;
  } else {
    //TeaCommerce.goToPayment();
  }
  return true;
});

/*
STEP 6 NEXT: The next step event on step 6 of the cart
*/
jQuery('#cart #print').live("click", function () {
  window.print();
  return false;
});

/*
CHANGE COUNTRY
When the country is changed we need to change the
Payment and Shipping options in the UI as they MAY
have changed with the new country.
In THIS setup it is NOT necessary as we let the user
choose these in step 3.
*/
jQuery('div#paymentInformation select#country').live('change', function () {
  /*
  We update the country on the server to let
  it know which payment and shipping methods are available
  */
  TeaCommerce.setCurrentCountry(jQuery(this).val());
});
