/*
************************************************************
- 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.Currency.ISOCode + ' ' + order.TotalPriceWithoutFeesFormattedNoSymbol);
  miniCart.find("#miniCartItemCount").text(order.TotalQuantity);
  if(order.TotalQuantity === 0){
    miniCart.find('a').each(function(){
      var jQEle = jQuery(this);
      jQEle.after(jQEle.children()).remove();
    });
  }
}
/*
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();
  removeTest();
}
/*
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').text(order.TotalPriceWithoutFeesWithoutVATFormatted);
  jQuery('#totalShipping .money').text(order.Shipping.FeeFormatted);
  jQuery('#totalPayment .money').text(order.Payment.FeeFormatted);
  jQuery('#totalWithoutVAT .money').text(order.TotalPriceWithoutVATFormatted);
  jQuery('#totalVAT .money').text(order.TotalVATWithoutFeesFormatted);
  jQuery('#totalWithVAT .money').text(order.TotalPriceWithoutFeesFormatted);
  jQuery('#orderQuantity').text(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.UnitPriceFormatted);
    orderlineEle.find('.productTotalPrice').text(orderLine.TotalPriceFormatted);
  } else {
    //The orderline has been removed and we need to do the same in the UI
    removeOrderLineFromUI(orderlineEle);
  }
}

/*
CLICK ON STEP 1 NEXT: The next step event on step 1 of the cart
*/
function sendCustomerInformation() {
  var paymentInformation = jQuery("#paymentInformation"),
      shippingInformation = jQuery("#shippingInformation"),
      otherShippingAddress = jQuery('#otherShippingAddress').is(':checked'),
      country = paymentInformation.find("#country option:selected");
  
  if(!otherShippingAddress){
    jQuery('#shippingDetails input').val('');
  }
  /*
  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(),
    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"),
    telephone: paymentInformation.find("#telephone").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()
  };

  //Simple validation
  var pageValidateText = '';
  if (formObj.firstName === '') {
    pageValidateText += '\nFirst name';
  }
  if (formObj.lastName === '') {
    pageValidateText += '\nLast name';
  }
  if (formObj.city === '') {
    pageValidateText += '\nCity';
  }
  if (formObj.zipCode === '') {
    pageValidateText += '\nZip Code';
  }
  if (formObj.streetAddress === '') {
    pageValidateText += '\nAddress';
  }
  if (formObj.telephone === '') {
    pageValidateText += '\nTelephone';
  }
  if (formObj.email === '') {
    pageValidateText += '\nE-mail';
  }

  if (pageValidateText != '') {
    //The form does not validate and we pop up the result
    pageValidateText = 'Remember to fill out' + pageValidateText;
    alert(pageValidateText);
    return false; //Return false and the browser will not send the user to the next step
  }

  return true; //Return true and the browser will send the user to the next step
}

jQuery(function(){
  var variant1 = jQuery('#variant1');
  if(variant1[0]){
    variant1.children('[selected]').attr('selected', false);
    variant1.children(':first').attr('selected', true);
  }
  removeTest();
  if(jQuery('#cart').is('.stepProgress02')){
    validateDeliveryAndPayment();
  }
  toggleDeliveryTime();

});

function removeTest(){
  if(Tea.Utils.getURLParam('isTest') != ''){
    jQuery('.test').removeClass('test');
    var miniCart = jQuery('#miniCart');
    miniCart.attr('cartlink', miniCart.attr('cartlink') + '?isTest=true');
    jQuery('#miniCart a, #cart a:not(.back)').each(function(){
      this.href += '?isTest=true';
    });
  }
}


function orderLineAdded(data, quantity) {
  var foldDownMessage = jQuery('#foldDownMessage');
  if(foldDownMessage[0]){
    var foldDownMessageContentProductAdded = foldDownMessage.find('#foldDownMessageContentProductAdded'),
        foldDownState = foldDownMessage.attr('foldDownState'),//Can be: foldingOut, foldingIn, out, in
        template = foldDownMessageContentProductAdded.find('.template'),
        orderLine = data.OrderLinesUpdated[0],
        oldOrderLine = foldDownMessageContentProductAdded.find('[orderLineId='+orderLine.Id+']'),
        newOrderLine = oldOrderLine[0] ? updateOrderLineMessageTemplate(orderLine, oldOrderLine, quantity): updateOrderLineMessageTemplate(orderLine, template.clone(), quantity);
    
    if(!oldOrderLine[0]){
      foldDownMessageContentProductAdded.append(newOrderLine);
    }

    openMessage(0, function(){

    });
    
  }
}

function openMessage(extraHeight, fn){
  var foldDownMessage = jQuery('#foldDownMessage'),
      height = foldDownMessage.outerHeight() + 1 + extraHeight;
  foldDownMessage.attr('foldDownState', 'foldingOut');
  foldDownMessage.stop().animate({bottom:-height}, 500, function(){
    foldDownMessage.attr('foldDownState', 'out');
    if(fn){
      fn();
    }
  });
  removeMessage(true);
}

var messageShowTime = 3500, messageTimerEnd;
function removeMessage(newShowTime){

  if (!messageTimerEnd || newShowTime) {
    messageTimerEnd = new Date().getTime() + messageShowTime;
  }
  var timeout = messageTimerEnd - new Date().getTime();
  //Check the timeout to see if it took at least half a second
  if (timeout > 0) {
    
    //If the return call was too fast we delay the call for
    window.setTimeout(function () {
      removeMessage();
    }, timeout);
    return false;
  }
  
  var foldDownMessage = jQuery('#foldDownMessage');
  if(foldDownMessage[0]){
    foldDownMessage.attr('foldDownState', 'foldingIn');
    foldDownMessage.stop().animate({bottom: 0}, 500, function(){
      foldDownMessage.attr('foldDownState', 'in');
      foldDownMessage.find('.clone').remove();
      messageTimerEnd = null;
    });
  }
}

function updateOrderLineMessageTemplate(orderLine, template, quantity){
  template.removeClass('template').addClass('orderLineAddedLine clone');
  template.attr('orderLineId', orderLine.Id);
  template.find('.image').attr('src', '/umbraco/ImageGen.ashx?width=93&image=' + getPropertyValue('productImage',orderLine.Properties));
  template.find('.quantity').text(orderLine.Quantity);
  template.find('.price').text(orderLine.TotalPriceFormattedNoSymbol);
  return template;
}

function getPropertyValue(alias, properties){
  var value = '';
  for(i = 0; i < properties.length; i++){
    if(properties[i].Alias === alias){
      value = properties[i].Value;
    }
  }
  return value;
}

jQuery('#shippingMethod, #paymentMethod').live('change', function(){
  validateDeliveryAndPayment();
});
       
function validateDeliveryAndPayment(){
  var shippingMethod = jQuery('#shippingMethod'),
      paymentMethod = jQuery('#paymentMethod');
  
  if(shippingMethod.val() === '2' && paymentMethod.val() === '2'){
    paymentMethod.val('1');
  }
  toggleDeliveryTime();
}

function toggleDeliveryTime() {
  var shippingMethod = jQuery('select#shippingMethod');
  if(shippingMethod[0]){
    var deliveryTime = jQuery('.deliveryTime');
    
    if(shippingMethod.val() === '2'){
      deliveryTime.css({display:'block'});
    }else{
      deliveryTime.css({display:'none'});
    }
  }
}

