﻿/// <reference path="jquery-1.5-vsdoc.js" />
function SetCartSummary(result, pageTypeID) {
   $('dl#total dd.total-sum').text(result.Total + ' SEK');
   if (result.SubTotalVatInCash != null) {
      $('dl#total-vat dd.total-vat-sum').text(result.SubTotalVatInCash + ' SEK');
   }
   if (pageTypeID == 10) {
      $('dl#total dd.total-sum').text(result.Total + ' SEK');
      $('dl#total dd.sub-total').text(result.SubTotal + ' SEK');
      $('dl#total dd.freight-cost').text(result.FreightCost + ' SEK');
      $('dl#total dd.vat-in-cash').text(result.TotalVatInCash + ' SEK');
      $('dl#total dd.vat-text').text('(' + result.VATText + ')');

      $('dl#total2 dd.sub-total').text(result.SubTotal + ' SEK');
      $('dl#total2 dd.freight-cost').text(result.FreightCost + ' SEK');
      $('dl#total2 dd.vat-in-cash').text(result.TotalVatInCash + ' SEK');

      $('dl#total2 dd.total-sum').text((result.TotalToPay) + ' SEK');
      $('dl#total2 dd.vat-text').text('(' + result.VATText + ')');
   }
}
function GetSelectedAttributes() {
   var attr = "[";
   $('p.attribute-type').each(function() {
      attr += '{"ATID":"' + $(this).find('input.attribute_type_id').val() + '","AID":"' + $(this).find('input.attribute_id').val() + '"},';
   });

   if (attr == "[") {
      return "[]";
   }
   attr = attr.substring(0, attr.length - 1);
   attr = attr + "]";
   return attr;
}

