var debugging = 0;

$(document).ready( function () {
  brochureCart.init();
});


// Default amount select options
var amountOptionsDefault = '';
var amountInc = 10;
for (amount = 10; amount <= 500; amount += amountInc) 
{
  amountOptionsDefault += '<option val="'+ amount +'">'+ amount +'</option>';
  if (amount >= 100) amountInc = 25;
  if (amount >= 300) amountInc = 50;
}

var brochureCart = {

  init: function () 
  {
    this.cart = {};
    this.brochures = {};
  
    this.cartElement = $("#brochurecart");              // Cart element
    this.cartItemsElement = $("#brochurecart_items");   // Cart elements items
    this.cartListElement = $("#brochurelist");          // Brochure list main element
    this.cartFormElement = $("#brochureform");          // Brochure order form element
  
    if (!this.cartElement.length) return false;

  
    this.getBrochures();  // Load brochures from XML
    this.getCartCookie(); // Get items from cookie
    this.listBrochures(); // Show brochure list 
    this.refresh();       // Update cart 

    // Cart scroll following
    this.cartElement.scrollFollow({
      container: "content_wide", "offset": 20
    });

    // Cart submit button
    brochureCart.cartElement.find("input:button").click( function () {
      brochureCart.cartListElement.hide();
      brochureCart.cartFormElement.show();
      $(this).attr("disabled", "disabled").css("opacity", 0.25);
    });
    
    // Form cancel/back 
    brochureCart.cartFormElement.find("input:button[name=cancel]").click( function () {
      brochureCart.cartFormElement.hide();
      brochureCart.cartListElement.show();
      brochureCart.cartElement.find("input:button").removeAttr("disabled").css("opacity", 1);
    });
    
    // Form submit
    brochureCart.cartFormElement.find("form").submit( function (e) {
      // Add materials to hidden input
      var materials = "";
      $.each(brochureCart.cart, function (id, amount) {
        var brochure = brochureCart.brochures[ id ];
        if (amount.length < 3) amount = " "+ amount;
        materials += amount +" stk.\t"+ brochure.name +"\n";
      })
      if (!materials) e.preventDefault();

      var message = 
        "Bestil materiale\n"+
        "\n"+
        "======================================================================\n"+
        "\n"+
        materials +"\n"+
        "======================================================================\n"+
        "\n"+
        "Navn ...................... "+ $(this).find("#name").val() +"\n"+
        "E-mail .................... "+ $(this).find("#email").val() +"\n"+
        "Adresse ................... "+ $(this).find("#address").val() +"\n"+
        "Postnr. og postdistrikt ... "+ $(this).find("#zipcity").val() +"\n"+
        "\n"+
        "======================================================================\n"+
        "\n"+
        ""+ $(this).find("#comments").val() +"\n";
       
      var now = new Date();
      var timestamp = (now.getTime() / 1000);
      $(this).find("#timestamp").val( timestamp );
      $(this).find("#message, #database").val( message );

      // Empty cart
      brochureCart.empty();
    });
    
    // Set cookie on window unload
    $(window).unload( function () {
      brochureCart.updateCartCookie();
    });
  },
  
  
  // Get cart items from cookie
  getCartCookie: function () 
  {
    var cookie = $.cookie("brochureCart");
    debug("cookie: "+ cookie);
    if (!cookie) return false;
    var items = cookie.split(",");
    var _this = this;
    $.each(items, function (num, item) {
      var itemAmount = item.split("=");
      _this.add(itemAmount[0], itemAmount[1], true);
    });
  },
  
  
  // Store cart items to cookie
  updateCartCookie: function () 
  {
    var cookie = [];
    $.each(brochureCart.cart, function (id, amount) {
      cookie.push(id +"="+ amount);
    });
    $.cookie("brochureCart", cookie.join(","));
  },
  
  
  // Load brochures from XML
  getBrochures: function () 
  { 
    $.ajax({
      type:  "GET",
      async: false,
      cache: true,
      url:   "/bestil_materiale_xml",
      data:  '',
      dataType: 'xml',
      success: function (data) 
      {
        $("material", data).each( function () {
          var id = $(this).attr("id");
          
          var amounts = [];
          var amount = $(this).find("amount").text();
          if (amount) amounts = amount.split(", ");
          
          debug(amounts);
          
          brochureCart.brochures[ id ] = {
            'id': id,
            'name': $(this).find("name").text(),
            'description': $(this).find("description").text(),
            'image': $(this).find("brochure_image").text(),
            'file': $(this).find("brochure_file").text(),
            'group': $(this).find("brochure_group").text(),
            'amount': amounts
          }
        });
      },
      complete: function () 
      {   
      }
    });
  },
  
  
  // List brochures
  listBrochures: function () 
  {
    $.each(brochureCart.brochures, function (id, brochure) {
      if (brochure.group)
        $("#brochures_"+ brochure.group).listBrochure( brochure );
    });
  },
  
  
  // Add brochure to cart
  add: function add (id, amount, update) 
  {
    debug("add "+ id +" ("+ amount +")")
    brochureCart.cart[ id ] = amount;
    if (!update) this.refresh();
    // this.refresh();
  },


  // Update brochure in cart
  update: function (id, amount) 
  {
    debug("update "+ id +" ("+ amount +")")
    brochureCart.cart[ id ] = amount;
    // this.refresh();
  },

  
  // Remove brochure from cart
  remove: function (id) 
  {
    debug("remove "+ id);
    delete(brochureCart.cart[ id ]);
    this.refresh();
  },

  
  // Empty cart
  empty: function () {
    brochureCart.cart = {};
    this.refresh();
  },


  // Refresh cart
  refresh: function () 
  {
    brochureCart.cartItemsElement.empty();
    var cartItems = 0;
    $.each(brochureCart.cart, function (id, amount) {
      cartItems++;
      brochureCart.cartItemsElement.cartBrochure(
        brochureCart.brochures[ id ]
      );
    });
    if (cartItems > 0) {
      brochureCart.cartElement.show();
    }
    else brochureCart.cartElement.hide();
    
    brochureCart.cartItemsElement.find(".brochure:odd").addClass("odd");
    brochureCart.cartItemsElement.find(".brochure:even").addClass("even");
  }
  
}


