/* ------------------------------------------------------------------------
  Author: GX
------------------------------------------------------------------------- */

$(function() {
  
    function formatCurrency(num) {
      num = num.toString().replace(/\$|\,/g, '');
      if (isNaN(num)) num = "0";
      sign = (num == (num = Math.abs(num)));
      num = Math.floor(num * 100 + 0.50000000001);
      cents = num % 100;
      num = Math.floor(num / 100).toString();
      if (cents < 10) cents = "0" + cents;
      for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
      num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
      return (((sign) ? '' : '-') + num + ',' + cents);
    }
  
    $('#accordion').accordion({
      header: 'div.accord',
      autoheight: false,
      active: '.selected',
      event: 'mouseover'});

    $(".thumbs a").prepend("<img src=\"/wm/f/e.gif\" style=\"display: none;\" />");

    window.bind_click = function(){
      // remove ALL click handlers - including PrettyPhoto.click()
      $('.show-bigger').unbind('click');

      // Show 2nd size image in bigger image box
      // allow 3rd size image to be shown in prettyphoto box.
      $('.show-bigger').click(function(){
        relSplit = this.rel.split(/\s/);

        image_id = relSplit[1];
        image_url = relSplit[2];

        $('#' + image_id).attr('src', image_url);
        $('#' + image_id).attr('alt', this.childNodes[1].alt);
        $('#' + image_id).parent().attr('href', this.href);
        $('#zoomImg').attr('href', this.href);

        return false;
      });
    }
    window.bind_click();


    $('#products-navigation a').live("click",function () {
      pageNr = $(this).attr('name');
      sortOption = $('#selectSort').val();
      amountPerPage = $('#selectNumb').val();
      sortProducts(amountPerPage,sortOption, pageNr);
    });


    $('#selectSort, #selectNumb').change(function() {
      sortOption = $('#selectSort').val();
      amountPerPage = $('#selectNumb').val();
      pageNr = getPageNr();
      sortProducts(amountPerPage,sortOption, pageNr);
    });

    getPageNr = function() {
      pageNr = '1';
      $('#products-navigation a').each(function (i) {
        if ($(this).attr('class') == 'active') {
          pageNr = $(this).attr('name');
        }
      });
      return pageNr;
    };

    sortProducts = function(amount, sort, pagenr) {
      var url = $('#ajaxUrl').attr('href');
      if (url.indexOf('?') != -1) {
        prefix = '&';
      } else {
        prefix = '/';
      }
      url = url + prefix + 'sort=' + sort;
      url = url + prefix + 'amount=' + amount;
      url = url + prefix + 'pagenr=' + pagenr;

      $.ajax({
      url: "" + url + "",
      success: function(html){
    	  $("#prodResults").html(html);
    	  $('#products-navigation').clone(true).appendTo('#prodResults');
        }
      });
    };

    function resetSizes() {
      $('#detailSizes a').each(function (i) {
        if ($(this).attr('class') == 'active') {
          $(this).attr('class','');
        }
      });
    };

    $('#detailAddToShopCart').click(function() {
      id = $('#productVariantId').attr('value');

      if (id != '') {
        var url = '/web/wcbservlet/nl.gx.product.wmpshopservlets.impl.Add?';

        url = url + 'id=' + id;
        amount = $('#quantity2').attr('value');
        if (amount != null && amount != '') {
          url = url + '&nrofitems=' + amount;
        }
        redirurl = $('#redirectUrl').attr('value');
        url = url + '&redirurl=' + redirurl;
        window.location.href = url;
      }
      return false;
    });

    function searchProductsKeyword() {
      keyword = $('#search-box-searchfield').val();
      if (keyword != null && keyword != '') {
        var url = $('#search-box-searchbutton').attr('href');
        var prefix  = '/';
        if (url.indexOf('?') != -1) {
          prefix = '&';
        } else {
          if (url.indexOf('.htm') != -1) {
            prefix = '?';
          }
        }
        url = url + prefix + 'keyword=' + keyword;
        window.location.href = url;
      }
    }

    $('#search-box-searchbutton').click(function(event) {
      event.preventDefault();
      searchProductsKeyword();
    });

    $('#search-box-searchfield').keyup(function(e) {      
      if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
        searchProductsKeyword();
      }
    });
    
    /**
     * field is a JQuery object.
     */
    function calculateTotalCost(field) {
      methodcost = parseFloat(field.text())
      if (methodcost > 0.0) {
        // remove thousands-dot, replace comma with dot. from: 2.346,12 to 2346.12
        price = parseFloat($('#base-cost .value').text().replace(".", "").replace(",", "."));
        totalprice = price + methodcost;
        // format the number back again.
        totalPrice = formatCurrency(totalprice);
        
        $('#payment-method-cost .value').text(formatCurrency(methodcost));
        $('#payment-method-cost').show();
        $('#total-cost .value').text(totalPrice);
        $('#total-cost').show();
      } else {
        // do not show / hide payment method cost / totals if there's no
        // extra price.
        $('#payment-method-cost').hide();
        $('#total-cost').hide();
      }
    }

    $('.checkout input[type=radio]').click(function() {
      calculateTotalCost($($(this).parents('.form-wrap')[0]).children('.additional-costs-value:first'));
    });
});
