/**
 * basket.js
 *
 * @author Paul Horton <phorton@doc-net.com>
 * @author James Jaber <jjaber@doc-net.com>
 * @author Adam Tuffley <atuffley@doc-net.com>
 * @copyright Doctor Net Limited &copy; 2008/2009
 * @package WebSite.WebSite
 */

$(document).ready(function() {
   bol_ajax_fired = false;
   bind_extended_warranty_checkboxes();
});

function bind_extended_warranty_checkboxes() {
   $('.warranty_checkbox').unbind();
   $('.warranty_checkbox').change(function() {
      if($(this).attr('checked')) {
         add_warranty_to_basket_line($(this).val());
      } else {
         remove_warranty_from_basket_line($(this).val());
      }
   });
}

function add_promo_code(){
   if ($('#promocode').val() != ""){
      //$('#hidden_update_button').click();
      var str_promotion_code = $('#promocode').val();
      bol_ajax_fired = true;
      $.ajax({
         async: true,
         type: "POST",
         url: "/ajax-basket/add-promotion-code",
         data: "str_promotion_code=" + str_promotion_code,
         success: process_basket_update_response,
         error: function (obj, str, exc){
            alert(str);
         }
      })
   } else {
      alert ('Please enter a Gear Code');
   }
}

function remove_promo_code(){
   //$('#hidden_update_button').click();
   bol_ajax_fired = true;
   $.ajax({
      async: true,
      type: "POST",
      url: "/ajax-basket/remove-promotion-code",
      success: process_basket_update_response,
      error: function (obj, str, exc){
         alert(str);
      }
   })
}

/**
 * Removed a line from the basket via Ajax.
 *
 * @param Integer int_basket_line_id
 */
function basket_remove_line(int_basket_line_id) {
   //$('#hidden_update_button').click();
   bol_ajax_fired = true;
   $.ajax({
      async: true,
      type: "POST",
      url: "/ajax-basket/remove-line",
      data: "int_removing_basket_line_id=" + int_basket_line_id,
      success: process_basket_update_response,
      error: function(obj, str, exc) {
         // Full on error
         window.location.href = "/basket/show";
      }
   });
}

function save_as_quotation() {
   //$('#hidden_update_button').click();
   var str_html_message = "";
   bol_ajax_fired = true;
   $.ajax({
      async: true,
      type: "POST",
      url: "/ajax-basket/save-basket-as-quotation",
      data: "",
      success: function(obj_response) {
         if($('response', obj_response).attr('success') == 'true') {
            alert("Your basket has successfully been save as a quotation with reference number " + $('str_quotation_number', obj_response).text());
         } else {
            alert("We are sorry, but there was a problem whilst saving your basket as a quotation.\n\nPlease contact us on 0871 309 0800 for assistance.");
         }
         $.fancybox.close();
      },
      error: function(obj, str, exc) {
         alert("We are sorry, but there was a problem whilst saving your basket as a quotation.\n\nPlease contact us on 0871 309 0800 for assistance.");
         $.fancybox.close();
      }
   });
}

/**
 * Sets the requested delivery date via Ajax.
 *
 * @param String str_delivery_date
 */
function set_delivery_date(str_delivery_date) {
   //$('#hidden_update_button').click();
   bol_ajax_fired = true;
   $.ajax({
      async: true,
      type: "POST",
      url: "/ajax-basket/set-delivery-date",
      data: "str_delivery_date=" + str_delivery_date,
      success: process_basket_update_response,
      error: function(obj, str, exc) {
         // Full on error
         window.location.href = "/basket/show";
      }
   });
}

/**
 * Updates the quantity of a product in the basket via Ajax.
 *
 * @param Integer int_product_id
 * @param Object obj_quantity
 */
