﻿$(document).ready(function() {
  $('table.lines tbody tr:odd td').not('.separator').css('background', 'White');
  $.spinnerImage = $('<img src="/content/images/spinner.gif" id="spinner">');
  $.saveImage = $('<img src="/content/images/save.png" id="save" style="cursor:pointer;">');
  $.metadata.setType("attr", "data");

  $.geekSkypeRemover(10000);

  $.ajaxSetup({
    cache: false
  });

  $('a', $('div#topmenu')).click(function() {
    $('a.active', $('div#topmenu')).removeClass('active');
    $(this).addClass('active');

    updateMenuArrowPadding();
  });

  $.list = $('#comparisonBox .frame ul');

  checkComparisonCheckBoxes();

  $.datepicker.setDefaults($.datepicker.regional['${Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName}']);

  $('.cornered').corner();
  $('.blockBody').wrap('<div class="blockBorder">').corner('bottom').parent().corner('bottom');
  $('.blockHeader').corner('top');
  $("div.sep:last", $("div#topmenu")).remove();
  $("div.sep:last", $("div#bottommenu")).remove();

  $('th:first', $('div.content table thead tr')).removeClass("middle");
  $('th:last', $("div.content table thead tr")).removeClass("middle").addClass("last");


  $('form#searchForm').submit(function() {
    $('input#page').val(0);
  });
  function updateMenuArrowPadding() {
    var menuArrowPadding = $('a.active', $('div#topmenu')).parent().position().left;
    var menuArrowPadding = menuArrowPadding + ($('a.active', $('div#topmenu')).parent().width() / 2) - 5;
    $("div#menuArrow").css("padding-left", menuArrowPadding);
  }

  $('input[name="quantity"]').blur(function() {
    $.checkQuantity($(this));
  });

  $('#order').submit(function(e) {
    var newTarget = GetNewOrderTarget();
    $(this).attr('action', newTarget);

    if ($('input[name="quantity"][value!=""]').length == 0) {
      alert($('span#noQuantitiesText').html());
      return false;
    }

    $('input[name="quantity"]').each(function() {
      if (!$.checkQuantity($(this))) {
        return false;
      }
    });



    return true;
  });

  $('input.compare[type="checkbox"]').click(function() {
    checkComparisonProducts(this);
  });

  $('img', $.list).live("click", function(e) {
    RemoveComparisonProduct($(this));
  });

  $('img#clear').click(function() {
    $.ajax({
      url: "/Comparison.aspx/Clear",
      success: function() {
        $('input[type="checkbox"]').attr("checked", "");
        $('#comparisonBox').hide();
        $.list.empty();
        checkComparisonCheckBoxes();
      }
    });
  });

  $('img', $.list).live("click", function(e) {
    RemoveComparisonProduct($(this));
  });

  $('input#toOrder').click(function() {
    var select = $('#orderSelect');

    var newTarget = $('option:selected', select).closest('optgroup').metadata().target + select.val() + '/Step1';
    window.location = newTarget;
  });

  $('input#toCart').click(function() {
    window.location = '/Cart.aspx/Index';
  });

  $('.order').click(function(e) {
    var newTarget = GetNewOrderTarget();

    if ($('#orderSelect').length == 1 && $('#orderSelect').val() != '0') {
      var checkurl = '/Proposal.aspx/CheckProposalLines';
      if (newTarget.indexOf('Order.aspx') != -1)
        checkurl = '/Order.aspx/CheckOrderLines';

      e.preventDefault();
      var formData = $("#order").serialize();
      $.ajax({
        url: checkurl,
        dataType: 'json',
        data: formData,
        success: function(data) {
          if (data.msg != '') {
            var warning = $('span#warninglinesexist').html().replace('{0}', data.msg);
            if (!confirm(warning))
              return false;
          }
          $("#order").submit();
        },
        error: function() {
          //alert('wrong');
        }

      })
    }
    //$("#order").submit();
  });

  function checkComparisonProducts(product) {
    if ($(product).attr("checked")) {
      AddComparisonProduct(product)
    }
    else {
      RemoveComparisonProduct(product)
    }
  }

  function AddComparisonProduct(product) {
    $.ajax({
      url: "/Comparison.aspx/Add",
      data: ({
        supplierOrderCode: $(product).attr("id"), supplierCode: 0
      }),
      success: function(data) {
        $.list.append(data);
        $('#comparisonBox').show();
        checkComparisonCheckBoxes();
      }
    })
  }

  function RemoveComparisonProduct(product) {
    $.ajax({
      url: "/Comparison.aspx/Remove",
      data: ({
        supplierOrderCode: $(product).attr("id"),
        supplierCode: 0
      }),
      success: function(data) {
        $('li#' + $(product).attr("id")).remove();
        if ($.list.children().length == 0) {
          $('#comparisonBox').hide();
        }

        $('input#' + $(product).attr("id")).attr("checked", "");
        checkComparisonCheckBoxes();
      }
    })
  }

  function checkComparisonCheckBoxes() {
    if ($.list.children().length > 0) {
      $('#comparisonBox').show();
    }

    if ($.list.children().length < 3) {
      $('input.compare').attr('disabled', '');
    }
    else {
      $('input.compare:not(:checked)').attr('disabled', 'disabled');
    }
  }

  function GetNewOrderTarget() {
    var newTarget;
    var select = $('#orderSelect');
    if ($('#orderSelect').length == 1) {
      if ($('input[name="quantity"]').length > 1)
        newTarget = $('option:selected', select).closest('optgroup').metadata().target + 'CreateLines';
      else
        newTarget = $('option:selected', select).closest('optgroup').metadata().target + 'CreateLine';

      var selectName = $('option:selected', select).closest('optgroup').metadata().name;

      //set the name for the select to the appropriate id if it's within the form
      if ($('#orderSelect', $(this)).length > 0) {
        select.attr('name', selectName);

      }
      else {
        $('#orderId').val($('#orderSelect').val());
        $('#proposalId').val($('#orderSelect').val());
      }
    }
    else {
      if ($('input[name="quantity"]').length > 1)
        newTarget = '/Cart.aspx/CreateLines';
      else
        newTarget = '/Cart.aspx/CreateLine';
    }

    return newTarget;
  }

  $.extend({
    checkQuantity: function($product) {
      var hasErrors = false;
      var supplierOrderCode = $product.metadata().supplierOrderCode;
      var minQuantity = $product.metadata().minQuantity;
      var adjustment = $product.metadata().adjustment;

      if (supplierOrderCode != null && $product.val()) {
        var val = $product.val().replace(",", ".") * 1;
        if (isNaN(val)) {
          val = minQuantity;
        }
        if (val < minQuantity) {
          var currHtml = $('span#minQuantityText').html();
          currHtml = $.format(currHtml, supplierOrderCode, minQuantity);

          if (confirm(currHtml)) {
            val = minQuantity;
            $product.val(val);
          }
          else {
            hasErrors = true;
          }
        }

        else if (val % adjustment != 0) {
          val = (val - val % adjustment) + adjustment;


          var currHtml = $('span#adjustmentText').html();
          currHtml = $.format(currHtml, supplierOrderCode, adjustment, val);
          if (confirm(currHtml)) {

            $product.val(val);
          }
          else {
            hasErrors = true;
          }
        }
      }
      return !hasErrors;
    }
  });
});
