var shopAction = {
  submit : function (id) {
    $('#'+id).submit();
  },

  openPanelRedirectOnClose : function(url, title, x, y, updateHeader){

      // open a welcome message as soon as the window loads
      if (x == null && y == null) {
        x = 300;
        y = 300;
      }


      Shadowbox.open({
          content:    '<span id="shadowboxMsg"></span>',
          player:     "html",
          title:      title,
          height:     y,
          width:      x,

          options: {onFinish: function () {
          $("#shadowboxMsg").append(loader);
          $("#shadowboxMsg img").css("margin-top", 42 + "px" );
          $("#shadowboxMsg img").css("margin-left", (x/2 - 12) + "px" );

          shopAction.simpleAjaxRequest(url, 'shadowboxMsg', updateHeader);

                    },

                    onClose: function () {
                      var huba = $('#redirect');
                      if( redirect){
                        window.location = shop.absoluteBaseUrl + "orderSummary" ;
                      }
                      else{

                      }
                    },
                    enableKeys: false

          }
      });

    },
  checkAddVoucher : function(){
    if($('#checkIfAdd:checked').val() != null){
    //checkbox is angehakt
      shopAction.addVoucher();
      Shadowbox.close();
    }
    else{
    //checkbox ist nicht angehakt
    }

  },

  submitShipping : function(id, event, url){
    var code = $('#payment_method_coupon').val();
    if (code != null && code != '') {
      shopAction.openPanelRedirectOnClose(url+code, 'Uw korting '+code,700,500);
      return false;
    } else{
      shopAction.submit(id);
      return false;
    }
  },

  consumeEnterInShippingForm : function(event, value, id, isRequiredPaymentMethod){
    if(event.keyCode == 13 && value != ''){
      shopAction.addVoucher(isRequiredPaymentMethod);
      return false;
    }else if(event.keyCode == 13 && value==''){
      shopAction.submit(id);

    }
  },

  disableEnterKey: function (e)  {
       var key;
       if(window.event)
            key = window.event.keyCode; //IE
       else
            key = e.which; //firefox

       return (key != 13);
  },

  submitFormOnEnter: function(id, event) {
    if (event.keyCode == 13) {
      shopAction.submit(id);
      return false;
    } else {
      return true;
    }
  },

  submitFormAjaxOnEnter: function(formId, targetId, event) {
    if (event.keyCode == 13) {
      shopAction.submitAjax(formId,targetId);
      return false;
    } else {
      return true;
    }
  },

  getDetailInformation : function(id){
    $.ajax({
      url: shop.baseUrl+'getPaketshopInformation',
      data: ({paketshopId: id}),
        dataType:'html',
        success: function (data) {
          $('#' + id).html(data);
          $('#' + id).css("margin-left", "0px");
        }
    });
    return false;
  },

  paketshopPaging : function(newPage,postalCode, onlySearch){
    $.ajax({
      url: shop.baseUrl+'pagePaketshop',
      data: ({postalCode: postalCode, p: newPage, onlySearch: onlySearch}),
      dataType:'html',
      success: function (data) {
        $('#sbcontent').html(data);
      }
    });
  },

  getItemForChange : function(itemId, index, simpleCheckout) {
    $.ajax({
      cache: false,
      url: shop.baseUrl+'getItemFromCartForChange',
      data: ({itemId: itemId, index: index, simpleCheckout: simpleCheckout}),
        dataType:'html',
        success: function (data) {
          $('#change_shopcart_position_' + index).html(data);
        }
    });
    return false;
  },

  submitAjax : function(formId, targetId, updateHeader) {
    var options = null;


    if (updateHeader) {
      options = {
          target:        '#'+targetId,
          cache:         false,
          success:       this.updateHeader
//          success:       this.debug
      };
    } else {
      options = {
          cache:         false,
          target:        '#'+targetId
//          success:       this.debug
      };
    }

    $('#'+formId).ajaxSubmit(options);
  },

  submitAjaxWithThrobber : function(formId, targetId, updateHeader, hideId, showId) {
    var options = null;


    if (updateHeader) {
      options = {
          beforeSend: function() {
            $('#'+hideId).hide();
            $('#'+showId).show();
          },
          target:        '#'+targetId,
          cache:         false,
          success:       this.updateHeader
      };
    } else {
      options = {
          beforeSend: function() {
            $('#'+hideId).hide();
            $('#'+showId).show();
          },
          cache:         false,
          target:        '#'+targetId
      };
    }

    $('#'+formId).ajaxSubmit(options);
  },


  submitSavingAccountUpdateShopcart : function(formId, targetId) {
    var options = {
        target:        '#'+targetId,
        cache:         false,
        success:       function(transport){
              $.post(shop.absoluteBaseUrl+"updateMiniBasket",
                  function(data){
                    $("#right_mini_basket").html(data);
                  });
            }
    };
    $('#'+formId).ajaxSubmit(options);

  },

  submitOldBasketCheckout : function(formId, targetId) {
 var options = null;
      var options = {
          cache:         false,
          target:        '#'+targetId,
          success:        function(transport){
        $.post(shop.absoluteBaseUrl+"updateMiniBasket",
            function(data){
              $("#right_mini_basket").html(data);
            });
      }
      };

    $('#'+formId).ajaxSubmit(options);
  },

  submit24hForm: function() {

   var options = {
        cache:         false,
        success:       function() {
         $.post(shop.absoluteBaseUrl+"updateMiniBasket",
             function(data){
               $("#right_mini_basket").html(data);
             });
        }
    };
    $('#24hForm').ajaxSubmit(options);
    osm.submit();
    Shadowbox.close();
  },

  initNormalDelivery: function() {
    $.post(shop.absoluteBaseUrl+"prepare24Selection",
        function() {
         $.post(shop.absoluteBaseUrl+"updateMiniBasket",
             function(data){
               $("#right_mini_basket").html(data);
             });
        });
    osm.submit();
  },

  submitAjaxChangeItem : function(formId, targetId,updateHeader,event, simpleCheckout) {
    var form = $('#'+formId);
    form.find('.mart').each(function () {
      var id = $(this).attr('id');
      var dim = id.substring(8,9);
      var value = form.find('#'+id+'_inp').val();
      form.find('input[name=dim'+dim+']').attr('value',value);
    });
    if(!event || event.keyCode==13){
      var options = {
            target:        '#'+targetId,
            cache:         false,
            success:       function(transport){
              this.updateHeader;
              if(simpleCheckout){
                shopAction.simpleAjaxRequest(shop.baseUrl+'updateTotalAmountOnShopcartSimple', 'total_amount_shopcart');
              }else{
                shopAction.simpleAjaxRequest(shop.baseUrl+'updateTotalAmountOnShopcart', 'total_amount_shopcart');
              }
            }
      };
      form.ajaxSubmit(options);
    }
  },

  simpleAjaxRequest : function(url, targetId, updateHeader) {
    $.ajax({
      cache: false,
      url: url,
      success: function(transport){
        if(updateHeader){
          if(url.indexOf("Notepad") != -1) {
            shopAction.updateNotepadHeader('','success');
          } else {
            shopAction.updateHeader('','success');
          }
        }
        $("#"+targetId).html(transport);
      }
      });
  },

  simpleAjaxRequestoutOfIFrame : function(url, targetId, targetFrame, updateHeader) {
    $.ajax({
      cache: false,
      url: url,
      success: function(transport){
        $('#'+targetId, targetFrame).html(transport);
      }
      });
  },

  submitAjaxWithInitStarRater : function(formId, targetId, updateHeader) {
    var options = {
        cache:         false,
        target:        '#'+targetId,
        success:      function(data) {
          var selected = $('#points :selected').val();
          var text = $('#points :selected').html();
          global.initStarRater('#article_detail_third_row div.star_rater');
          li_elem = $('#article_detail_third_row div.star_rater li');
          el_value = $('#article_detail_third_row div.star_rater div');
          li_elem.filter(':lt('+(selected)+')').addClass('active');
          el_value.text( text );



        }
    };

  $('#'+formId).ajaxSubmit(options);
  },

  submitAjaxWithValidation : function(formId, targetId, updateHeader) {
    var errors = false;
    $("#"+formId+" :input").each(function() {
      var element = $(this);
      if (element.val() == '') {
        errors = true;
        element.attr("class", "error");
        $("label[for='"+element.attr('id')+"']").attr("class", "error");
      } else {
        element.removeClass("error");
        $("label[for='"+element.attr('id')+"']").removeClass("error");
      };
    });

    if(!errors) {
      shopAction.submitAjax(formId, targetId, updateHeader);
    }
  },

  submitOnlyValid : function(id) {
    window.location = $('#'+id).attr("action") + "?" + $("#"+id+" :input[value][value!='.']").serialize();
  },

  updateHeader : function(responseText, statusText) {
    if (statusText == 'success') {
      $.ajax({
        cache: false,
        url: shop.absoluteBaseUrl+"updateHeader",
        success: function(transport){
          $("#session").html(transport);
        }
        });
    }
  },

  updateNotepadHeader : function(responseText, statusText) {
    if (statusText == 'success') {
      $.ajax({
        cache: false,
        url: shop.absoluteBaseUrl+"updateNotepadHeader",
        success: function(transport){
          $("#notepad_info").html(transport);
        }
      });
    }
  },

  debug : function(responseText, statusText) {
    alert('responseText '+responseText);
    alert('statusText '+responseText);
  },

  rateReview : function(reviewId, helpfull, productId){
    $.ajax({
      url: shop.baseUrl+"productdetail/rateReview",
      data: "reviewId="+reviewId+"&helpfull="+helpfull+"&productId="+productId,
      success: function(data) {
        $('#product_review_id_'+reviewId + " .helpful").html(data);

      }
    });
  },

  addAjax : function(url) {
    $.ajax({
      cache: false,
      url: url,
      success: this.updateHeader
      });
  },
  openGlossary : function(id, url) {
    window.location.href=url + "&gid=" + id;
  },

  changeFilter : function (preis) {

    var query = {};
    var search = window.location.search.replace(/^\?/, "").replace(/\+/g, "%20");

    if (search != "") {
      var t1 = search.split("&");
      for (var i=0;i<t1.length;i++) {
        var kv = t1[i].split("=", 2);
        query[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
      }
    }
    if (this.activeValue == null)
      delete query[this.activeFilter];
    else
      query[this.activeFilter] = this.activeValue;
    query["filter.preis"] = preis;
    window.location.search = $.param(query);
  },
updatePreisFilter : function (preis) {
    var range = preis.split('-');
    $('div.slider').each(function() {
      var el = $(this);
    var el_option_handle = el.find('.handle');
    var el_option_handle2 = el.find('.handle2');
    el_option_handle.text(range[0].split(' ')[0]);
    el_option_handle2.text(range[1].split(' ')[0]);
    });
  },
  ajaxRequestUpdateCartForm : function(itemId, index, view) {
    $.post(shop.absoluteBaseUrl+"getItemFromCartForChange", { itemId: itemId, index:index, view:view},
        function(data){
          $("#getItemFromCartForChange").html(data);
        });

  },

  addVoucher : function(isRequiredPaymentMethod, isFromShadowbox) {
    var code = $('#payment_method_coupon').val();
    if (code != null && code != '') {
      $.post(shop.absoluteBaseUrl+"addVoucher", { code: code, isRequiredPaymentMethod: isRequiredPaymentMethod, isFromShadowbox: isFromShadowbox },
          function(data){
            if (isFromShadowbox) {
              $("#voucherCodeShadowbox").html(data);
            } else {
              $("#voucherCode").html(data);
            }
            $('#payment_method_coupon').val("");
            $.post(shop.absoluteBaseUrl+"updateMiniBasket",
                function(data){
                  $("#right_mini_basket").html(data);
                  var $price = $('#basket_total_price').html();
                  $price = $price.substring(1);
                  $price = $price.replace(",",".");
                  $('#openRatenrechnerAt').attr('var1', $price);
                   var installment = shopAction.getInstallment($price);
                    if(installment > 0 ){
                      $("#bepaalt1").text(installment);
                    }else{
                      $('#ratePayment1').hide();
                    }
                });
          });
    }
  },

  removeVoucher : function(code) {
    if (code != null) {
      $.post(shop.absoluteBaseUrl+"removeVoucher", { code: code },
          function(data){
            $("#voucherCode").html(data);
            $.post(shop.absoluteBaseUrl+"updateMiniBasket",
                function(data){
                  $("#right_mini_basket").html(data);
                  var $price = $('#basket_total_price').html();
                  $price = $price.substring(1);
                  $price = $price.replace(",",".");
                   var installment = shopAction.getInstallment($price);
                   if(installment > 0 ){
                    $("#bepaalt1").text(installment);
                  }else{
                    $('#ratePayment1').hide();
                  }
                });
          });

    }
  },

  updateUserAddress: function(street,streetNumber, zipCode, city) {
    if(street != '')
      $('#update_new_street').val(street);
    if(streetNumber != '')
      $('#update_new_streetNumber').val(streetNumber);
    if(zipCode != '')
      $('#update_new_zipCode').val(zipCode);
    if(city != '')
      $('#update_new_city').val(city);
  },

  processCheckoutPaymentBoxes : function(choice, simpleCheckout) {
    $('input[name=payment_break]').attr('checked', false);
    $('input[name=xxl_protection]').attr('checked', false);
    shopAction.updateMiniBasketForPayment(choice, simpleCheckout);
  },

  checkPaymentCachondeliveryHit : function() {
    if($('#payment_method_cash_on_delivery').attr('checked')){
      $('#payment_cachondelivery_hit').show();
      $('#cashOnDeliveryCharge').show();
    }else{
      $('#payment_cachondelivery_hit').hide();
      $('#cashOnDeliveryCharge').hide();
    }
  },

  updateMiniBasketForPayment : function(choice, simpleCheckout) {
    if(simpleCheckout) {
      shopAction.simpleAjaxRequest(shop.absoluteBaseUrl+'simpleUpdateMiniBasketPrice?paymentMethod='+$(choice).val(),'basket_total_price');
    } else {
      var payment_break = '';
      var xxl_protection = '';
      if($(choice).val() == 'payment_method_installments') {
        if ($('#payment_break_installments').attr('checked')) {
          payment_break = 'on';
        }
        if ($('#xxl_protection').attr('checked')) {
          xxl_protection = 'on';
        }
      }
      if($(choice).val() == 'payment_method_complete' && $('#payment_break_bank_transfer').attr('checked')) {
          payment_break = 'on';
      }
      shopAction.simpleAjaxRequest(shop.absoluteBaseUrl+'updateMiniBasketPrice?paymentMethod='+$(choice).val()+'&payment_break='+payment_break+'&xxl_protection='+xxl_protection,'right_mini_basket');
    }
  },

  processRadioPaymentBoxes : function(checkbox, radiobox) {
    if(checkbox.id == 'payment_break_bank_transfer'){
      $('input[name=xxl_protection]').not(checkbox).attr('checked', false);
      $('#payment_break_installments').attr('checked', false);
    }else{
      $('#payment_break_bank_transfer').attr('checked', false);
    }
    $('input[name=payment_method]').attr('checked', false);
    $('#'+radiobox).attr('checked', true);
    shopAction.updateMiniBasketForPayment($('#'+radiobox), false);
  },

  openPopUp : function(url) {

      var MyWindow;
       MyWindow = open(
         url,
         "confirmation",
         "width=800, height=700, resizable=yes, scrollbars=yes, directories=no, menubar=no, location=no");
       MyWindow.focus();
  },

  callbackOpenPopUp : function(url) {
    var MyWindow;
     MyWindow = open(
       url,
       "confirmation",
       "width=800, height=820, left=100,top=200,location=no,menubar=no,resizable=no,scrollbars=yes,status=no");
     MyWindow.focus();
},

  refreshIFrameById : function(iframeId) {
    jQuery.each($("#"+iframeId, window.parent.document), function() {
      $(this).attr({
        src: $(this).attr("src")
      });
    });
    return false;
  },

  refreshIFrameByJQueryObject : function(iFrame) {
      iFrame.attr({
        src: iFrame.attr("src")
      });
    return false;
  },

  closeOverlay : function(id) {
    var obj = $('#'+id);
    $(obj).find("a.overlay_close").click();
  },

  getInstallment: function(basketPrice) {
    var ar = this.getInstallmentMap();
    var last = 0;
    for (i=0; i < ar.length; i++) {
      if (parseFloat(basketPrice) > parseFloat(ar[i].split("=")[0])) {
        last = parseFloat(ar[i].split("=")[1]);

      }
    }
    return last;
  },


  showBundles : function(productId) {
    var url = shop.absoluteBaseUrl + "displayBundles?productId=" + productId;
    $.get(url, function(text) {
      $('#carouselBody').html(text);
      global.initCarousel('div.carousel div.js');
    });
  },

  show : function(id) {
    $("#"+id).removeClass("hidden");
  },

  hide : function(id) {
    $("#"+id).addClass("hidden");
  },

  showOverlay : function(id) {
    $('#'+id).overlay({
      absolute: false,
      top: 'center',
      zIndex: 10002,
      close: 'a.jsclose',
      api: true,
      expose: {
        color: '#000',
        loadSpeed: 'normal',
        opacity: 0.1,
        zIndex: 10001
      }
    }).load();
  },

  // Nur noch aus Kompatibilitaetsgruenden. Bitte nicht mehr benutzen, stattdessen openBox() nutzen!
  openPanel : function(url, title, x, y, updateHeader, modal){

    // open a welcome message as soon as the window loads
    if (x == null && y == null) {
      x = 300;
      y = 300;
    }
    if (modal == null) {
    	modal = false;
    }

    Shadowbox.open({
        content:    '<span id="shadowboxMsg"></span>',
        player:     "html",
        title:      title,
        height:     y,
        width:      x,

        options: {
          onFinish: function () {
            $("#shadowboxMsg").append(loader);
            $("#shadowboxMsg img").css("margin-top", 42 + "px" );
            $("#shadowboxMsg img").css("margin-left", (x/2 - 12) + "px" );
            shopAction.simpleAjaxRequest(url, 'shadowboxMsg', updateHeader);
          },
          enableKeys: false,
          modal: modal
        }
    });

  },

  //Oeffnet eine Shadowbox
  openBox : function(url, title, x, y, player, updateHeader, modal){

    // open a welcome message as soon as the window loads
    if (x == null && y == null) {
      x = 300;
      y = 300;
    }
    if (player == null) {
      player = "html";
    }
    if (modal == null) {
    	modal = false;
    }

    Shadowbox.open({
        content:    '<div id="shadowboxContent"></div>',
        player:     player,
        title:      title,
        height:     y,
        width:      x,

        options: {
          onFinish: function () {
            $("#shadowboxContent").append(loader);
            $("#shadowboxContent img").css("margin-top", 42 + "px" );
            $("#shadowboxContent img").css("margin-left", (x/2 - 12) + "px" );
            shopAction.simpleAjaxRequest(url, 'shadowboxContent', updateHeader);
            },
          enableKeys: false,
          modal: modal
        }
    });

  },

  openPanelForceUserToSubmitContent : function(url, title, x, y, updateHeader){

    // open a welcome message as soon as the window loads
    if (x == null && y == null) {
      x = 300;
      y = 300;
    }

    Shadowbox.open({
        content:    '<span id="shadowboxMsg"></span>',
        player:     "html",
        title:      title,
        height:     y,
        width:      x,
        options: {onFinish: function () {
        $("#shadowboxMsg").append(loader);
        $("#shadowboxMsg img").css("margin-top", 42 + "px" );
        $("#shadowboxMsg img").css("margin-left", (x/2 - 12) + "px" );
        $('#sb-nav-close').removeAttr("onclick");
        $('#sb-nav-close').hide();

        shopAction.simpleAjaxRequest(url, 'shadowboxMsg', updateHeader);

                  },
                  enableKeys: false,
                  modal:      true
        }
    });
  },

  showServiceSouthTyrol : function(boxValue){
    shopAction.simpleAjaxRequest(shop.baseUrl+'service/service?view='+boxValue, 'sbcontent');
  },

  openPanelS : function(text, title, x, y){

    // open a welcome message as soon as the window loads
    if (x == null) {
      x = 300;
    }
    if (y == null) {
      y = 400;
    }
    Shadowbox.open({
        content:    text,
        player:     "html",
        title:      title,
        height:     y,
        width:      x,
        options: {
          enableKeys: false
        }
    });
  },
  popup : function (url, title, x, y, param) {
    if (x == null) {
      x = 300;
    }
    if (y == null) {
      y = 400;
    }

    if(typeof param == 'undefined') {
      url += (url.lastIndexOf("?") == -1 ? "?" : "&") + "clickedPopup=true";
    } else if (param != ''){
      url += (url.lastIndexOf("?") == -1 ? "?" : "&") + param;
    }

    if (y == null && x == null) {


      try {
        fenster = window.open(url, title, "resizable=yes");
        } catch (e) {
          alert(e.message);
        }
    } else {
      try {
      fenster = window.open(url, title, "width=" + x + ",height=" + y + ",resizable=yes");
      } catch (e) {
        alert(e.message);
      }
    }
    fenster.focus();
    return false;
   },
   trackKeys : function (evnt,regEx) {
     var keyCode = evnt.keyCode ? evnt.keyCode : evnt.which;
     // console.debug(keyCode);
   return !!String.fromCharCode(keyCode).match(regEx) || keyCode>=36 && keyCode<41 || keyCode==8 ;
    },
    switchLocation : function(url) {
      window.location=url;
    },

    validateEmailField: function (formId, userId, targetId) {
      var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
      var form = $('#' + formId);
      var email = $('#'+ userId, form).removeClass('ErrorBorder');
      var msg = '';
      if (email.val() == '') {
        msg += email.attr('custom:msg1');
        email.addClass('ErrorBorder');
      } else if (!filter.test(email.val())) {
        msg += email.attr('custom:msg2');
        email.addClass('ErrorBorder');
      }
      if (msg == '') {
        shopAction.submitAjax(formId, targetId);
      } else {
        var errorInfo = $('#ClientsiteErrorInfo', form);
        errorInfo.addClass('ErrorInfo').attr('width: 480px');
        errorInfo.html(msg);
      }
      return false;
    },

  hasCookiesEnabled : function() {
    $.cookie("cookiecheck", "done", { path: '/' });
    cookieValue = $.cookie("cookiecheck");
    $.cookie("cookiecheck", null, { path: '/' });
    return cookieValue == "done";
  },

  openRatenrechnerADS : function(url, title, width, height) {
    var price = $("#NewPriceValue");
    if (price.text() != '') {
      price = price.text().replace(/[^0-9,]/g, "");
      url += "&value=" + price;
    }
    shopAction.openPanel(url, title, width, height);
  },

  switchRating : function(active) {
    if ($('#ratingImage').size() > 0) {
      $('#ratingImage').children().hide();
      if (active)
        $('#ratingActive').show();
      else
        $('#ratingInactive').show();
    }
  },

  checkAdobeFlash : function(boxUrl, title, successAction) {
    var hasReqestedVersion = DetectFlashVer(8, 0, 0); // AC_OETags.js
    if (hasReqestedVersion == false) {
      shopAction.openPanel(boxUrl, '<img src="' + title + '" style="position: relative; top: -45px;" />', 555, 425);
      return false;
    } else if (successAction != undefined) {
      successAction();
      return false;
    }
    return true;
  },

  getInstallmentMap : function() {
    var ar = new Array();
    ar.push("75=7");
    ar.push("358=8");
    ar.push("405=9");
    ar.push("453=10");
    ar.push("500=11");
    ar.push("548=12");
    ar.push("596=13");
    ar.push("644=14");
    ar.push("691=15");
    ar.push("739=16");
    ar.push("787=17");
    ar.push("834=18");
    ar.push("882=19");
    ar.push("930=20");
    ar.push("977=21");
    ar.push("1025=22");
    ar.push("1073=23");
    ar.push("1120=24");
    ar.push("1168=25");
    ar.push("1215=26");
    ar.push("1262=27");
    ar.push("1310=28");
    ar.push("1358=29");
    ar.push("1405=30");
    ar.push("1453=31");
    ar.push("1501=32");
    ar.push("1548=33");
    ar.push("1596=34");
    ar.push("1644=35");
    ar.push("1691=36");
    ar.push("1739=37");
    ar.push("1787=38");
    ar.push("1834=39");
    ar.push("1882=40");
    ar.push("1930=41");
    ar.push("1977=42");
    ar.push("2025=43");
    ar.push("2073=44");
    ar.push("2120=45");
    ar.push("2168=46");
    ar.push("2215=47");
    ar.push("2262=48");
    ar.push("2310=49");
    ar.push("2358=50");
    ar.push("2405=51");
    ar.push("2453=52");
    ar.push("2501=53");
    ar.push("2548=54");
    ar.push("2596=55");
    ar.push("2644=56");
    ar.push("2691=57");
    ar.push("2739=58");
    ar.push("2787=59");
    ar.push("2834=60");
    ar.push("2882=61");
    ar.push("2930=62");
    ar.push("2977=63");
    ar.push("3025=64");
    ar.push("3073=65");
    ar.push("3120=66");
    ar.push("3168=67");
    ar.push("3215=68");
    ar.push("3262=69");
    ar.push("3310=70");
    ar.push("3358=71");
    ar.push("3405=72");
    ar.push("3453=73");
    ar.push("3501=74");
    ar.push("3548=75");
    ar.push("3596=76");
    ar.push("3644=77");
    ar.push("3691=78");
    ar.push("3739=79");
    ar.push("3787=80");
    ar.push("3834=81");
    ar.push("3882=82");
    ar.push("3930=83");
    ar.push("3977=84");
    ar.push("4025=85");
    ar.push("4073=86");
    ar.push("4120=87");
    ar.push("4168=88");
    ar.push("4215=89");
    ar.push("4262=90");
    ar.push("4310=91");
    ar.push("4358=92");
    return ar;
  },

  encodeMailAddress : function(recipient, domain, countryCode, bold, ajax, text) {
    e=recipient+'&#64;'+domain+'&#46;'+countryCode;
    if (text != null)
      e2 = text;
    else
      e2 = e;
    a1='<a href="mai' + 'lto:';
    a2='">';
    a3='</a>';
    b1='<b>';
    b2='</b>';
    if (ajax != null) {
      if (bold)
        $('#'+ajax).html(a1+e+a2+b1+e2+b2+a3);
      else
        $('#'+ajax).html(a1+e+a2+e2+a3);
    } else {
      if (bold)
        document.write(a1+e+a2+b1+e2+b2+a3);
      else
        document.write(a1+e+a2+e2+a3);
    }
  },

  trimEmailAndPassword: function() {
    var email = $('#email');
    var password = $('#password');
    email.val($.trim(email.val()));
    password.val($.trim(password.val()));
  },

  changeItemAndUpdateAvailability: function(itemId, context, index) {
    viewerModel.setItem(itemId, context);
    var item = viewerModel.getItemById(itemId);
    $('#availability'+index).html(item.availability);
    $('#orderNo'+index).html(item.artNo);
    $('#price'+index).html(item.price);
    $('#oldPrice'+index).html(item.oldPrice);
    $.ajax({
      url: shop.baseUrl+'changeItemData',
      data: ({itemId: itemId, index: index}),
      success: function(data) {
        $('#changedAttributes').html(data);
      }
    });
  },

  shopCartToggleGuarantee: function(checkbox, index, itemId, simpleCheckout) {
    if (simpleCheckout) {
      var updateCart = 'updateCartSimple';
    } else {
      var updateCart = 'updateCart';
    }
    if ($(checkbox).is(':checked')) {
      var guaranteeAction = 'add';
    } else {
      var guaranteeAction = 'remove';
    }
    $.ajax({
      cache: false,
      url: shop.baseUrl + updateCart,
      data: {
        index: index,
        guarantee: guaranteeAction,
        newItemId: itemId,
        currentItemId: itemId          
      },
      success : function(data) {
        $('#change_shopcart_position_' + index).html(data);
        if(simpleCheckout){
          shopAction.simpleAjaxRequest(shop.baseUrl+'updateTotalAmountOnShopcartSimple', 'total_amount_shopcart');
        }else{
          shopAction.simpleAjaxRequest(shop.baseUrl+'updateTotalAmountOnShopcart', 'total_amount_shopcart');
        }
      }
    });
  }
};

function getNextField(thisFieldId, nextFieldId, maxLength, event) {
  var value = $('#'+thisFieldId).val();
  if(value.length == maxLength && event.keyCode != 9 && event.keyCode != 16 && event.keyCode != 37 && event.keyCode != 38 && event.keyCode != 39 && event.keyCode != 40){
    $('#'+nextFieldId).focus();
  }else{
    $('#'+thisFieldId).focus();
  }
}

function setMaxLengthToField(inputFieldIdToSetLength, dependentInputFieldId){
  var value = $('#'+dependentInputFieldId).val();
  var maxLength = 10;
  for(i=0; i<=10;i++) {
    if(value.length == i){
      maxLength = 10-i;
    }
  }
  $('#'+inputFieldIdToSetLength).attr("maxlength", maxLength);
}

function validateIntInInputField(inputFieldId, maxInt){
  var value = $('#'+inputFieldId).val();
  if(value > maxInt){
    $('#'+inputFieldId).addClass('ErrorBorder');
  }else{
    $('#'+inputFieldId).removeClass('ErrorBorder');
  }
}

//endsWith-Funktion fuer Strings
String.prototype.endsWith = function(str)
{return (this.match(str+"$")==str)}

/*
 * Zustaendig fuer die Anzeige und Ausblendung eines Eingabehinweises
 * in Eingabefeldern
 */
var inputHintListener = {
  bind : function(item, hintText, hintStyle, normalStyle) {
    var virginFocus = true;
    if (item.val() == '' ) {
      item.val(hintText).attr('style', hintStyle);
    }
    else if (item.val() != hintText) {
      virginFocus = false;
    }
    item.focus(function(){
      item.attr('style', normalStyle);
      if (virginFocus) {
        item.val('');
        virginFocus = false;
      }
    });
    item.blur(function(){
      if (item.val() == '') {
        item.val(hintText).attr('style', hintStyle);
        virginFocus = true;
      }
    });
  }
};

var ratenzahlungAt = {

    q : 0.0165, // Zinsfaktor, monatlich

    getLaufzeitN : function (bw, rate) {
      var lzn = this.getLaufzeit(bw, rate);
      lzn = Math.floor(lzn);
      return lzn;
    },
    getLaufzeit : function (bw, rate) {
      rate = rate * 1;
      var lz = this.zzr(this.q, rate, bw, 0);
      return lz;
    },
    getMindestRate : function (bw) { // ok
      var mindestrate = 10;
      if ( bw > 100 ) mindestrate = 12;
      if ( bw > 150 ) mindestrate = 14;
      if ( bw > 360 ) mindestrate = 15;
      if ( bw > 400 ) mindestrate = 16;
      if ( bw > 500 ) mindestrate = 19;
      if ( bw > 600 ) mindestrate = 22;
      if ( bw > 700 ) mindestrate = Math.ceil(0.030324 * bw);
      return mindestrate;
    },
    getWunschRate : function (lzw, bw) {
      var q = this.q;
      var z = this.q * Math.pow(1 + this.q, lzw);
      var n = Math.pow(1 + this.q, lzw) - 1;
      var result = bw * z / n;
      result = Math.floor(result);
      return result;
    },
    zzr : function (zins, rmz, bw) {
      var zzr =Math.log((zins+(rmz*(-1))/bw)/((rmz*(-1))/bw))/Math.log(1/(1+zins));
      return zzr;
    },
    getLetzteRate : function(bw, rate) {
      return rate * (1 + (this.getLaufzeit(bw, rate) - this.getLaufzeitN(bw, rate)));
    },
    getLetzteWunschRate : function(bw, rate, lzw) {
      return rate * (1 + (this.getLaufzeit(bw, rate) - lzw));
    },
    getEffZinsAnno : function() {
      return 21.7;
    },
    format : function(value) {
      var result = (1 * value).toFixed(2) + "";
      result = result.replace(/\./,",");
      return result;
    }
  };

var ratenzahlungNl = {

    q : 0.013584, // Zinsfaktor, monatlich

    getLaufzeitN : function (bw, rate) {
      var untergrenzeMindestRaten = 15;
      lzn = this.getLaufzeitM(bw, rate);
      letzeRate = this.getLetzteRateM(bw,rate);
      if(letzeRate < untergrenzeMindestRaten) {
        lzn = lzn - 1;
      }
      return lzn;
    },
    getLaufzeitM : function (bw, rate) {
      var lzn = this.getLaufzeit(bw, rate);
      lzn = Math.ceil(lzn);
      return lzn;
    },
    getLaufzeit : function (bw, rate) {
      rate = rate * 1;
      var lz = this.zzr(this.q, rate, bw, 0);
      return lz;
    },
    getMindestRate : function (bw) {
      var mindestrate = 7;
      var faktor = 0.021;
      var untergrenzeSaldo = 250;
      if (bw > untergrenzeSaldo) mindestrate = Math.ceil((bw*faktor).toFixed(2));
      return mindestrate;
    },
    getWunschRate : function (lzw, bw) {
      var q = this.q;
      var z = this.q * Math.pow(1 + this.q, lzw);
      var n = Math.pow(1 + this.q, lzw) - 1;
      var result = bw * z / n;
      result = Math.floor(result);
      return result;
    },
    zzr : function (zins, rmz, bw) {
      var zzr =Math.log((zins+(rmz*(-1))/bw)/((rmz*(-1))/bw))/Math.log(1/(1+zins));
      return zzr;
    },
    getLetzteRateM : function(bw, rate) {
      return rate * (1 + (this.getLaufzeit(bw, rate) - this.getLaufzeitM(bw, rate)));
    },
    getLetzteRate : function(bw, rate) {
      return rate * (1 + (this.getLaufzeit(bw, rate) - this.getLaufzeitN(bw, rate)));
    },
    getLetzteWunschRate : function(bw, rate, lzw) {
      return rate * (1 + (this.getLaufzeit(bw, rate) - lzw));
    },
    getEffZinsAnno : function() {
      return 16.0;
    },
    format : function(value) {
      var result = (1 * value).toFixed(2) + "";
      result = result.replace(/\./,",");
      return result;
    }
  };