// Brochure in list
jQuery.fn.listBrochure = function (brochure) 
{
  var amountOptions = '';
  if (brochure.amount.length)
  {
    $.each(brochure.amount, function (n, amount) {
      amountOptions += '<option value="'+ amount +'">'+ amount +'</option>';
    });
  }
  else amountOptions = amountOptionsDefault;
  
  $(document.createElement("div"))
    .attr("id", brochure.id)
    .attr("title", brochure.description)
    .addClass("brochure")
    .hover(
      function () { $(this).addClass("hover") },
      function () { $(this).removeClass("hover") }
    )
    .append(
    
      $(document.createElement("a")) 
        .attr("href", brochure.file)
        .attr("target", "_blank")
        .append(
          $(document.createElement("img"))
            .attr("src", brochure.image)
            .attr("alt", brochure.name),
          $(document.createElement("div"))
            .attr("class", "name")
            .append( brochure.name )
        ),
      
      $(document.createElement("form"))
        .attr("id", "add_"+ brochure.id)
        .append(
          $(document.createElement("select"))
            .attr("name", "amount")
            .append( amountOptions ),
            
          $(document.createElement("input"))
            .attr("type", "button")
            .attr("name", "cart_add")
            .addClass("submit")
            .val("bestil")
            .click( function () {
              var amount = $(this).parent().find("[name=amount]");
              brochureCart.add(brochure.id, amount.val());
              amount.find("option:eq(0)").attr("selected", "selected")
              $(this).hide().fadeIn(1000)
            })
        )    
    )  
    .appendTo(this);
}

// Brochure in cart
jQuery.fn.cartBrochure = function ( brochure ) 
{
  var amountOptions = '';
  if (brochure.amount.length)
  {
    $.each(brochure.amount, function (n, amount) {
      amountOptions += '<option value="'+ amount +'">'+ amount +'</option>';
    });
  }
  else amountOptions = amountOptionsDefault;

  $(document.createElement("div"))
    .attr("id", "brochure_"+ brochure.id)
    .attr("title", brochure.description)
    .addClass("brochure")
    .append(
    
      $(document.createElement("b"))
        .html(brochure.name),
      
      $(document.createElement("form"))
        .attr("id", "update_"+ brochure.id)
        .append(
        
          " ",
          
          $(document.createElement("select"))
            .change( function () {
              brochureCart.update(brochure.id, $(this).val());
            })
            .attr("name", "amount")
            .append( amountOptions )
            .val(brochureCart.cart[ brochure.id ]),
            
          " ",
        
          $(document.createElement("input"))
            .attr("type", "button")
            .attr("name", "cart_del")
            .addClass("submit")
            .val("x")
            .click( function () {
              brochureCart.remove(brochure.id);
            })
        )

    )
    
    .appendTo(this)
    .fadeIn(500);
}


function debug (string) {
  if (debugging) $("#content_left").append(string +"<br />");
}