$.fn.extend(
{
   get_ecom_request: null,
   UpdatePage: function() {
      var pageTypeID = $(val_pageTypeID).selector;
      if (pageTypeID == 1) {
         $.fn.SetPriceCategoryFN(function() { $.fn.GetNewPriceInterval(true, function() { $.fn.ResetAndGetProducts(); }); });
      } else if (pageTypeID == 2) {
         $.fn.SetPriceCategoryFN(function() { $.fn.GetProductsPL(); });
      }
   },
   SetCustomerType: function(customerTypeID) {
      if ($.fn.get_ecom_request != null) {
         $.fn.get_ecom_request.abort();
      }
      $cartContent = $('#cart_content');
      var pageTypeID = $(val_pageTypeID).selector;
      $.fn.get_ecom_request = $.ajax({
         type: 'POST',
         url: '/Handlers/Public/ShoppingCart/CartHandler.ashx',
         xhr: function() {
            if ($.browser.msie && $.browser.version.substr(0, 1) <= 7)
               return new ActiveXObject("Microsoft.XMLHTTP");
            else
               return new XMLHttpRequest();
         },
         data: '{"Action":"SET-CUSTOMER-TYPE","PTID":"' + pageTypeID + '","CTID":"' + customerTypeID + '"}',
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         beforeSend: function() {
         },
         success: function(result) {
            if (result == null) { return; }
            if (result.HasError) {
               ShowFancybox(result.ErrorHeadline, CreateULList('', '', result.Errors), 'error');
            }
            else {
               $.fn.PresentCart(result.GCRI, false, function() { $(cartContentWrapper).fadeIn('300'); });
               $.fn.PresentDeliveryMethods(result, false, function() { });
               $.fn.PresentPaymentMethods(result, false, function() { });
            }
         },
         error: function(err) {
            if (err.statusText == "abort") { return; }
            ShowFancybox('Systemfel', CreateULList('', '', new Array('Tyvärr blev något fel, var god försök igen')), 'error');
         },
         complete: function() {
            $.fn.get_ecom_request = null;
         }
      });
   },
   GetCart: function() {
      if ($.fn.get_ecom_request != null) {
         $.fn.get_ecom_request.abort();
      }
      $cartContent = $('#cart_content');
      var pageTypeID = $(val_pageTypeID).selector;
      $.fn.get_ecom_request = $.ajax({
         type: 'POST',
         url: '/Handlers/Public/ShoppingCart/CartHandler.ashx',
         xhr: function() {
            if ($.browser.msie && $.browser.version.substr(0, 1) <= 7)
               return new ActiveXObject("Microsoft.XMLHTTP");
            else
               return new XMLHttpRequest();
         },
         data: '{"Action":"GET","PTID":"' + pageTypeID + '"}',
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         beforeSend: function() {
         },
         success: function(result) {
            if (result == null) { return; }
            if (result.HasError) {
               ShowFancybox(result.ErrorHeadline, CreateULList('', '', result.Errors), 'error');
            }
            else {
               $.fn.PresentCart(result, false, function() { $(cartContentWrapper).fadeIn('300'); });
               ShowFancyboxAndFade(result.PAH, '', 2500, 'success add-item', false);
            }
         },
         error: function(err) {
            if (err.statusText == "abort") { return; }
            ShowFancybox('Systemfel', CreateULList('', '', new Array('Tyvärr blev något fel, var god försök igen')), 'error');
         },
         complete: function() {
            $.fn.get_ecom_request = null;
         }
      });
   },
   PresentCart: function(result, reset, callback) {
      var pageTypeID = $(val_pageTypeID).selector;

      $wrapper = 'div#cart_wrapper';

      $cartInfoBar = $('#myCart ul');
      $cartInfoBarContent = $('div#myCart ul li#showHideCart');
      $($wrapper + ' dl.shopping_cart_item').remove();
      $cartInfoBarContent.empty();

      $newContent = $('<dl/>');

      $cartInfoBarContent.removeAttr('class').addClass('theCart rounded-corners-bottom');

      if (result.ProductQuantity == 0) {
         $CI = $('<dd/>').text(result.CI.CartInfoText).appendTo($newContent);
         $newContent.appendTo($cartInfoBarContent);
         $($wrapper).hide();
         return;
      }

      $cartInfoBarContent.addClass('has-products');


      $CIAnchor = $('<a/>').attr('id', 'cart-show').attr('href', 'javascript:ShowHideCart();').append($('<b/>').text(result.CI.CartInfoText + ', ')).append($('<span/>').text(result.SubTotal + ' ' + result.CurrencyName));
      $CI = $('<dd/>').append($CIAnchor);
      $newContent.append($CI);
      $('<dd/>').text(' | ').appendTo($newContent);
      $anchor = $('<a/>').text(result.CI.ToCheckoutText).attr('href', result.CI.CheckoutURL).attr('title', result.CI.ToCheckoutText);
      $('<dd/>').addClass('to-checkout-wrapper').append($anchor).appendTo($newContent);

      $newContent.appendTo($cartInfoBarContent);

      var directive = {
         'div.template dl.shopping_cart_item': {
            'scli <- ShoppingCartListItems': {
               '@class+': function(a) { return a.item.ORTID == 2 ? ' campaign_item' : ''; },
               'dd a.delete': function(a) { return a.context.CTT.R; },
               'dd a.delete@title': function(a) { return a.context.CTT.R; },
               'dd a.delete@href': function(a) { return 'javascript:$.fn.RemoveProduct(\'' + a.item.ProductID + '\',' + a.item.PAF + ',\'' + a.item.Quantity + '\',\'' + a.item.ORTID + '\');'; },
               'dd a.add': function(a) { return a.context.CTT.M; },
               'dd a.add@title': function(a) { return a.context.CTT.M; },
               'dd a.add@href': function(a) { return 'javascript:$.fn.UpdateProduct(\'' + a.item.ProductID + '\',' + a.item.PAF + ',\'+1\',\'' + a.item.ORTID + '\');'; },
               'dd a.sub': function(a) { return a.context.CTT.L; },
               'dd a.sub@title': function(a) { return a.context.CTT.L; },
               'dd a.sub@href': function(a) { return 'javascript:$.fn.UpdateProduct(\'' + a.item.ProductID + '\',' + a.item.PAF + ',\'-1\',\'' + a.item.ORTID + '\');'; },
               'dd a.sub@style': function(a) { return a.item.Quantity > 1 ? '' : 'display:none;'; },
               'dd a.product-link+': 'scli.Name',
               'dd a.product-link@title': 'scli.Name',
               'dd a.product-link@href': 'scli.Url',
               'dd.img span': function(a) { return a.item.PAN; },
               'dd.product-quantity': 'scli.Quantity',
               'dd.product-quantity+': function(a) { return ' ' + a.item.Price.UnitName; },
               'dd.product-price': function(a) { return a.item.Price.Price + ' ' + a.context.CurrencyName; },
               'dd.product-total': function(a) { return a.item.TotalPrice + ' ' + a.context.CurrencyName; }
            }
         }
      };

      SetCartSummary(result, pageTypeID);

      var generateItem = $('div#shopping_cart_item_template').compile(directive, false);

      var item = generateItem(result);

      $items = $(item).children('div.template').children();
      $items.insertAfter($wrapper + ' dl.cart_top');

      if (result.GotAllInfo) {
         $summaryWrapper = $('#summary');
         $summaryWrapper.find('dl.sub-total dt.sub-total-text').text(result.SubTotalPriceLabel);
         $summaryWrapper.find('dl.sub-total dd.sub-total-price').text(result.SubTotal + ' ' + result.CurrencyName);
         $summaryWrapper.find('dl.freight dt.freight-text').text(result.FreightCostName);
         $summaryWrapper.find('dl.freight dd.freight-price').text(result.FreightCost + ' ' + result.CurrencyName);
         $summaryWrapper.find('dl.handling dt.handling-text').text(result.HandlingCostName);
         $summaryWrapper.find('dl.handling dd.handling-price').text(result.HandlingCost + ' ' + result.CurrencyName);
         $summaryWrapper.find('dl.total-price dt.total-price-text').text(result.TotalPriceLabel);
         $summaryWrapper.find('dl.total-price dd.total-price-price').text(result.Total + ' ' + result.CurrencyName);
         $summaryWrapper.find('dl.total-price dd#total-cart-equals-to').html(result.EqualsTo);
         $summaryWrapper.find('dl.total-price-sek dt#warning div').html(result.CWT);
         if (result.CWT.length == 0) {
            $summaryWrapper.find('dl.total-price-sek dt#warning div').hide();
         } else {
            $summaryWrapper.find('dl.total-price-sek dt#warning div').show();
         }

         $summaryWrapper.find('dl.total-price-sek dt.total-price-sek-text').text(result.TotalPriceInSekLabel);
         $summaryWrapper.find('dl.total-price-sek dd.total-price-sek-price').text(result.TotalInSek + ' SEK');

      }



      if (callback != null) {
         callback.call();
      }
   },
   BuyAnchor: function(hfID, input_qty) {
      $anchor = $(this);
      $anchor.bind('click', function() {
         var attributes = GetSelectedAttributes();
         var quantity = $(input_qty).val();
         var productID = $(hfID).val();
         $.fn.AddProductToShoppingCart(productID, attributes, quantity);
      });
   },
   AddProductToShoppingCart: function(productID, attributes, quantity) {
      if ($.fn.get_ecom_request != null) {
         $.fn.get_ecom_request.abort();
      }
      var pageTypeID = $(val_pageTypeID).selector;

      $.fn.get_ecom_request = $.ajax({
         type: 'POST',
         url: '/Handlers/Public/ShoppingCart/CartHandler.ashx',
         xhr: function() {
            if ($.browser.msie && $.browser.version.substr(0, 1) <= 7)
               return new ActiveXObject("Microsoft.XMLHTTP");
            else
               return new XMLHttpRequest();
         },
         data: '{"Action":"ADD","ProductID":"' + productID + '","Quantity":"' + quantity + '","ProductAttributes":' + attributes + ',"PTID":"' + pageTypeID + '"}',
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         beforeSend: function() {
         },
         success: function(result) {
            if (result == null) { return; }
            if (result.HasError) {
               ShowFancybox(result.ErrorHeadline, CreateULList('', '', result.Errors), 'error');
            }
            else {
               $.fn.PresentCart(result, false, function() { $(cartContentWrapper).fadeIn('300'); });
               var phs = '<ul>';
               for (var i = 0; i < result.ProductsHandeled.length; i++) {
                  phs = phs + '<li>' + result.ProductsHandeled[i].Quantity + ' st ' + result.ProductsHandeled[i].Name + '</li>';
               }
               phs = phs + '</ul>';
               ShowFancyboxAndFade(result.PAH, phs, 2500, 'success add-item', false);
            }
         },
         error: function(err) {
            if (err.statusText == "abort") { return; }
            ShowFancybox('Systemfel', 'Tyvärr blev något fel, var god försök igen', 'error');
         },
         complete: function() {
            $.fn.get_ecom_request = null;
         }
      });
   },
   GetCartPas: function(pas) {
      var attr = "[";
      $(pas).each(function() {
         attr += '{"ATID":"' + this.ATID + '","AID":"' + this.AID + '"},';
      });
      if (attr == "[") {
         return "[]";
      }
      attr = attr.substring(0, attr.length - 1);
      attr = attr + "]";
      return attr;
   },
   UpdateProduct: function(productID, pas, quantity, ortid) {
      if ($.fn.get_ecom_request != null) {
         $.fn.get_ecom_request.abort();
      }

      var serPas = $.fn.GetCartPas(pas);

      var pageTypeID = $(val_pageTypeID).selector;

      $.fn.get_ecom_request = $.ajax({
         type: 'POST',
         url: '/Handlers/Public/ShoppingCart/CartHandler.ashx',
         xhr: function() {
            if ($.browser.msie && $.browser.version.substr(0, 1) <= 7)
               return new ActiveXObject("Microsoft.XMLHTTP");
            else
               return new XMLHttpRequest();
         },
         data: '{"Action":"UPDATE","ProductID":"' + productID + '","ProductAttributes":' + serPas + ',"Quantity":"' + quantity + '","PTID":"' + pageTypeID + '","ORTID":"' + ortid + '"}',
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',

         beforeSend: function() {
            if (pageTypeID == 11) {
               $(product_list_wrapper).fadeOut('300');
               $(product_loader).show();
            }
         },

         success: function(result) {
            if (result == null) { return; }
            if (result.HasError) {
               ShowFancybox(result.ErrorHeadline, CreateULList('', '', result.Errors), 'error');
            }
            else {
               if (pageTypeID == 10) {
                  $.fn.PresentCart(result, false, function() { });
                  $.fn.PresentDeliveryMethods(result, false, function() { });
               }
               else {
                  $.fn.PresentCart(result, false, function() { $(cartContentWrapper).fadeIn('300'); });
               }
            }
         },
         error: function(err) {
            if (err.statusText == "abort") { return; }
            ShowFancybox('Systemfel', CreateULList('', '', new Array('Tyvärr blev något fel, var god försök igen')), 'error');
         },
         complete: function() {
            $.fn.get_ecom_request = null;
         }
      });
   },
   RemoveProduct: function(productID, pas, quantity, ortid) {
      if ($.fn.get_ecom_request != null) {
         $.fn.get_ecom_request.abort();
      }

      var serPas = $.fn.GetCartPas(pas);

      var pageTypeID = $(val_pageTypeID).selector;

      $.fn.get_ecom_request = $.ajax({
         type: 'POST',
         url: '/Handlers/Public/ShoppingCart/CartHandler.ashx',
         xhr: function() {
            if ($.browser.msie && $.browser.version.substr(0, 1) <= 7)
               return new ActiveXObject("Microsoft.XMLHTTP");
            else
               return new XMLHttpRequest();
         },
         data: '{"Action":"REMOVE","ProductID":"' + productID + '","ProductAttributes":' + serPas + ',"Quantity":"' + quantity + '","PTID":"' + pageTypeID + '","ORTID":"' + ortid + '"}',
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',

         beforeSend: function() {
            if (pageTypeID == 11) {
               $(product_list_wrapper).fadeOut('300');
               $(product_loader).show();
            }
         },
         success: function(result) {
            if (result == null) { return; }
            if (result.HasError) {
               ShowFancybox(result.ErrorHeadline, CreateULList('', '', result.Errors), 'error');
            }
            else {
               if (pageTypeID == 10 || pageTypeID == 11) {
                  if (result.ProductQuantity == 0) {
                     ShowFancybox(result.RedirectTitle, result.RedirectText, 'info');
                     window.location = result.RedirectURL;
                     return false;
                  } else {

                  }
               }
               $.fn.PresentCart(result, false, function() { $(cartContentWrapper).fadeIn('300'); });
            }
         },
         error: function(err) {
            if (err.statusText == "abort") { return; }
            ShowFancybox('Systemfel', CreateULList('', '', new Array('Tyvärr blev något fel, var god försök igen')), 'error');
         },
         complete: function() {
            $.fn.get_ecom_request = null;
         }
      });
   },
   get_checkout_request: null,
   GetCustomerByEmail: function(exception) {
      var timeout;
      $input = $(this);
      $input.bind(($.browser.opera ? "keypress" : "keydown"), function(event) {
         var arr = new Array(16, 17, 18, 20, 34, 33, 188, 27, 9, 40, 38); // common non-alfabetic and non-numeric characters' keycodes
         lastKeyPressCode = event.keyCode;
         if ($.inArray(event.keyCode, arr) == -1) {
            clearTimeout(timeout);
            var text = $input.val();
            if (text != exception) {
               timeout = setTimeout('$.fn.FetchCustomerByEmail()', 750);
               if (lastKeyPressCode == 13)
                  return false;
            }
            return false;
         }
         else {
            return false;
         }
      });
   },
   GetCustomerByEmailAnchor: function(exception, callback) {
      $anchor = $(this);
      $anchor.bind('click', function() {
         $.fn.FetchCustomerByEmail(exception, callback);
      });
   },
   FetchCustomerByEmail: function(exception, callback, email, pw) {
      if ($.fn.get_checkout_request != null) {
         $.fn.get_checkout_request.abort();
      }

      $email = $(input_email).val();
      if (email != null) {
         $email = email;
      }
      $pw = $(input_pw).val();
      if (pw != null) {
         $pw = pw;
      }
      if ($email == exception) {
         AnimateBackground($(input_email), '#f00', 300, '#fff', 300);
         return false;
      }

      $.fn.get_checkout_request = $.ajax({
         type: 'POST',
         url: '/Handlers/Public/ShoppingCart/CartHandler.ashx',
         xhr: function() {
            if ($.browser.msie && $.browser.version.substr(0, 1) <= 7)
               return new ActiveXObject("Microsoft.XMLHTTP");
            else
               return new XMLHttpRequest();
         },
         dataType: 'json',
         data: '{"Action":"GET-CUST'
                + '","Email":"' + $email
                + '","Pw":"' + $pw
                + '"}',
         contentType: 'application/json; charset=utf-8',
         beforeSend: function() {
         },
         success: function(result) {
            if (result == null) { return; }
            if (result.HasError) {
               $(result_box).empty().show().append($('<h3/>').text(result.ErrorHeadline)).append(CreateULList('', '', result.Errors));
               $.fancybox.resize();
            }
            else {
               if (!result.CustomerFound) {
                  $(result_box).empty().show().append($('<h3/>').text(result.ErrorHeadline)).append(CreateULList('', '', result.Errors));
                  $.fancybox.resize();
               }
               else {
                  $.fn.PresentCustomer(result);
                  $.fancybox.close();
               }
               if (callback != null) {
                  callback.call();
               }
            }
         },
         error: function(err) {
            if (err.statusText == "abort") { return; }
            $(result_box).empty().show().append($('<h3/>').text('Oväntat fel')).append($('<p/>').text('Tyvärr blev något fel, var god försök igen'));
            $.fancybox.resize();
         },
         complete: function() {
            $.fn.get_checkout_request = null;
         }
      });
   },
   PresentCustomer: function(customer) {
      $(input_form_email).val(customer.Email);
      $(input_form_email_repeat).val(customer.Email);
      $(input_form_cname).val(customer.CompanyName);
      $(input_form_cno).val(customer.CompanyNo);
      $(input_form_fname).val(customer.FirstName);
      $(input_form_lname).val(customer.LastName);
      $(input_form_sadress).val(customer.StreetAdress);
      $(input_form_padress).val(customer.PostalAdress);
      $(input_form_city).val(customer.City);
      $(input_form_phone).val(customer.Phone);
      $(input_form_country).find('option[value="' + customer.CountryID + '"]').attr('selected', true);

      if (customer.HasDifferentDeliveryAdress) {
         $(input_form_del_fname).val(customer.FirstName);
         $(input_form_del_lname).val(customer.LastName);
         $(input_form_del_sadress).val(customer.DeliveryStreetAdress);
         $(input_form_del_padress).val(customer.DeliveryPostalAdress);
         $(input_form_del_city).val(customer.DeliveryCity);
         $(input_form_del_country).find('option[value="' + customer.DeliveryCountryID + '"]').attr('selected', true);
         ShowDeliveryAddress();
      }
      else {
         HideDeliveryAddress();
      }

      $.fn.PresentDeliveryMethods(customer, false, function() { });
      $.fn.PresentPaymentMethods(customer, false, function() { });
      $('#get_customer_trigger').hide();
      $('#customer_logout_trigger').show();
      $('#topInfoBar').show();
      $('a#top-login-anchor').attr('href', '/mina-sidor/kunduppgifter.aspx').text('Mina sidor »').parent().removeAttr('class');
      $('#top_anchor_customer_email').text(customer.Email);
      $('#select-priv-company').hide();
      $('#select-priv-company dd label span[rel!="' + customer.CustomerTypeID + '"] input').attr('checked', false);
      $('#select-priv-company dd label span[rel="' + customer.CustomerTypeID + '"] input').attr('checked', true);

      if (customer.Countries.length > 0) {
         $(input_form_country).children().remove();
         for (var c in customer.Countries) {
            $('<option />').attr('value', customer.Countries[c].CountryID).attr('text', customer.Countries[c].Name).appendTo($(input_form_country));
         }
      }
      if (customer.CountryID != null) {
         $(input_form_country).find('option[value="' + customer.CountryID + '"]').attr('selected', true);
     }

     if (customer.DeliveryCountries.length > 0) {
         $(input_form_del_country).children().remove();
         for (var c in customer.DeliveryCountries) {
             $('<option />').attr('value', customer.DeliveryCountries[c].CountryID).attr('text', customer.DeliveryCountries[c].Name).appendTo($(input_form_del_country));
         }
     }
      if (customer.DeliveryCountryID != null) {
         $(input_form_del_country).find('option[value="' + customer.DeliveryCountryID + '"]').attr('selected', true);
      }

      if (customer.CustomerTypeID == '1') {
         $('#special-color-wrapper').hide();
         $(input_form_email).attr('readonly', false).attr('class', 'swap_value showTip');
         $(input_form_email_repeat).attr('readonly', false).attr('class', 'swap_value showTip');
         $(input_form_cname).attr('readonly', false).attr('class', 'swap_value showTip company-only');
         $(input_form_cno).attr('readonly', false).attr('class', 'swap_value showTip company-only');
         $(input_form_fname).attr('readonly', false).attr('class', 'swap_value showTip');
         $(input_form_lname).attr('readonly', false).attr('class', 'swap_value showTip');
         $(input_form_sadress).attr('readonly', false).attr('class', 'swap_value showTip');
         $(input_form_padress).attr('readonly', false).attr('class', 'swap_value showTip');
         $(input_form_city).attr('readonly', false).attr('class', 'swap_value showTip');
         $(input_form_phone).attr('readonly', false).attr('class', 'swap_value showTip');
         $(input_form_country).removeAttr('onchange').attr('class', 'swap_value showTip');

      }
      else {
         $('#special-color-wrapper').show();
         $(input_form_email).attr('readonly', true).attr('class', 'showTip disabled');
         $(input_form_email_repeat).attr('readonly', true).attr('class', 'showTip disabled');
         $(input_form_cname).attr('readonly', true).attr('class', 'showTip disabled company-only');
         $(input_form_cno).attr('readonly', true).attr('class', 'showTip disabled company-only');
         $(input_form_fname).attr('readonly', true).attr('class', 'showTip disabled');
         $(input_form_lname).attr('readonly', true).attr('class', 'showTip disabled');
         $(input_form_sadress).attr('readonly', true).attr('class', 'showTip disabled');
         $(input_form_padress).attr('readonly', true).attr('class', 'showTip disabled');
         $(input_form_city).attr('readonly', true).attr('class', 'showTip disabled');
         $(input_form_phone).attr('readonly', true).attr('class', 'showTip disabled');
         var selectedIndex = $(input_form_country).attr('selectedIndex');
         $(input_form_country).attr('onchange', 'this.selectedIndex = ' + selectedIndex + ';').attr('class', 'showTip disabled');
      }

      SetView(customer.CustomerTypeID);

   },
   PresentDeliveryMethods: function(result, reset, callback) {
      $wrapper = $('#delivery-methods-wrapper');
      var directive = {
         'dl': {
            'dmwj <- DeliveryMethods': {
               'dl dd.dd1 label span': function(a) { return a.item.Name },
               'dl dd.dd1 p': function(a) { return a.item.ShortDescription },
               'dl dd.dd1 label input@id': function(a) { return 'delivery_method_' + a.item.DeliveryMethodID; },
               'dl dd.dd1 label input@rel': function(a) { return a.item.DeliveryMethodID; },
               'dl dd.dd1 label input@onclick': function(a) { return '$.fn.SelectDeliveryMethod(' + a.item.DeliveryMethodID + ');'; },
               'dl dd.dd1 label input@checked': function(a) { return a.item.Selected; },
               'dl dd.dd2 a.info span.iBlock': function(a) { return a.item.Description },
               'dl dd.dd2 span.ip': function(a) { return '+' + a.item.PriceFormatted + ' SEK'; }
            }
         }
      };

      var generateItem = $('div#delivery-method-template').compile(directive, false);

      var item = generateItem(result);

      $items = $(item).children('dl');
      $items.find('dd.dd1 label input').attr('checked', false);
      $items.find('dd.dd1 label input[rel="' + result.SDMID + '"]').attr('checked', true).parent().parent().parent().addClass('active');
      $wrapper.empty();
      $wrapper.append($items);
   },
   PresentPaymentMethods: function(result, reset, callback) {
      $wrapper = $('#payment-methods-wrapper');
      var directive = {
         'dl': {
            'dmwj <- PaymentMethods': {
               'dl dd.dd1 label span': function(a) { return a.item.Name },
               'dl dd.dd1 label input@id': function(a) {
                  if (result.SPMID == a.item.PaymentMethodID) {
                     $(input_submit).html(a.item.NSBT + ' »<span>&nbsp;</span>');
                  }
                  return 'payment_method_' + a.item.PaymentMethodID;
               },
               'dl dd.dd1 label input@rel': function(a) { return a.item.PaymentMethodID; },
               'dl dd.dd1 label input@onclick': function(a) { return '$.fn.SelectPaymentMethod(' + a.item.PaymentMethodID + ');'; },
               'dl dd.dd1 label input@checked': function(a) { return a.item.Selected; },
               'dl dd.dd1 p img@src': function(a) { return a.item.ImageUrl; },
               'dl dd.dd1 p img@alt': function(a) { return a.item.Name; },
               'dl dd.dd2 a.info span.iBlock': function(a) { return a.item.Description; }
            }
         }
      };

      var generateItem = $('div#payment-method-template').compile(directive, false);

      var item = generateItem(result);

      $items = $(item).children('dl');
      $items.find('dd.dd1 label input[rel="' + result.SPMID + '"]').attr('checked', true).parent().parent().parent().addClass('active');

      $wrapper.empty();
      $wrapper.append($items);
   },
   SetAddressInformation: function(addressID, showErrorPopup) {
      if ($.fn.get_checkout_request != null) {
         $.fn.get_checkout_request.abort();
      }
      var setCountry = false;
      $.fn.get_checkout_request = $.ajax({
         type: 'POST',
         url: '/Handlers/Public/Customer/CustomerHandler.ashx',
         xhr: function() {
            if ($.browser.msie && $.browser.version.substr(0, 1) <= 7)
               return new ActiveXObject("Microsoft.XMLHTTP");
            else
               return new XMLHttpRequest();
         },
         dataType: 'json',
         data: '{"Action":"GET-ADDRESS-INFO'
                + '","AddressID":"' + addressID
                + '"}',
         contentType: 'application/json; charset=utf-8',
         beforeSend: function() {
         },
         success: function(result) {
            if (result == null) { return; }
            if (result.HasError) {
               if (showErrorPopup) {
                  ShowFancybox(result.ErrorHeadline, CreateULList('', '', result.Errors), 'error');
               }
            }
            else {
               $(input_first_name).val(result.FirstName);
               $(input_last_name).val(result.LastName);
               $(input_care_of).val(result.JAW.CareOf);
               $(input_street_address).val(result.JAW.StreetAddress);
               $(input_postal_address).val(result.JAW.PostalAddress);
               $(input_city).val(result.JAW.City);
               $(input_state).val(result.JAW.State);
               $(opt_country).find('option[value="' + result.JAW.CountryID + '"]').attr('selected', true);
               setCountry = true;
               $(input_email_cust).val(result.Email);
               $(input_phone).val(result.JAW.Phone);
               $(input_age).attr('checked', true);
            }
         },
         error: function(err) {
            if (err.statusText == "abort") { return; }
            ShowFancybox('Systemfel', CreateULList('', '', new Array('Tyvärr blev något fel, var god försök igen')), 'error');
         },
         complete: function() {
            $.fn.get_checkout_request = null;
            if (setCountry) {
               $(opt_country).change();
            }
         }
      });
   },
   LogoutCustomer: function() {
      if ($.fn.get_checkout_request != null) {
         $.fn.get_checkout_request.abort();
      }


      $.fn.get_checkout_request = $.ajax({
         type: 'POST',
         url: '/Handlers/Public/Customer/CustomerHandler.ashx',
         xhr: function() {
            if ($.browser.msie && $.browser.version.substr(0, 1) <= 7)
               return new ActiveXObject("Microsoft.XMLHTTP");
            else
               return new XMLHttpRequest();
         },
         dataType: 'json',
         data: '{"Action":"LOGOUT'
                + '"}',
         contentType: 'application/json; charset=utf-8',
         beforeSend: function() {
         },
         success: function(result) {
            if (result == null) { return; }
            if (result.HasError) {
               ShowFancybox(result.ErrorHeadline, CreateULList('', '', result.Errors), 'error');
            }
            else {
               $('#shopEarlier h3').text(result.ShopEarlierHeadline);
               $('#shopEarlier p').html(result.ShopEarlierText);

               $('#shopEarlier ul#shopEarlierActionGetCust').show();
               $('#shopEarlier ul#shopEarlierActionGetOrders').hide();

               $(opt_country_cart).SetInitialSelectedCountry('0');
               $.fn.SetSelectedCountry($(opt_country_cart).find('option:selected').val(), function() { $.fn.UpdatePage(); $.fn.GetCart(); });
            }
         },
         error: function(err) {
            if (err.statusText == "abort") { return; }
            ShowFancybox('Systemfel', CreateULList('', '', new Array('Tyvärr blev något fel, var god försök igen')), 'error');
         },
         complete: function() {
            $.fn.get_checkout_request = null;
         }
      });
   },
   SelectDeliveryMethod: function(deliveryMethodID) {
      if ($.fn.get_checkout_request != null) {
         $.fn.get_checkout_request.abort();
      }

      $('div#methods-wrapper dl.delivery-method').removeClass('active');
      $('div#methods-wrapper dl dd label input#delivery_method_' + deliveryMethodID).parent().parent().parent().addClass('active');

      $.fn.get_checkout_request = $.ajax({
         type: 'POST',
         url: '/Handlers/Public/ShoppingCart/CartHandler.ashx',
         xhr: function() {
            if ($.browser.msie && $.browser.version.substr(0, 1) <= 7)
               return new ActiveXObject("Microsoft.XMLHTTP");
            else
               return new XMLHttpRequest();
         },
         dataType: 'json',
         data: '{"Action":"SET-DELIVERY-METHOD'
                + '","DeliveryMethodID":"' + deliveryMethodID
                + '"}',
         contentType: 'application/json; charset=utf-8',
         beforeSend: function() {
         },
         success: function(result) {
            if (result == null) { return; }
            if (result.HasError) {
               ShowFancybox(result.ErrorHeadline, CreateULList('', '', result.Errors), 'error');
            }
            else {
               var pageTypeID = $(val_pageTypeID).selector;
               SetCartSummary(result, pageTypeID);
               //                $.fn.PresentDeliveryMethod(result, false, function() { /*$(cartContentWrapper).fadeIn('300');*/ });
            }
         },
         error: function(err) {
            if (err.statusText == "abort") { return; }
            ShowFancybox('Systemfel', CreateULList('', '', new Array('Tyvärr blev något fel, var god försök igen')), 'error');
         },
         complete: function() {
            $.fn.get_checkout_request = null;
         }
      });
   },
   SelectPaymentMethod: function(paymentMethodID) {
      if ($.fn.get_checkout_request != null) {
         $.fn.get_checkout_request.abort();
      }

      $('div#methods-wrapper dl.payment-method').removeClass('active');
      $('div#methods-wrapper dl dd label input#payment_method_' + paymentMethodID).parent().parent().parent().addClass('active');

      //      $('div#methods-wrapper dl dd label input.payment-method').attr('checked', false);
      //      $('div#methods-wrapper dl dd label input#payment_method_' + paymentMethodID).attr('checked', true);

      $.fn.get_checkout_request = $.ajax({
         type: 'POST',
         url: '/Handlers/Public/ShoppingCart/CartHandler.ashx',
         xhr: function() {
            if ($.browser.msie && $.browser.version.substr(0, 1) <= 7)
               return new ActiveXObject("Microsoft.XMLHTTP");
            else
               return new XMLHttpRequest();
         },
         dataType: 'json',
         data: '{"Action":"SET-PAYMENT-METHOD'
                + '","PaymentMethodID":"' + paymentMethodID
                + '"}',
         contentType: 'application/json; charset=utf-8',
         beforeSend: function() {
         },
         success: function(result) {
            if (result == null) { return; }
            if (result.HasError) {
               ShowFancybox(result.ErrorHeadline, CreateULList('', '', result.Errors), 'error');
            }
            else {
               var pageTypeID = $(val_pageTypeID).selector;
               SetCartSummary(result, pageTypeID);
               //$('div#methods-wrapper dl dd label input#payment_method_' + paymentMethodID).parent().parent().parent().addClass('active');
               //                $.fn.PresentDeliveryMethod(result, false, function() { /*$(cartContentWrapper).fadeIn('300');*/ });
            }
         },
         error: function(err) {
            if (err.statusText == "abort") { return; }
            ShowFancybox('Systemfel', CreateULList('', '', new Array('Tyvärr blev något fel, var god försök igen')), 'error');
         },
         complete: function() {
            $.fn.get_checkout_request = null;
         }
      });
   }
});