function basket_update_quantity(int_product_id, obj_quantity) {
   //$('#hidden_update_button').click();
   if (obj_quantity.value == 0) {
      int_basket_line_id = parseInt(obj_quantity.id.substr(9));
      bol_ajax_fired = true;
      $.ajax({
         async: true,
         type: "POST",
         url: "/ajax-basket/remove-line",
         data: "int_removing_basket_line_id=" + int_basket_line_id,
         success: process_basket_update_response,
         error: function(obj, str, exc) {
            // Full on error
            window.location.href = "/basket/show";
         }
      });
   } else {
      bol_ajax_fired = true;
      $.ajax({
         async: true,
         type: "POST",
         url: "/ajax-basket/update-quantity",
         data: "int_product_id=" + int_product_id + "&int_quantity=" + obj_quantity.value,
         success: process_basket_update_response,
         error: function(obj, str, exc) {
            // Full on error
            window.location.href = "/basket/show";
         }
      });
   }
}

/**
 * Updates the service category via Ajax.
 *
 */
function basket_update_service_category() {
   //$('#hidden_update_button').click();
   obj_service_category_select = document.getElementById('int_service_category_id');
   int_selected_service_category_id = obj_service_category_select.options[obj_service_category_select.selectedIndex].value;
   bol_ajax_fired = true;
   $.ajax({
      async: true,
      type: "POST",
      url: "/ajax-basket/update-service-category",
      data: "int_service_category_id=" + int_selected_service_category_id,
      success: process_basket_update_response,
      error: function(obj, str, exc) {
         // Full on error
         window.location.href = "/basket/show";
      }
   });
}

/**
 * Processes the repsonse from a basket update Ajax call.
 *
 * @param Object obj_response
 */
