$(function () {

  $.config = {
    orderTotal : "",
    productCode : "",
    productDescription : "",
    productQuantity : "",
    productPrice : "",
    productCategory : ""
  }

  $('#logo h2 a').hide().fadeIn(800);
  $('#bubble').hide().fadeIn(800);
  $('#testimonial').hide().slideDown(800);
  $('#gallery-thumbnails a.lightbox').lightBox({fixedNavigation:true});
  $('#gallery-season a.lightbox').lightBox({fixedNavigation:true});
  $('#news-item a.lightbox').lightBox({fixedNavigation:true});
  $('a.jeff.lightbox').lightBox({fixedNavigation:true});
  $('a.reset.lightbox').lightBox({fixedNavigation:true});
  $('#customer-lounge a.lightbox').lightBox({fixedNavigation:true});

  $('#news-item img').mouseover(function () {
    $('p.enlarge-image').fadeIn(200);
  });

  $('#news-item img').mouseout(function () {
    $('p.enlarge-image').fadeOut(200);
  });

  // Order +add

  $("input.order_checkbox").live("click", function () {
    $("p.checkoutButton span.success").hide();
    var row = $(this).closest("tr");
    if($(row).hasClass("ordered")) {
      $(row).removeClass("ordered");
      $(row).removeClass("active");
      $("input.lineItem", row).attr("value", "");
    } else {
      $(row).addClass("ordered");
      $(row).addClass("active");

      $.config.productCode = $("td.code", row).text();
      $.config.productDescription = $("td.description", row).text();
      $.config.productPrice = $("td.price", row).attr("rel");
      $.config.productQuantity = $("td.quantity input", row).val();
      var fit = $("select.fit", row).val();
      var size = $("select.size", row).val();
      var price = $.config.productQuantity*$.config.productPrice;
      var line = "" + $.config.productCode + " : " + $.config.productDescription + " : Fit(" + fit + ") : Size(" + size + ") : Quantity x " + $.config.productQuantity + " : Cost = £" + price.toFixed(2);
      line = line.replace(/[\n\r\t]/g, '');
      $("input.lineItem", row).attr("value", line);
      var ediline = "LIN," + $.config.productCode + "," + fit + "," + size + "," + $.config.productCode + fit + size + "," + $.config.productQuantity;
      $("input.ediItem", row).attr("value", ediline);
    }

    // Calculate total

    $.config.orderTotal = 0;

    $("table#productsTable tr.ordered").each(function () {
      $.config.productPrice = $("td.price", $(this)).attr("rel");
      $.config.productQuantity = $("td.quantity input", $(this)).val();
      $.config.orderTotal += $.config.productQuantity * $.config.productPrice;
    });

    $.config.orderTotal = $.config.orderTotal.toFixed(2);

    if($.config.orderTotal > 0) {
      $.config.orderTotal = "Order Total : £" + $.config.orderTotal;
      $("div.basket p.checkoutButton").show();
    } else {
      $.config.orderTotal = "No items in order";
      $("div.basket p.checkoutButton").hide();
    }

    $("div.basket p.orderTotal").text($.config.orderTotal);
    $("input.total").attr("value", $.config.orderTotal); 
    $("div.basket").show();
  });

  // Change quantity

  $("input.quantity").live("keyup",function () {
    $("p.checkoutButton span.success").hide();
    var row = $(this).closest("tr");

    if($(row).hasClass("ordered")) {

      $.config.productCode = $("td.code", row).text();
      $.config.productDescription = $("td.description", row).text();
      $.config.productPrice = $("td.price", row).attr("rel");
      $.config.productQuantity = $("td.quantity input", row).val();
      var fit = $("select.fit", row).val();
      var size = $("select.size", row).val();
      var price = $.config.productQuantity*$.config.productPrice;
      var line = $.config.productCode + " : " + $.config.productDescription + " : Fit(" + fit + ") : Size(" + size + ") : Quantity x " + $.config.productQuantity + " : Cost = £" + price.toFixed(2);
      line = line.replace(/[\n\r\t]/g, '');
      $("input.lineItem", row).attr("value", line);
      var ediline = "LIN," + $.config.productCode + "," + fit + "," + size + "," + $.config.productCode + fit + size + "," + $.config.productQuantity;
      $("input.ediItem", row).attr("value", ediline);

      // Calculate total

      $.config.orderTotal = 0;

      $("table#productsTable tr.ordered").each(function () {
        $.config.productPrice = $("td.price", $(this)).attr("rel");
        $.config.productQuantity = $("td.quantity input", $(this)).val();
        $.config.orderTotal += $.config.productQuantity * $.config.productPrice;
      });

      $.config.orderTotal = $.config.orderTotal.toFixed(2);

      if($.config.orderTotal > 0) {
        $.config.orderTotal = "Order Total : £" + $.config.orderTotal;
        $("div.basket p.checkoutButton").show();
      } else {
        $.config.orderTotal = "No items in order";
        $("div.basket p.checkoutButton").hide();
      }

      $("div.basket p.orderTotal").text($.config.orderTotal);
      $("input.total").attr("value", $.config.orderTotal); 
      $("div.basket").show();

    }
  });

  // Change size/fit

  $("#productsTable select").change(function () {
    $("p.checkoutButton span.success").hide();
    var row = $(this).closest("tr");
    if($(row).hasClass("ordered")) {
      $.config.productCode = $("td.code", row).text();
      $.config.productDescription = $("td.description", row).text();
      $.config.productPrice = $("td.price", row).attr("rel");
      $.config.productQuantity = $("td.quantity input", row).val();
      var fit = $("select.fit", row).val();
      var size = $("select.size", row).val();
      var price = $.config.productQuantity*$.config.productPrice;
      var line = $.config.productCode + " : " + $.config.productDescription + " : Fit(" + fit + ") : Size(" + size + ") : Quantity x " + $.config.productQuantity + " : Cost = £" + price.toFixed(2);
      line = line.replace(/[\n\r\t]/g, '');
      $("input.lineItem", row).attr("value", line);
      var ediline = "LIN," + $.config.productCode + "," + fit + "," + size + "," + $.config.productCode + fit + size + "," + $.config.productQuantity;
      $("input.ediItem", row).attr("value", ediline);
    }
  });

  // Reset Form

  $("input.reset").click(function () {
    $("p.checkoutButton span.success").hide();
    $("input.lineItem").attr("value", "");
    $("#productsTable tr").removeClass("ordered active");
    $(".error").hide();
    $("div.basket p.orderTotal").text("No items in your order");
    $("div.basket p.checkoutButton").hide();
  });

  // Submit order : checkout

  $("p.checkoutButton").click(function () {
    $("span.error").hide();
    $("p.checkoutButton span.errors").hide();
    var hasError = false;

    var nameVal = $("input.name").val();
    if(nameVal == '') {
      $("label.name").after('<span class="error">Name missing!</span>');
      hasError = true;
    }

    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    var emailVal = $("input.email").val();
    if(emailVal == '') {
      $("label.email").after('<span class="error">Email missing!</span>');
      hasError = true;
    } else if(!emailReg.test(emailVal)) {
      $("label.email").after('<span class="error">Email invalid!</span>');
      hasError = true;
    }

    var jobRoleVal = $("input.job_role").val();
    if(jobRoleVal == '') {
      $("label.job_role").after('<span class="error">Job Role missing!</span>');
      hasError = true;
    }

    var addressVal1 = $("input.address_1").val();
    if(addressVal1 == '') {
      $("label.address_1").after('<span class="error">Address missing!</span>');
      hasError = true;
    }

    var addressVal2 = $("input.address_2").val();
    var addressVal3 = $("input.address_3").val();

    var postcode = $("input.postcode").val();
    if(postcode == '') {
      $("label.postcode").after('<span class="error">Postcode missing!</span>');
      hasError = true;
    }

    var rpcVal = $("input.rpc_code").val();
    if(rpcVal == '') {
      $("label.rpc_code").after('<span class="error">RPC Code missing!</span>');
      hasError = true;
    }

    var employeeNumberVal = $("input.employee_number").val();
    if(employeeNumberVal == '') {
      $("label.employee_number").after('<span class="error">Employee Number missing!</span>');
      hasError = true;
    }

    var telephoneVal = $("input.telephone").val();
    if(telephoneVal == '') {
      $("label.telephone").after('<span class="error">Telephone Number missing!</span>');
      hasError = true;
    }
    
    var faxVal = $("input.fax").val();
    if(faxVal == '') {
      $("label.fax").after('<span class="error">Fax Number missing!</span>');
      hasError = true;
    }
    
    var branchNameVal = $("input.branch_name").val();
    if(branchNameVal == '') {
      $("label.branch_name").after('<span class="error">Branch Name missing!</span>');
      hasError = true;
    }

    var siteCodeVal = $("input.site_code").val();
    if(siteCodeVal == '') {
      $("label.site_code").after('<span class="error">Site Code missing!</span>');
      hasError = true;
    }


    if(hasError) {
      $("p.checkoutButton span.errors").show();
      $("body").scrollTo({ top:820, left:0 }, 400);
    } else {
      var emailRecipientVal = $("p.order_recipient").next().find("a").text();
      $("input.order_recipient").attr("value", emailRecipientVal);
      var companyVal = $("h1").text().replace(/Welcome /, "");
      $("input.company").attr("value", companyVal);
      $("p.checkoutButton a").hide();
      $("p.checkoutButton span.sending").show();
      var data = $("form#products").serialize();
      $.post("/customerlounge/post", { data: data }, function(data){ $("p.checkoutButton span.sending").hide(); $("p.checkoutButton span.success").show(); } );
      $("body").scrollTo({ top:820, left:0 }, 400);
    }
    return false;
  });

  // Table Category Headers

  $("table#productsTable tr").each(function () {
    if($.config.productCategory != $(this).attr("category")) {
      $.config.productCategory = $(this).attr("category");
      $(this).before("<tr class='category closed'><td colspan='10'>" + $.config.productCategory + "</td></tr>");
    }
  });
  
  $("table#productsTable tr.category").click(function () {
    var thisCategory = $("td", this).text();
    if($(this).hasClass("closed")) {
      $(this).removeClass("closed");
      $("table#productsTable tr").each(function () {
        if($(this).attr("category") == thisCategory) {
          $(this).show();
        }
      });
    } else {
      $(this).addClass("closed");
      $("table#productsTable tr").each(function () {
        if($(this).attr("category") == thisCategory) {
          $(this).hide();
        }
      });
    }
  });
  
  
  var firstCategory = $("table#productsTable tr:eq(2)").text();
  $("table#productsTable tr.item").hide();
  $("table#productsTable tr").each(function () {
    if($(this).attr("category") == firstCategory) {
      $(this).show();
    }
  });
  $("table#productsTable tr:eq(2)").removeClass("closed");
  
  $("table#productsTable td.duplicate").live("click", function() {
    var row = $(this).parent().clone();
    row.find("td.remove").text("-").addClass("active").attr("title", "- Remove this line item");
    $(this).parent().after(row);
    $(this).parent().next().hide().fadeIn(500);
    
    // Calculate total

    $.config.orderTotal = 0;

    $("table#productsTable tr.ordered").each(function () {
      $.config.productPrice = $("td.price", $(this)).attr("rel");
      $.config.productQuantity = $("td.quantity input", $(this)).val();
      $.config.orderTotal += $.config.productQuantity * $.config.productPrice;
    });

    $.config.orderTotal = $.config.orderTotal.toFixed(2);

    if($.config.orderTotal > 0) {
      $.config.orderTotal = "Order Total : £" + $.config.orderTotal;
      $("div.basket p.checkoutButton").show();
    } else {
      $.config.orderTotal = "No items in order";
      $("div.basket p.checkoutButton").hide();
    }

    $("div.basket p.orderTotal").text($.config.orderTotal);
    $("input.total").attr("value", $.config.orderTotal); 
    $("div.basket").show();
  });
  
  $("table#productsTable td.remove.active").live("click", function() {
    $(this).parent().animate({opacity : 0}, 500, function(){ $(this).remove()});
    
    // Calculate total

    $.config.orderTotal = 0;

    $("table#productsTable tr.ordered").each(function () {
      $.config.productPrice = $("td.price", $(this)).attr("rel");
      $.config.productQuantity = $("td.quantity input", $(this)).val();
      $.config.orderTotal += $.config.productQuantity * $.config.productPrice;
    });

    $.config.orderTotal = $.config.orderTotal.toFixed(2);

    if($.config.orderTotal > 0) {
      $.config.orderTotal = "Order Total : £" + $.config.orderTotal;
      $("div.basket p.checkoutButton").show();
    } else {
      $.config.orderTotal = "No items in order";
      $("div.basket p.checkoutButton").hide();
    }

    $("div.basket p.orderTotal").text($.config.orderTotal);
    $("input.total").attr("value", $.config.orderTotal); 
    $("div.basket").show();
  });
  

  $("table#productsTable tr:first").hide();

  $("p.order_recipient").next().hide();

})