var ShoppingCart = new Class.create();
ShoppingCart.prototype = {
	initialize: function() {
		this.container = $('shoppingCart');
		this.setup();
	},
	setup: function() {
		if ($('shippingForm')) {
			this.shippingForm = $('shippingForm');
			Event.observe(this.shippingForm, 'submit', this.updateShipping.bindAsEventListener(this));
			
			this.shippingMethod = $('shippingMethod');
			Event.observe(this.shippingMethod, 'change', this.updateShipping.bindAsEventListener(this));
		}
		
		if ($('enterZip')) {
			Event.observe('enterZip', 'click', this.promptZipCode.bindAsEventListener(this));
		}
		
		Event.observe($('postalCode'), 'keyup', this.checkZipCode.bindAsEventListener(this));
		
		this.updateForms  = this.container.getElementsBySelector('form.updateCartItem');
		
		this.updateForms.each(function(form) {
			Event.observe(form.down('select'), 'change', this.updateCartItem.bindAsEventListener(this)) }.bind(this));
		
		this.removeLinks = this.container.getElementsBySelector('a.remove');
		this.removeLinks.each(function(el) {
			Event.observe(el, 'click', this.removeCartItem.bindAsEventListener(this)) }.bind(this));
	
		this.standardQuantityLinks = this.container.getElementsBySelector('a.standardQuant');
	
		 this.standardQuantityLinks.each(function(el) {
		 Event.observe(el, 'click', this.standardQuantityDisplay.bindAsEventListener(this)) }.bind(this));
			
	},
	complete: function() {
		this.setup();
		new MiniCart();
		$('shippingProgress').hide();
	},
	
	updateShipping: function(event) {
		var zipCode = this.shippingForm.elements['postalCode'].value;
		if (!Validation.get('validate-zipcode').test(zipCode)) {
			alert('Please enter a valid zip code.');
		} else {
			$('shippingProgress').show();
			var myAjax = new Ajax.Updater(this.container, '/ae/control/updateShipping',
				{ method: 'post', parameters: Form.serialize(this.shippingForm), onComplete: this.complete.bind(this) });
		}
		Event.stop(event);
	},
	promptZipCode: function(event) {
		var zipCode = prompt('Enter the zip code where you want to ship this order.', '');
		if (!Validation.get('validate-zipcode').test(zipCode)) {
			alert('Please enter a valid zip code.');
		} else if (zipCode != null){
			this.shippingForm.elements['postalCode'].value = zipCode;
			this.updateShipping(false);
		}
		Event.stop(event);
	},
	checkZipCode: function(event) {
		if (Validation.get('validate-zipcode').test($F('postalCode'))) {
			this.updateShipping(event);
		}
	},
	updateCartItem: function(event) {
		var el = Event.element(event);
		var qtyToUpdate = el.form.add_product_id.value;

		if(qtyToUpdate!="custom" && qtyToUpdate!="cancel"){
			this.showItemProgress(el.form.id);
			var myAjax = new Ajax.Updater(this.container, '/ae/control/updateCartItem',
				{ method: 'post', parameters: Form.serialize(el.form), onComplete: this.complete.bind(this) });
		}else if(qtyToUpdate == "cancel"){
			var el = Event.element(event);
			var qtyValues = "qtyValues_"+el.form.itemIndex.value;
			var myAjax = new Ajax.Updater(qtyValues, '/ae/control/changeToCustom',
				{ method: 'post', parameters: Form.serialize(el.form), onComplete: this.initChangeLinks.bind(this) });
		}else{
			var el = Event.element(event);
			var qtyValues = "qtyValues_"+el.form.itemIndex.value;
			var myAjax = new Ajax.Updater(qtyValues, '/ae/control/changeToCustom',
				{ method: 'post', parameters: Form.serialize(el.form),onComplete: this.initShoppingCart.bind(this) });
		}	
		Event.stop(event);
	},
	initShoppingCart: function() {
		this.updateCustomQuantity = this.container.getElementsBySelector('form.updateCustomQuantity');
		this.updateCustomQuantity.each(function(form) {
			Event.observe(form.down('input.qty_update'),'keyup', this.updateCartItemQuantity.bindAsEventListener(this))}.bind(this));	
		this.initChangeLinks();	
			
	},
	initChangeLinks: function() {
		this.standardQuantityLinks = this.container.getElementsBySelector('a.standardQuant');
		 this.standardQuantityLinks.each(function(el) {
		 Event.observe(el, 'click', this.standardQuantityDisplay.bindAsEventListener(this)) }.bind(this));
	},
	
	initStandardQuant: function() {
		this.updateForms  = this.container.getElementsBySelector('form.updateCartItem');
		this.updateForms.each(function(form) {
			Event.observe(form.down('select'), 'change', this.updateCartItem.bindAsEventListener(this)) }.bind(this));
			
	this.setToCustomLinks = this.container.getElementsBySelector('a.setToCustom');
		 this.setToCustomLinks.each(function(el) {
		 Event.observe(el, 'click', this.setToCustom.bindAsEventListener(this)) }.bind(this));		
	},
	setToCustom: function(event){
			var el = Event.element(event);
			var qtyValues = "qtyValues_"+el.id;
			var myAjax = new Ajax.Updater(qtyValues, el.getAttribute('href'),
				{ method: 'post',onComplete: this.initShoppingCart.bind(this) });
			Event.stop(event);		
	},
	standardQuantityDisplay:function(event) {
			var el = Event.element(event);
			var id = el.id;
			var qtyValues = "qtyValues_"+id;
			var myAjax = new Ajax.Updater(qtyValues, el.getAttribute('href'),
				{ method: 'post',onComplete: this.initStandardQuant.bind(this) });
	
			Event.stop(event);	
	},
	updateCartItemQuantity: function(event) {
	  var el = Event.element(event);
	  var custQuantStr = el.form.qty_plain;
	  if(custQuantStr == null || custQuantStr == 'undefined'){
	    var custQuantStr = el.form.qty_print.value;
	  }else{
	  	var custQuantStr = custQuantStr.value;
	  }
		var respos = el.form.itemIndex.value;
	  if(custQuantStr!=null && custQuantStr!=""){
		  custQuantStr = custQuantStr.replace(/^\s+|\s+$/g, '');
	       	if(!(/^[-+]?[0-9]+$/.test(parseInt(custQuantStr)))){
	       		$('inlineError_'+respos).innerHTML = 'Please enter a valid quantity.'
	       		return false;
	       	}
       		if(custQuantStr!=""){
       			custQuantStr = custQuantStr.replace(",","");
		       	var customQuant=parseInt(custQuantStr);
		       	allowableMultiple = 50;
		       	var formProductId = el.form.add_product_id.value;;
	       		if(formProductId.match("P1C")!=null || formProductId.match("P2C")!=null || formProductId.match("P4C")!=null){
	       			allowableMultiple = 500;
	       		}
	       		
	       		if(customQuant<allowableMultiple){
		    		$('inlineError_'+respos).innerHTML= "The minimum is "+allowableMultiple+".";
		    		return;
		    	}
		    	
		    	if(customQuant>allowableMultiple){
		    		var decimalQuant = customQuant/allowableMultiple;
		    		if(!(/^[-+]?[0-9]+$/.test(decimalQuant))){
		    			$('inlineError_'+respos).innerHTML = "The quantity is required to be a multiple of "+allowableMultiple+".";
		    			return;
		    		}
		    	}
	       }else{
	       		$('inlineError_'+respos).innerHTML = 'Quantity cannot be Empty.';
	       		return;
	       }	
	  }else{
	  	$('inlineError_'+respos).innerHTML = 'Quantity cannot be Empty.';
	  	return;
	  }
		$('inlineError_'+respos).innerHTML = '';
		this.updateCartItem(event);
	},
	removeCartItem: function(event) {
		var el = Event.element(event);
		this.showItemProgress(el.id);
		var myAjax = new Ajax.Updater(this.container, el.getAttribute('href'),
			{ method: 'post', onComplete: this.complete.bind(this) });
		Event.stop(event);
	},
	showItemProgress: function(id) {
		var position = id.replace(/(updateCartItem|remove|updateCustomQuantity)_/,'');
		$('total_' + position).hide();
		$('progress_' + position).show();
	}
}

/*--------------------------------------------------------------------------*/

Event.onDOMReady(function(){
	new ShoppingCart();
	new PopUp('security', 'securityCallout');
	new PopUp('privacy', 'privacyCallout');
	new PopUp('return', 'returnCallout');
	new PopUp('shipping', 'shippingCallout');
});