function process_basket_update_response(obj_response) {
   if($('response', obj_response).attr('success') == 'true') {
      // Server side success
      var int_basket_line_count = $('basket_line', obj_response).length;
      if (int_basket_line_count == 0) {
         // Empty Basket - Reload Page
         window.location.href = "/basket/show";
      }

      var flt_total_promotion_savings = 0;

      // get rid off al the promotion lines, because we need to recalculate the
      // whole lot every time something changes
      var int_promotion_lines = $('[id*=promotion_line]');
      int_promotion_lines.each(function(){
         $(this).remove();
      });

      // Basket Line Updates.
      for (int_i = 0, int_n = int_basket_line_count; int_i < int_n; int_i++) {
         obj_line = $('basket_line', obj_response).get(int_i);
         var int_basket_line_id = $('basket_line_id', obj_line).text();
         $('#quantity_' + int_basket_line_id).val($('basket_line_quantity', obj_line).text());
         $('#basket_line_price_' + int_basket_line_id).html($('basket_line_price', obj_line).text());
         $('#basket_line_total_' + int_basket_line_id).html($('basket_line_total', obj_line).text());

         // Update Warranty Totals/Descriptions
         if ($('basket_line_warranty_chosen', obj_line).text() == 1 && $('basket_line_warranty_included', obj_line).text() != 1) {
            $('.warranty_line_total_' + int_basket_line_id).html($('basket_line_warranty_total', obj_line).text());
         } else {
            $('.warranty_line_total_' + int_basket_line_id).html('');
         }
         // Always update the left total next to the checkbox
         if ($('basket_line_warranty_included', obj_line).text() != 1) {
            $('.warranty_line_unit_' + int_basket_line_id).html($('basket_line_warranty_unit', obj_line).text());
         }

         if ($('basket_line_promotion_value', obj_line).length > 0){
            if ($('promotion_applies_to_whole_basket', obj_response).text() == "false" && parseFloat($('basket_line_promotion_total_unformatted', obj_line).text()) > 0.00){
               var obj_promotion_line = $(document.createElement('tr'));
               obj_promotion_line.attr('id','promotion_line_' + int_basket_line_id);
               obj_promotion_line.attr('class','tablePromotionLine');
               obj_promotion_line.append($(document.createElement('td')).attr('align','left').addClass('promotionLineDesc').html('- ' + $('promotion_name',obj_response).text()));
               obj_promotion_line.append($(document.createElement('td')).attr('align','center').html('&nbsp;'));
               obj_promotion_line.append($(document.createElement('td')).attr('align','center').html($('basket_line_quantity', obj_line).text()));
               obj_promotion_line.append($(document.createElement('td')).attr('align','right').html('&nbsp;'));
               obj_promotion_line.append($(document.createElement('td')).attr('align','right').addClass('priceNoVAT').html('- ' + $('basket_line_promotion_total', obj_line).text()));
               obj_promotion_line.append($(document.createElement('td')).attr('align','center').html('&nbsp;'));
               $('#basket_line_' + int_basket_line_id).after(obj_promotion_line);
            }

            flt_total_promotion_savings += parseFloat($('basket_line_promotion_total_unformatted', obj_line).text());
         }

         // update WEEE charges if provided
         if ($('weee', obj_line).length > 0) {
            $('#weee_charge_basket_line_' + int_basket_line_id).html($('weee_display_price', obj_line).text());
         }
      }

      if (flt_total_promotion_savings > 0.00) {
         $('#promoform').html('<button class="btn-g4m silver" onclick="remove_promo_code();">Remove Gear Code</button>')
      } else {
         $('#promoform').html('<label>Gear Code? <input type="text" name="promocode" id="promocode" value=""> <a href="javascript: add_promo_code();"><img src="/images/add.gif" border="0" width="16" height="16" alt="Add gear code" title="Add gear code" /></a></label>');
      }

      // Delivery Date Updates
      configure_delivery_date_calendar($('str_earliest_delivery_date', obj_response).text(), $('str_delivery_date', obj_response).text());

      // Service Category Updates
      int_selected_service_category_id = $('selected_service_category_id', obj_response).text();
      obj_service_category_select = document.getElementById('int_service_category_id');
      for (int_i = obj_service_category_select.options.length-1; int_i >= 0; int_i--) {
         obj_service_category_select.remove(int_i);
      }

      var int_service_category_count = $('service_category', obj_response).length;
      for (int_i = 0, int_n = int_service_category_count; int_i < int_n; int_i++) {
         obj_line = $('service_category', obj_response).get(int_i);
         obj_new_option = document.createElement('option');
         obj_new_option.value = $('service_category_id', obj_line).text();
         if ($('service_category_id', obj_line).text() == int_selected_service_category_id) {
            obj_new_option.selected = true;
         }
         // extract the price info and inject them to the option (xml DOM maybe better choice!!)
         var spanReg = /\<span.*?\>\&\#(.*?)\;\<\/span\>\<span.*?\>(.*?)\<\/span\>\<span.*?\>\&nbsp\;(.*?)\<\/span\>/;
         var str_price = $('service_category_price', obj_line).text();
         var arr_res = spanReg.exec(str_price);
         obj_new_option.text = ($('service_category_description', obj_line).text() + ", "+String.fromCharCode(parseInt(arr_res[1]))+arr_res[2]+" "+arr_res[3]).replace(/&nbsp;/,' ');

         if (document.all) {
            obj_service_category_select.add(obj_new_option);
         } else {
            obj_service_category_select.add(obj_new_option, null);
         }
      }

      // Totals Updates.
      $('#bsk-del-prc').html($('basket_total_delivery', obj_response).text());
      //$('#basket_total_exc_vat').html($('basket_total_exc_vat', obj_response).text());
      //$('#basket_total_vat').html($('basket_total_vat', obj_response).text());

      if ($('#delivery_value_line')) {
         $('#delivery_value_line .c-sym').html('');
         $('#delivery_value_line .c-val').html($('basket_total_delivery', obj_response).text());

         $('#sub_value_line .c-sym').html('');
         $('#sub_value_line .c-val').html($('basket_total_sub', obj_response).text());

         $('#vat_value_line .c-sym').html('');
         $('#vat_value_line .c-val').html($('basket_total_vat', obj_response).text());

         $('#total_value_line .c-sym').html('');
         $('#total_value_line .c-val').html($('basket_total_grand', obj_response).text());
      }
      // Remove Basket Line?
      if ($('basket_line_removed', obj_response).size() > 0) {
         $('basket_line_removed', obj_response).each(function() {
            $('#basket_line_' + $(this).text()).remove();

            // Remove the associated warranty line if there is one.
            $('#warranty_line_' + $(this).text()).remove();
         });
      }

      // if the promotion savings value > 0, add promotion stuff to the DOM
      if (flt_total_promotion_savings > 0.00) {

         // if the promotion summary stuff isn't already in the DOM, we need to create it
         if ($('#tablePromotionSummary').length == 0) {
            if ($('promotion_applies_to_whole_basket', obj_response).text() == "true") {
               summaryTextExtra = ' (' + $('promotion_name',obj_response).text() + ')';
            } else {
               summaryTextExtra = '';
            }
            // first line of promotion particulars
            var obj_promotion_summary = $(document.createElement('tr'));
            obj_promotion_summary.attr('id','tablePromotionSummary');
            obj_promotion_summary.append($(document.createElement('th')).html('Gear Code Saving' + summaryTextExtra + ':'));
            obj_promotion_summary.append(
               $(document.createElement('td')).addClass('no-vat').html(
                  $(document.createElement('strong')).addClass('discountSavingLine').attr('id','basket_promotion_saving').html('- ' +
                     $('basket_total_promotion_saving', obj_response).text()
                  )
               )
            );

            $('#basket_total_grand').removeClass('bsk-amnt');
            $('#bsk-total-inc').after(obj_promotion_summary);

            // second line of promotion particulars
            var obj_promotion_youpay = $(document.createElement('tr'));
            obj_promotion_youpay.attr('id','tableYouPay');
            obj_promotion_youpay.append($(document.createElement('th')).html('You pay:'));
            obj_promotion_youpay.append(
               $(document.createElement('td')).addClass('bsk-amnt').addClass('no-vat').attr('id','basket_promotion_adjusted').html(
                  $('basket_total_grand_promotion_adjusted', obj_response).text()
               )
            );

            // put the new objects directly after the price breakdown line ;)
            $('#tablePromotionSummary').after(obj_promotion_youpay);
         } else {
            // else if it IS in the DOM, we just repopulate some fields
            $('#basket_promotion_saving').html('- ' + $('basket_total_promotion_saving', obj_response).text());
            $('#basket_promotion_adjusted').html($('basket_total_grand_promotion_adjusted', obj_response).text());
         }
         $('#bsk-ttl-prc').html($('basket_total_grand_promotion_adjusted', obj_response).text());
         $('#basket_total_grand').html($('basket_total_grand', obj_response).text());
      } else {
         $('#tablePromotionSummary').remove();
         $('#tableYouPay').remove();
         $('#basket_total_grand').addClass('bsk-amnt');
         $('#basket_total_grand').html($('basket_total_grand', obj_response).text());
         $('#bsk-ttl-prc').html($('basket_total_grand', obj_response).text());
      }

      $.fancybox.close();
      bol_ajax_fired = false;
   } else {
      var str_error_message = $('response', obj_response).children('message').text();
      if (str_error_message){
         alert(str_error_message);
         $.fancybox.close();
      } else {
         window.location.href = "/basket/show";
      }
   }
}

