
$(window).load(function() {
  // height-equalizer for tiles
  // in window.load because the heights can not always be calculated correctly
  // in document.ready
  $('.tileline').each(function() {
    stn_equal_height_array($.map($('.tile', this), function(n, i) { return $('h2', n); })); 
    stn_equal_height_array($.map($('.tile', this), function(n, i) { return $('.content', n); })); 
  });
});

$(document).ready(function() {
//  $(window).bind("resize", delayed_resizer);

  $('#banner').html('<embed src="/style/banner.swf" width="222" height="90" menu="false" wmode="opaque"/>');

  $('#menu-search a').click(function() { 
    $('#menu-search').toggleClass('active');
    return false; 
  });

  var lightboxoptions = {
    animationSpeed: 'normal',
    padding: 40,
    opacity: 0.40,
    showTitle: false,
    allowresize: false,
    theme: 'light_rounded'
  };
  $('a[rel^=lightbox]').prettyPhoto(lightboxoptions);

  $('.product .info a.lightbox img').each(function() {
    var imgheight = $(this).height() + 20;
    $('.product .info').css({'minHeight':imgheight, '_height':imgheight});
  });

  $('a.basket-toggler').click(function() {
    return basket_toggler(this);
  });

  $('a.basket-delete').click(function() {
    return basket_delete(this);
  });

  $('a.basket-update').click(function() {
    return basket_update(this);
  });

  $('a.basket-add').click(function() {
    return basket_add(this);
  });

  $('a.barcode-add').click(function() {
    return barcode_add(this);
  });

  $('input[name=labelform_update_list]').click(function() {
    barcode_update_list($('#labelform-artnrs').val());
    return false;
  });

  $('form.track-changes').each(function() {
    var track_form = this;
    $('input, textarea, select', track_form).change(function() {
      $('.track-changes-unchanged').css({display:'none'});
      $('.track-changes-changed').css({display:'block'});
      $(this).addClass('changed');
    });
  });

});
window.onload = function() { 
  resizer(); 
  $(window).bind("resize", delayed_resizer);
}

var resize_timeout = null;
function delayed_resizer()
{
    if (resize_timeout) window.clearTimeout(resize_timeout);
    resize_timeout = window.setTimeout(resizer, 100);
}

function resizer()
{
  var footerheight = $('#footer').height();
  var windowheight = $(window).height();

  var content = $('#content');

  if (!content.length) return;

  var contentdim = dimensions(content);
  var contentheight = contentdim.h + contentdim.mt + contentdim.mb + contentdim.bt + contentdim.bb + contentdim.pt + contentdim.pb;
  var mincontentheight = windowheight - content.offset().top - footerheight;

  if (contentheight < mincontentheight) {
    content.height(mincontentheight - (contentdim.mb + contentdim.bt + contentdim.bb + contentdim.pt + contentdim.pb));
  }

}

function dimensions(e) {
  return { w: $(e).width(),
           h: $(e).height(),
           mt: parseInt('0'+$(e).css('margin-top'), 10),
           mr: parseInt('0'+$(e).css('margin-right'), 10),
           mb: parseInt('0'+$(e).css('margin-bottom'), 10),
           ml: parseInt('0'+$(e).css('margin-left'), 10),
           pt: parseInt('0'+$(e).css('padding-top'), 10),
           pr: parseInt('0'+$(e).css('padding-right'), 10),
           pb: parseInt('0'+$(e).css('padding-bottom'), 10),
           pl: parseInt('0'+$(e).css('padding-left'), 10),
           bt: parseInt('0'+$(e).css('border-top-width'), 10),
           br: parseInt('0'+$(e).css('border-right-width'), 10),
           bb: parseInt('0'+$(e).css('border-bottom-width'), 10),
           bl: parseInt('0'+$(e).css('border-left-width'), 10)
           };
}

