/*
************************************************************
- THE STUFF YOU PROBABLY NEED TO CHANGE
- IMPORTANT: Uses teaCommerce_Advanced.js functionality
- This is the simple stuff
************************************************************
*/
/*
When something goes completely wrong on the server
this is where you will know.
*/
function teaCommerceError(error) {
  alert("Cart Error: \n" + error.responseText);
}
/*
When the minicart needs to be updated this method is called.
You get the mini cart as a jQuery object and the order.
Here you update the mini carts html or info.
*/
function updateMiniCartUI(miniCart, order) {
  miniCart.find("#miniCartItemPrice").text(order.TotalPriceWithoutFeesFormatted);
  miniCart.find("#miniCartItemCount").text(order.TotalQuantity);
}
/*
Will update one product element.
We only do this because the variants have different stock
and prices than the main product.
*/
function updateProduct(productEle) {
  var variant = productEle.find('.productVariants select').val(),
      chosenProductId = variant ? variant : productEle.attr('productid'),
      xsltFile = productEle.parent().hasClass('productList') ? 'productList-AjaxProduct.xslt' : 'product.xslt',
      htmlFromServer = TeaCommerce.invokeXSLT(xsltFile, chosenProductId,
      {
        umbracoLanguageId: _languageId,
        async: false
      });
  productEle.before(htmlFromServer).remove();
  initTabbedArea();
}
/*
This is a light weight way to update the total amounts
of the cart. This way we do not have to update the entire UI html
*/ 
function updateCartUI(order) {
  //Update the cart content
  jQuery('#totalExVAT .money div').text(order.TotalPriceWithoutFeesWithoutVATFormatted);
  jQuery('#totalShipping .money div').text(order.Shipping.FeeFormatted);
  jQuery('#totalPayment .money div').text(order.Payment.FeeFormatted);
  jQuery('#totalWithoutVAT .money div').text(order.TotalPriceWithoutVATFormatted);
  jQuery('#totalVAT .money div').text(order.TotalVATWithoutFeesFormatted);
  jQuery('#totalWithVAT .money div').text(order.TotalPriceWithoutFeesFormatted);
  jQuery('#cartTotalQuantity').text(order.TotalQuantity);
  jQuery('#VATPercent').text(order.VATPercent);
  var cart = jQuery('#cart'),
      cartClasses = cart.attr('class').split(' '),
      cartStepClass = '';
  for(i = 0; i < cartClasses.length; i++){
    if(cartClasses[i].indexOf('stepProgress') > -1){
      cartStepClass = cartClasses[i];
      break;
    }
  }
  cart.attr('class', cartStepClass + ' ' + 'items' + order.TotalQuantity);
}
/*
Removes one orderline from the UI
*/
function removeOrderLineFromUI(orderlineEle) {
  /*
  We just remove the orderline tr element
  You could instead do it with a nice animation
  */
  orderlineEle.remove();
}
/*
Updates one orderline in the UI
*/
function updateOrderLineInUI(orderlineEle, orderLine) {
  if (orderLine.Quantity > 0) {
    //The orderline has changed and we need to update the UI
    orderlineEle.find('.productQuantity').val(orderLine.Quantity);
    orderlineEle.find('.productUnitPrice').text(orderLine.UnitPriceWithoutVATFormatted);
    orderlineEle.find('.productTotalPrice').text(orderLine.TotalPriceWithoutVATFormatted);
  } else {
    //The orderline has been removed and we need to do the same in the UI
    removeOrderLineFromUI(orderlineEle);
  }
}

/*
CLICK ON STEP 2 NEXT: The next step event on step 2 of the cart
*/
function sendCustomerInformation() {
  var paymentInformation = jQuery("#paymentInformation"),
      shippingInformation = jQuery("#shippingInformation"),
      country = paymentInformation.find("#country option:selected");

  /*
  We fetch the information from the form and creates
  an object that can be sent to the server as a form
  POST submit
  */
  var formObj = {
    company: paymentInformation.find("#company").val(),
    customerNumber: paymentInformation.find("#customerNumber").val(),
    firstName: paymentInformation.find("#firstName").val(),
    lastName: paymentInformation.find("#lastName").val(),
    city: paymentInformation.find("#city").val(),
    zipCode: paymentInformation.find("#zipCode").val(),
    streetAddress: paymentInformation.find("#streetAddress").val(),
    country: country.text(),
    ISOCountryCode: country.attr("ISOCountryCode"),
    phone: paymentInformation.find("#phone").val(),
    email: paymentInformation.find("#email").val(),
    comments: jQuery("#comments").val(),
    shipping_firstName: shippingInformation.find("#shippingFirstName").val(),
    shipping_lastName: shippingInformation.find("#shippingLastName").val(),
    shipping_streetAddress: shippingInformation.find("#shippingStreetAddress").val(),
    shipping_zipCode: shippingInformation.find("#shippingZipCode").val(),
    shipping_city: shippingInformation.find("#shippingCity").val(),
    shipping_ISOCountryCode: country.attr("ISOCountryCode")
  };

  //Simple validation
  var pageValidateText = '';
  if (formObj.firstName === '') {
    pageValidateText += '\nFörnamn';
  }
  if (formObj.lastName === '') {
    pageValidateText += '\nEfternamn';
  }
  if (formObj.city === '') {
    pageValidateText += '\nOrt';
  }
  if (formObj.zipCode === '') {
    pageValidateText += '\nPostnummer';
  }
  if (formObj.streetAddress === '') {
    pageValidateText += '\nAdress';
  }
  if (formObj.phone === '') {
    pageValidateText += '\nTelefon';
  }
  if (formObj.email === '') {
    pageValidateText += '\nE-post';
  }

  if (pageValidateText != '') {
    //The form does not validate and we pop up the result
    pageValidateText = 'Kom ihåg att fylla i' + pageValidateText;
    alert(pageValidateText);
    return false; //Return false and the browser will not send the user to the next step
  }
  /*
  Update the country from the dropdown value
  */
  TeaCommerce.setCurrentCountry(paymentInformation.find('#country').val(), { async: false });
  /*
  The properties is sent to the server with a syncronous call
  This way we lock the UI and can redirect the user.
  */
  TeaCommerce.updateOrderProperties(formObj, { async: false });
  return true; //Return true and the browser will send the user to the next step
}


jQuery('.product .quantity a').live('click', function(){
  var plusOrMinus = jQuery(this),
      quantityInput = plusOrMinus.siblings('input'),
      val = parseInt(quantityInput.val(), 10);
  if(!val){
    val = 1;
  }else{
    if(plusOrMinus.is('.plusCount')){
      val = val + 1;
    }else{
      val--;
    }
  }
  quantityInput.val(val);
  
  return false;
});

jQuery('.product .quantity input').live('focus', function(){
  this.select();
});