/**
 * Add a warranty to the basket line via Ajax.
 *
 * @param Integer int_basket_line_id
 */
function add_warranty_to_basket_line(int_basket_line_id) {
   //$('#hidden_update_button').click();
   bol_ajax_fired = true;
   $.ajax({
      async: true,
      type: "POST",
      url: "/ajax-basket/add-warranty",
      data: "int_basket_line_id=" + int_basket_line_id,
      success: process_basket_update_response,
      error: function(obj, str, exc) {
         // Full on error
         window.location.href = "/basket/show";
      }
   });
}
/**
 * Remove a warranty to the basket line via Ajax.
 *
 * @param Integer int_basket_line_id
 */
function remove_warranty_from_basket_line(int_basket_line_id) {
   //$('#hidden_update_button').click();
   bol_ajax_fired = true;
   $.ajax({
      async: true,
      type: "POST",
      url: "/ajax-basket/remove-warranty",
      data: "int_basket_line_id=" + int_basket_line_id,
      success: process_basket_update_response,
      error: function(obj, str, exc) {
         // Full on error
         window.location.href = "/basket/show";
      }
   });
}

/**
 * Fancybox callback function
 * Check if there's a current ajax request, if not - close popup
 */
function fancybox_opened() {
   if (bol_ajax_fired == false) {
      $.fancybox.close();
   }
}