/* baskets */
function basket_toggler(a)
{
  var href = $(a).attr('href');
  var prev_html = $(a).html();
  $(a).html('<img src="/style/icons/ajax-loader.gif"/>');
  $.ajax({
    url: href,
    type: 'POST',
    data: {'returntype':'json'},
    dataType: "json",
    error: function(req, resulttype, exc)
    { 
      $(a).html('<img src="/style/icons/fav-error.gif"/>');
      window.setTimeout(function() { $(a).html(prev_html); }, 3000);
    },
    success: function(data)
    {
      if (data['result']==1) {
        $(a).replaceWith(data['html']);
        $('a.basket-toggler').unbind('click');
        $('a.basket-toggler').click(function() {
          return basket_toggler(this);
        });
      }
      else {
        $(a).html('<img src="/style/icons/fav-error.gif"/>');
        window.setTimeout(function() { $(a).html(prev_html); }, 3000);
      }
    }
  });
  return false;
}

function basket_delete(a)
{
  var aparent = $(a).parent().eq(0);
  aparent.append('<div class="basket-delete"><a href="#confirm"><img src="/style/icons/basket_delete-confirm.png" alt="Bevestig verwijderen" title="Bevestig verwijderen"/></a></div>');
  aparent.css({position:'relative', zIndex:'10'});
  var confirm_div = $('div', aparent);
  var confirmlink = $('a', confirm_div);
  confirmlink.focus();

  confirmlink.blur(function(e) {
      confirm_div.remove();
      return false;
  });

  confirmlink.click(function(e) {
    var href = $(a).attr('href');
    var prev_html = $(a).html();
    confirm_div.remove();
    $(a).html('<img src="/style/icons/ajax-loader.gif"/>');
    $.ajax({
      url: href,
      type: 'POST',
      data: {'returntype':'json'},
      dataType: "json",
      error: function(req, resulttype, exc)
      { 
        $(a).html('<img src="/style/icons/basket_delete-error.png"/>');
        window.setTimeout(function() { $(a).html(prev_html); }, 3000);
      },
      success: function(data)
      {
        if (data['result']==1) {
          $(a).parents('tr').eq(0).remove();
          // update totals!
          if (data['basket_total']) {
            $('#basket_total').html(data['basket_total']);
          }
        }
        else {
          $(a).html('<img src="/style/icons/basket_delete-error.png"/>');
          window.setTimeout(function() { $(a).html(prev_html); }, 3000);
        }
      }
    });
    return false;
  });

  return false;
}

function basket_update(a)
{
  var href = $(a).attr('href');
  var prev_html = $(a).html();
  // the last entry in the href is the quantity
  var slashpos = href.lastIndexOf('/');
  if (slashpos==-1) {
    e.preventDefault();
    e.stopPropagation();
    return false;
  }
  var hrefq = href.substring(0, slashpos);
  var prevq = parseFloat(prev_html);

  var aparent = $(a).parent().eq(0);
  aparent.append('<form class="basket-update"><input type="text" name="quantity" value="'+prevq+'"/></form>');
  aparent.css({position:'relative', zIndex:'10'});
  var update_article_form = $('form', aparent);
  var quantityinput = $('input', update_article_form);
  quantityinput.focus();
  quantityinput.val(prevq);
  quantityinput.select();

  quantityinput.blur(function(e) {
      update_article_form.remove();
      return false;
  });

  quantityinput.keydown(function(e) {

    if (e.keyCode==13) { // Enter
      var quantity = quantityinput.val();
      quantity = quantity.replace(',', '.');
      quantity = parseFloat(quantity);
      update_article_form.remove();
      if (!isNaN(quantity)) {
        hrefq = hrefq + '/' + quantity;
        $(a).html('<img src="/style/icons/ajax-loader.gif"/>');
        $.ajax({url: hrefq,
                type: 'POST',
                data: {'returntype':'json'
                       },
                dataType: "json",
                error: function() {
                  $(a).html('<img src="/style/icons/basket_error.png"/>');
                  window.setTimeout(function() { $(a).html(prev_html); }, 3000);
                  },
                success: function(data) {
                  if (data['result']==1) {
                    $(a).html(quantity);
                    // update totals!
                    if (data['item_subtotal']) {
                      $('.subtotal', $(a).parents('tr').eq(0)).html(data['item_subtotal']);
                    }
                    if (data['basket_total']) {
                      $('#basket_total').html(data['basket_total']);
                    }
                  }
                  else {
                    var title = '';
                    if (data['message']) title = ' title="'+data['message']+'"';
                    $(a).html('<img src="/style/icons/basket_error.png"'+title+'/>');
                    var messagetimeout = window.setTimeout(function() { $(a).html(prev_html); }, 10000);
                    $('img', a).click(function(e) { window.clearTimeout(messagetimeout); $(a).html(prev_html); e.preventDefault(); e.stopPropagation(); return false; });
                  }
                }
               });
      }
      e.preventDefault();
      e.stopPropagation();
      return false;
    }

    if (e.keyCode==27) { // Esc
      update_article_form.remove();
      return false;
    }
  });

  return false;
}

