$(document).ready(function() {
 
  $(".addToCart").click( function() {
    addToCart($(this).parents(".shopItem"));
    updateOrderListInput()
    return false;
  });
  $('.deleteButton').live('click', function() {
    $(this).parents("tr").fadeOut('fast', function() {
      $(this).remove();
      zebraStripe("#cart");
      updateOrderListInput()
    });
  });

  $("#mountainGovernments .contentBox:nth-child(odd)").addClass("first-box");
   
});

function zebraStripe(table) {
  $(table+" tbody tr:nth-child(odd)").addClass('odd');
  $(table+" tbody tr:nth-child(even)").removeClass('odd');
}

function addToCart(product) {
  if ($("#cart tr").last() && !$("#cart tr").last().hasClass("odd")) {
    var zebraRow = " class='odd'";
  } else { var zebraRow = ""; } //Setting the row class first, so the highlight effect works correctly in IE

  var id = $(product).attr("id");
  var productName = $(product).find("h4").text();
  var selectedSize = $(product).find("'#"+id+"_size'").val();
  var selectedQuantity = $(product).find("'#"+id+"_quantity'").val();
  var formInput = "<input class='inOrderList' type='hidden' name='"+id+"name' value='"+selectedQuantity+" stk "+productName+", str "+selectedSize+"'>";
  var tableRow = $("<tr"+zebraRow+"><td>"+selectedQuantity+" stk</td><td>"+productName+formInput+"</td><td>"+selectedSize+"</td><td><img class='deleteButton' alt='Slett' src='/images/deleteButton.png'></td></tr>");
  $(tableRow).appendTo("#cart tbody").show("highlight", {}, "400");
  
  var message = $("<div class='confirmBox'><p><strong>"+productName+"</strong> ligger n&aring; i ordrelisten.</p><p>Antall: "+selectedQuantity+" stk<br> St&oslash;rrelse: "+selectedSize+"</p></div>");
  $(message).dialog({
    resizable: false,
    title: "Vare lagt til!",
    buttons: { "Ok": function() { $(this).dialog("close");$(this).remove(); }}
  });
}

function updateOrderListInput() {
  var currentOrderList = "";
  $("input.inOrderList").each(function() {
    currentOrderList += $(this).val() + "\n";
  });
  $("#theOrderList").val(currentOrderList);
}

function ruleHandler(form, node, ruleMsg, successful) {
  var wrapper = node.parentNode;
  var div;
  if (o2.hasClassName(wrapper, "error")) {
    var firstChild = wrapper.firstChild;
    if (firstChild.nodeType === 3) {
      firstChild = getNextElement(firstChild);
    }
    div = firstChild;
  }
  else {
    div = document.createElement("div");
    o2.addClassName(div, "errorMessage");
    wrapper.insertBefore(div, wrapper.firstChild);
  }
  if (successful) {
    o2.removeClassName(div.parentNode, "error");
    $(div).remove();
  }
  else {
    div.innerHTML = ruleMsg;
    o2.addClassName(div.parentNode, "error");
  }
}

function ignoreErrors() {}

function showSuccess() {
  $("#successMessage").dialog({
    modal: true,
    resizable: false,
    title: "Bestilling sent!",
    buttons: { "Ok": function() { $(this).dialog("close");$(this).remove(); }}
  });
}

