function Cart() {

  this.formID = 'paymentForm';

  this.quantityID = 'quantity_';
  this.packQuantityID = 'packQuantity_';
  this.quantityButtonID = 'quantity_button_';
  this.removeButtonID = 'remove_button_';
  this.summaryID = 'cartSummary';
  
  this.attemptShowSummary = false;

  this.add = function(id, vipDiscount) {
    $('#'+this.quantityButtonID+id).blur();
    var quantity = new Number($('#'+this.quantityID+id).val());
    var packQuantity = new Number($('#'+this.packQuantityID+id).val());
    var checkPackQuantity = this.checkPackQuantity(quantity, packQuantity);
    if (checkPackQuantity) {
      this.addExec(id, quantity, vipDiscount);
    } else {
      this.invalidQuantity(id, packQuantity);
    }
  }
  
  this.addExec = function(id, quantity, vipDiscount) {
    $.get('/cart/cartAdd.jsp?productID='+id+'&quantity='+quantity, function(data){
      if ($.trim(data) == '0') { // success
        cart.setAdded(id, quantity);
        cart.getSummary();
        cart.updateProductPrices(id, vipDiscount);
      } else { // error
        alert('There was a problem adding this product to the cart');
      }  
    });
  }
  
  this.setAdded = function(id, packQuantity) {
    $('#'+this.quantityButtonID+id).attr('value', 'UPDATE');
    $('#'+this.removeButtonID+id).fadeIn();    
  }
  
  this.invalidQuantity = function(id, packQuantity) {
    $('#'+this.quantityID+id).select();
    alert('You need to add at least ' + packQuantity + ' for this product');
  }
  
  this.checkPackQuantity = function(quantity, packQuantity) {
    if (quantity < packQuantity) {
      return false;
    }
    return true;
  }
  
  this.remove = function(id, viewingCart) {
    $('#'+this.removeButtonID+id).blur();
    $.get('/cart/cartRemove.jsp?productID='+id, function(data) {
      if ($.trim(data) == '0') {
        cart.getSummary();
        var packQuantity = $('#'+cart.packQuantityID+id).val();
        $('#'+cart.removeButtonID+id).fadeOut();
        $('#'+cart.quantityID+id).val(packQuantity);
        $('#'+cart.quantityButtonID+id).attr('value', 'ADD');
        if (viewingCart) {
          $('#dataRows'+id).fadeOut('slow', function() {
            var cartCount = new Number($('#cartCount').val());
            if (cartCount == 0) {
              $('#hasNonPOA').val(false);
              $('#hasPOA').val(false);
              $('#cart_display_totals').fadeOut('slow');
              $('#cart_display_title_non_poa').fadeOut('slow', function() {
                  $('#cart_display_hasPOA_no_nonPOA').fadeOut('slow');
                  
                  $('#cart_display_no_items').fadeIn('slow');
                  $('#cart_display_no_items_2').fadeIn('slow');
                  
              });
            
            }
             
            if ($('#nonPoaCount').val() == 0){
              $('#cart_display_non_poa_items').fadeOut('slow', function(){
                if ($('#poaCount').val() > 0){
                  $('#cart_display_hasPOA_no_nonPOA').fadeIn('slow');
                }
              });
              $('#hasNonPOA').val(false);
            }

            if ($('#poaCount').val() == 0){
              $('#nonPOAContinue').show();
              $('#cart_display_poa_items').fadeOut('slow');
              $('#poa_heading').fadeOut('slow');
              $('#hasPOA').val(false);
            }
            $('#dataRows'+id).remove();
            //alert("vipDiscountInDatabase" + $('#vipDiscountInDatabase').val());
            //alert('cart_display_cartTotal:- ' +$('#cart_display_cartTotal').html().substr(1));
             // alert('cart_display_discountAmount:- ' +$('#cart_display_discountAmount').html().substr(1));
            if (($('#cart_display_cartTotal').html().substr(1) < 200.00) && ($('#vipDiscountInDatabase').val() == 0.0) ) {
              //alert('cart_display_cartTotal:- ' +$('#cart_display_cartTotal').html().substr(1));
              //alert('cart_display_discountAmount:- ' +$('#cart_display_discountAmount').html().substr(1));
              $('#special').hide();
              //$('#cart_display_discountAmount').hide();
            }
            
          });
        } 
      } else {
        alert('There was a problem removing this product from the cart');
      }
    });
  }
  
  this.getSummary = function() {
    //alert("getsummaryCalled");
    $.get('/cart/cartSummary.jsp', function(data) {
      $('#'+cart.summaryID).html($.trim(data));
      if (cart.attemptShowCart) {
        //alert("in get method");
        $('#cart_display_cartTotal').html($('#cartTotal').val());
        //if ($('#cartTotal').val().substr(1) >= 200.00 ) {
        //  alert($('#cartTotal').val().substr(1));
          $('#cart_display_discountAmount').html($('#discountAmount').val());
        //}
        $('#cart_display_freightCost').html($('#freightCost').val());
        $('#cart_display_freightName').html($('#freightName').val());
        if ($('#discountAmountValue').val() <= 0.0){
          $('#special').hide();
        }
        $('#cart_display_gstAmount').html($('#gstAmount').val());
        $('#cart_display_orderTotal').html($('#orderTotal').val());
        $('#shipping').val($('#freightAmount').val());
        try { 
          //alert("cartTotalD is " + $('#cartTotalD').val());
          if ($('#cartTotalD').val() >= 200.0) {
            $('#cart_total_freight_amount').val(0.0);
          } else {
            $('#cart_total_freight_amount').val($('#freightAmount').val()); 
          }
          //alert("cart_total_freight_amount is " + $('#cart_total_freight_amount').val());
        } catch (e) { 
        }
        try { $('#cart_total_tax').val($('#gstAmountClean').val()); } catch (e) { }
        cart.getPaypal();
      }
    });
  }
  
  this.getPaypal = function() {
    $.get('/cart/cartPaypal.jsp', function(data) {
      $('#paypalItems').html($.trim(data));
    });
  }
  
  this.fixCartPricing = function(){
    // alert('start');
  	$.get('/cart/cartFixPricing.jsp', function(data) {
  		if ($.trim(data) == '0') {
  		//Success
  		}else{
  		  alert('There was a problem fixing the pricing in the cart');
  		}
  	});
  }
  
  this.updateProductPrices = function(productID, vipDiscount){
  	var targetID = 'productPrice_'+productID;
  	$.get('/cart/updateProductPrices.jsp?productID=' + productID + '&vipDiscount=' + vipDiscount + '&bulk=false', function(data) {
  		$('#'+targetID).html($.trim(data));
  		targetID = 'productBulkPrice_'+productID;
	  	$.get('/cart/updateProductPrices.jsp?productID=' + productID + '&vipDiscount=' + vipDiscount + '&bulk=true', function(data) {
	  		$('#'+targetID).html($.trim(data));
	  		$('#productBulkQty_'+productID).html($('#productPricePackBulkQuantity_'+productID).val());
	  		$('#productQty_'+productID).html($('#productPricePackQuantity_'+productID).val());
	  		$('#packQuantity_'+productID).val($('#productPricePackQuantity_'+productID).val());
	  		if ($('#quantity_'+productID).val() == '0'){
	  		   $('#quantity_'+productID).val($('#productPricePackQuantity_'+productID).val());
	  		}
	  	});
  	});
  }
  
  this.check = function() {
    $('#checkout').attr('disabled','disabled');
    var purchaseOrderNumber = $('#purchaseOrderNumber').val();
    var deliveryInstructions = $('#deliveryInstructions').val();
    var freight = $('#freightAmount').val();
    if (freight == 'TBA'){
      freight = "";
    }else{
      freight = "&freight=" + freight;
    }
    if ($('#poaCount').val() > 0){
        $.get('/cart/sendEmail.jsp?enquiry=true', function(data) {
          $('#cart_display_poa_items').fadeOut('slow');
          $('#nonPOAContinue').fadeIn('slow');
        });
    }
    
    if (new Number($('#freightAmount').val()) > 0) {
      //alert("Test for BuyNow. PO is " +purchaseOrderNumber+ " and deliveryInstructions is "+ deliveryInstructions);
      //$('#deliveryTable').show();
      var cart_display_discountAmount = 0.00;
      if ($('#cart_display_discountAmount').html() != null) {
        cart_display_discountAmount = $('#cart_display_discountAmount').html().substr(2);
      } 
      //alert('cart_display_discountAmount' + cart_display_discountAmount)
      //cart_display_discountAmount = cart_display_discountAmount.
      //alert('/cart/sendEmail.jsp?confirmation=true'+freight+ '&purchaseOrderNumber=' +purchaseOrderNumber+ '&deliveryInstructions=' +deliveryInstructions+ '&vipDiscount=' +cart_display_discountAmount);
      $.get('/cart/sendEmail.jsp?confirmation=true'+freight+ '&purchaseOrderNumber=' +purchaseOrderNumber+ '&deliveryInstructions=' +deliveryInstructions+ '&vipDiscount=' +cart_display_discountAmount, function(data) {
        $G.submit(cart.formID);
      });
    } else {
      customerServiceDialog.show();
      
      $.get('/cart/sendEmail.jsp?purchaseOrderNumber=' +purchaseOrderNumber+ '&deliveryInstructions=' +deliveryInstructions, function(data) {
        customerServiceDialog.getClose('reload');
      });
    }
  }
  
  this.confirm = function() {
    $('#deliveryTable').show();
    $('#confirmTable').hide();
  }
  
  this.sendEnquiry = function() {
    $('#send_enquiry').attr('disabled','disabled');
    customerServiceDialog.show(true);
    $.get('/cart/sendEmail.jsp?enquiry=true', function(data) {
      customerServiceDialog.getClose();
      $('#cart_display_poa_items').fadeOut('slow');
      $('#nonPOAContinue').fadeIn('slow');
      if ($('#nonPoaCount').val() == 0){
        $('#cart_display_no_items').fadeIn('slow');
        $('#cart_display_no_items_2').fadeIn('slow');
      }
      cart.getSummary();
    });
  }
  
  this.displayAddressChangeDialog = function(addressType, id) {
    //var response = window.confirm("Do you want to change the address");
    $('#displayAddressChangeDialogID').remove();
    //if (response) {
       var displayAddressChangeDialogID = "displayAddressChangeDialogID";
       var displayAddressChangeDialogDiv = '<div class="ui-corner-all" id="displayAddressChangeDialogID"></div>';
       $('body').append(displayAddressChangeDialogDiv);
       $('#'+displayAddressChangeDialogID).dialog({
         title: 'Change ' +addressType ,
		 autoOpen: true,
		 bgiframe: true,
		 height: 250,
		 width: 550,
		 resizable: false,
		 draggable: false,
		 modal: true,
		 closeOnEscape: false,
		 zIndex: 9999
	  });
     
      $.get('/cart/changeAddress.jsp?addressType=' +addressType+ '&id=' +id, function(data) {
        $('#'+displayAddressChangeDialogID).html($.trim(data));
      });
    //}
  }
  
  this.validateAddressChangeDialog = function() {
    var message = 'Unable to update details. Please fillup:-\n';
    var formValidated = true;
    var dialogStreetAddress = $('#dialogStreetAddress').val();
    var dialogSuburb = $('#dialogSuburb').val();
    var dialogPostcode = $('#dialogPostcode').val();
    var dialogStateID = $('#dialogStateID').val();
    var dialogState = $('#dialogStateID option:selected').text();
    if (dialogStreetAddress.length == 0) {
      formValidated = false;
      message = message + 'StreetAddress\n';
    }
    if (dialogSuburb.length == 0) {
      formValidated = false;
      message = message + 'Suburb\n';
    }
    if (dialogPostcode.length == 0) {
      formValidated = false;
      message = message + 'Postcode\n';
    }
    if (dialogStateID <= -1 || dialogStateID > 8) {
      formValidated = false;
      message = message + 'State\n';
    }
    if (formValidated) {
      var addressType = $('#addressType').val();
      var id = $('#id').val();
      $.get('/cart/changeAddress.jsp', { id: id, attemptSave: true, dialogStreetAddress: dialogStreetAddress, dialogSuburb: dialogSuburb, dialogPostcode: dialogPostcode, dialogStateID: dialogStateID } , function(data) {
        if (addressType == 'Billing Address') {
          $('#streetAddress').html(dialogStreetAddress);
          $('#suburb').html(dialogSuburb);
          $('#postcode').html(dialogPostcode);
          $('#state').html(dialogState);
        }
        if (addressType == 'Shipping Address') {
          $('#shippingStreetAddress').html(dialogStreetAddress);
          $('#shippingSuburb').html(dialogSuburb);
          $('#shippingPostcode').html(dialogPostcode);
          $('#shippingState').html(dialogState);
        }
        //alert("calling summary");
        cart.attemptShowCart = true;
        cart.getSummary();
      });
      this.closeAddressChangeDialog();
    } else {
      alert(message);
    }
  
  
  }
  this.closeAddressChangeDialog = function() {
	$('#displayAddressChangeDialogID').dialog('close');
  }
}
