var cart = new Cart();
$(document).ready(cart.init);

function Cart() {
  var dom = {};
  
  this.init = init;
  function init() {
    dom['body'] = $('body');
    dom['dark'] = $('#darkLayer');
    dom['products'] = $('#products > li');
    dom['emptyProduct'] = $('#products > li.empty');
    dom['productDetail'] = $('#product_detail');
    dom['continueShopping'] = $('#continue_shopping');
    dom['detailCalculator'] = $('#detail_calculator');
    dom['detailCalculatorForm'] = $('form#calc_form');
    dom['detailDescriptionContainer'] = $('#detail_desc_container');
    dom.dark.click(function() {
      hideProductDetail();
    });
    // product detail bindings
    $('#detail_add').click(function() {
      addToCart();
      return false;
    });
    $('#detail_cancel').click(function() {
      hideProductDetail();
      return false;
    });
    $('#detail_calc_button').click(function() {
      toggleCalculator();
      return false;
    });
    $('#detail_quantity').keyup(function() {
      var qty = Math.ceil(parseInt($(this).val()));
      if (!isNaN(qty)) $(this).val(qty);
    }).blur(function() {
      if (isNaN(parseInt($(this).val()))) {
        alert('Please enter a valid amount to order.');
      }
    });
    $('#detail_category').click(function() {
      hideProductDetail();
      setTimeout(readFilter, 50);
    });
    $('#shopping_continue').click(function() {
      hideProductDetail();
      return false;
    });
    // calculator bindings
    $('#calc_form').submit(function() {
      return false;  // prevent form from being submitted...we're just using it for reset()
    });
    $('#calc_form input').keyup(runCalculator);
    $('#calc_form select').change(runCalculator);
    $('#calc_use').click(function() {
      var result = $('#calc_result').val();
      if (result && Number(result) == result) $('#detail_quantity').val(result);
      return false;
    });
    // product page setup
    if (dom.body.hasClass('product')) {
      // filter bindings
      $('#cart_filter_form').submit(function() { return false; });
      if ($('#cart_filter_form').length) $('#cart_filter_form')[0].reset();
      $('#cart_filter input').change(function() {
        var radio = this;
        setTimeout(function() { applyFilter(radio); }, 50);
      });
      // hook up bindings to product grid
      $('#products > li').each(function() {
        var li = $(this);
        li.find('a.product_add, div.product_thumb, a.more').click(function() {
          showProductDetail(li);
          return false;
        });
      });
      // setup
      readFilter();
    }
    // home page setup
    if (dom.body.hasClass('home')) {
      $('#shopping_continue').unbind().attr('href', common.baseUrl() + 'product');
      $('#sidebar div.product').each(function() {
        var product = $(this);
        product.find('div.thumb, a.product_add').click(function() {
          showProductDetail(product);
          return false;
        });
      });
    }
  }
  
  function addToCart() {
    var qty = $('#detail_quantity').val();
    var calcQty = $('#calc_result').val();
    if (qty && (parseInt(qty) == qty)) {
      if (!dom.detailCalculator.hasClass('hide') && parseInt(calcQty) == calcQty && calcQty != qty) {
        if (confirm('Would you like to buy the calculated amount (' + calcQty + ' yards)? If so, press "OK" below.')) {
          qty = calcQty;
        }
      }
      $.post(
        common.baseUrl() + 'product/add_to_cart',
        {
          id: $('#detail_id').val(),
          name: $('#detail_name').text(),
          price_id: $('#detail_price_id').text(),
          price: dom.productDetail.find('.price').eq(0).text(),
          unit: dom.productDetail.find('.unit').eq(0).text(),
          quantity: qty
        },
        function(data) {
          $('#cart_items').text(data.total_items);
          dom.continueShopping.find('.msg').text(data.message);
          positionModal(dom.continueShopping);
          dom.productDetail.addClass('offscreen');
          dom.continueShopping.removeClass('offscreen');
        }, 'json'
      );
    }
  }
  
  function applyFilter(radio) {
    radio = $(radio);
    var selected = radio.val();
    if (selected == 'all') {
      dom.products.removeClass('hide');
    } else {
      dom.products.each(function() {
        var product = $(this);
        if (!product.hasClass('empty')) {
          if (product.hasClass(selected)) {
            product.removeClass('hide');
          } else {
            product.addClass('hide');
          }
        }
      });
    }
    styleProductGrid();
    window.location.href = String(window.location.href).split('#')[0] + '#' + selected;
  }
  
  this.hideProductDetail = hideProductDetail;
  function hideProductDetail() {
    dom.dark.addClass('offscreen');
    dom.productDetail.addClass('offscreen');
    dom.continueShopping.addClass('offscreen');
  }
  
  function positionModal(modal) {
    modal = $(modal);
    modal.css('top', ($(window).height() - modal.outerHeight()) / 2);
    modal.css('left', ($(window).width() - modal.outerWidth()) / 2);
  }
  
  function readFilter() {
    var hrefArr = String(window.location.href).split('#');
    if (hrefArr.length > 1) {
      var anchor = hrefArr[1];
      $('#cart_filter input').each(function() {
        if (anchor == $(this).attr('value')) {
          this.checked = true;
          applyFilter(this);
        }
      });
    }
  }
  
  function runCalculator() {
    var sqYards = $('#calc_dim').val();
    var depth = $('#calc_depth').val() / 3;
    if (sqYards && depth && (!(isNaN(Number(sqYards)) || isNaN(Number(depth))))) {  // both are valid numbers
      if ($('#calc_dim_unit').attr('value') == 'feet') sqYards = sqYards / 9;
      if ($('#calc_depth_unit').attr('value') == 'inches') depth = depth / 12;
      $('#calc_result').val(Math.ceil(sqYards * depth));
    }
  }
  
  function showProductDetail(productDom) {
    productDom = $(productDom);
    // load data
    var idPrefix = '#' + productDom.attr('id');
    var priceArr = String($(idPrefix + '_price').val() || $(idPrefix + '_price').text()).replace(/\$([\d\.]*) \/ ([A-Za-z0-9 ]*)/g, '$1|$2').split('|');
    if (priceArr.length < 2) { priceArr = ['', '']; }
    var product = {
      category: $(idPrefix + '_category').val(),
      categoryUrl: common.baseUrl() + 'product#' + String(String($(idPrefix + '_category').val()).replace(/ /g, '-')).toLowerCase(),
      desc: $(idPrefix + '_desc').val(),
      id: productDom.attr('id').split('_')[1],
      name: $(idPrefix + '_name').text(),
      price: $.trim(priceArr[0]),
      thumb: String($(idPrefix + '_thumb img').attr('src')).replace('_thumb', ''),
      unit: $.trim(priceArr[1]),
      price_id: $(idPrefix + '_price_id').val()
    };
    $('#detail_category').text(product.category).attr('href', product.categoryUrl);
    $('#detail_desc').html(String(product.desc).replace(/\n/g, '<br/>'));
    $('#detail_id').val(product.id);
    $('#detail_price_id').html(product.price_id);
    $('#detail_name').text(product.name);
    dom.productDetail.find('.price').text(product.price);
    dom.productDetail.find('.unit').text(product.unit);
    $('#detail_thumb').removeAttr('src');
    $('#detail_thumb').attr('src', product.thumb);
    $('#detail_quantity').val('1');
    // show dom elements
    if (String(product.category).toLowerCase() == 'mulch' && String(product.unit).toLowerCase() == 'yard') {
      $('#detail_calc_show').removeClass('hide');
    } else {
      $('#detail_calc_show').addClass('hide');
    }
    toggleCalculator(false);
    positionModal(dom.productDetail);
    dom.dark.css({
      height: $(window).height() + 'px',
      width: $(window).width() + 'px'
    });
    dom.dark.removeClass('offscreen');
    dom.productDetail.removeClass('offscreen');
  }
  
  function styleProductGrid() {
    var count = 0;
    dom.products.each(function() {
      var product = $(this);
      if (!product.hasClass('hide') && !product.hasClass('empty')) {
        if (count % 3 == 0) product.addClass('newline');
        else product.removeClass('newline');
        count++;
      }
    });
    if (count % 3) dom.emptyProduct.removeClass('hide');
    else dom.emptyProduct.addClass('hide');
  }
  
  this.toggleCalculator = toggleCalculator;
  function toggleCalculator(override) {
    if (override === true || (dom.detailCalculator.hasClass('hide') && override !== false)) {  // we need to show the calculator
      dom.detailCalculatorForm[0].reset();
      dom.detailDescriptionContainer.addClass('hide');
      dom.detailCalculator.removeClass('hide');
    } else { // we need to hide the calculator
      dom.detailCalculator.addClass('hide');
      dom.detailDescriptionContainer.removeClass('hide');
    }
  }
  
}