function basket_add(a)
{
  var href = $(a).attr('href');
  var prev_html = $(a).html();
  // the last entry in the href is the quantity
  var slashpos = href.lastIndexOf('/');
  if (slashpos==-1) {
    e.preventDefault();
    e.stopPropagation();
    return false;
  }
  var hrefq = href.substring(0, slashpos);
  var prevq = href.substring(slashpos + 1);

  var aparent = $(a).parent().eq(0);
  aparent.append('<form class="basket-add"><input type="text" name="quantity" value="1"/></form>');
  aparent.css({position:'relative', zIndex:'10'});
  var add_article_form = $('form', aparent);
  var quantityinput = $('input', add_article_form);
  quantityinput.focus();
  quantityinput.val('1');
  quantityinput.select();

  quantityinput.blur(function(e) {
      add_article_form.remove();
      return false;
  });

  quantityinput.keydown(function(e) {

    if (e.keyCode==13) { // Enter
      var quantity = quantityinput.val();
      quantity = quantity.replace(',', '.');
      quantity = parseFloat(quantity);
      add_article_form.remove();
      if (!isNaN(quantity)) {
        hrefq = hrefq + '/' + quantity;
        $(a).html('<img src="/style/icons/ajax-loader.gif"/>');
        $.ajax({url: hrefq,
                type: 'POST',
                data: {'returntype':'json'
                       },
                dataType: "json",
                error: function() {
                  $(a).html('<img src="/style/icons/basket_error.png"/>');
                  window.setTimeout(function() { $(a).html(prev_html); }, 3000);
                  },
                success: function(data) {
                  if (data['result']==1) {
                    $(a).html('<img src="/style/icons/basket_success.png"/>');
                    window.setTimeout(function() { $(a).html(prev_html); }, 3000);
                  }
                  else {
                    var title = '';
                    if (data['message']) title = ' title="'+data['message']+'"';
                    $(a).html('<img src="/style/icons/basket_error.png"'+title+'/>');
                    var messagetimeout = window.setTimeout(function() { $(a).html(prev_html); }, 10000);
                    $('img', a).click(function(e) { window.clearTimeout(messagetimeout); $(a).html(prev_html); e.preventDefault(); e.stopPropagation(); return false; });
                  }
                }
               });
      }
      e.preventDefault();
      e.stopPropagation();
      return false;
    }

    if (e.keyCode==27) { // Esc
      add_article_form.remove();
      return false;
    }
  });

  return false;
}

/* barcodes */
function barcode_add(a)
{
  var href = $(a).attr('href');
  var prev_html = $(a).html(); // image of label or labels
  $(a).html('<img src="/style/icons/ajax-loader.gif"/>');
  $.ajax({
    url: href,
    type: 'POST',
    data: {'returntype':'json'},
    dataType: "json",
    error: function(req, resulttype, exc)
    { 
      $('#content').prepend('<p class="message">Error</p>');
      window.setTimeout(function() { $('#content .message').remove(); }, 3000);
      $(a).html(prev_html);
    },
    success: function(data)
    {
      if (data['result']==1) {
        $('#content').prepend('<p class="message">'+data['message']+'</p>');
        window.setTimeout(function() { $('#content .message').remove(); }, 3000);
      }
      else {
        $('#content').prepend('<p class="message">'+data['message']+'</p>');
        window.setTimeout(function() { $('#content .message').remove(); }, 3000);
      }
      $(a).html(prev_html);
    }
  });
  return false;
}

function barcode_update_list(listitems)
{
  $.ajax({
    url: '/labels/update-list',
    type: 'POST',
    data: {'returntype':'json', 'items':listitems},
    dataType: "json",
    error: function(req, resulttype, exc) {},
    success: function(data) {}
  });
}

