
var Bag = Class.create();

Bag.prototype = {
	isOpen:false,
	doOpenBag:false,
	isAnimating:false,
	contentElementId:"bagPopup",
	priceElementId:"bagSummaryPrice",
	itemCountElementId:"bagNumberOfItems",
	titleElementId:"bagSummaryTitle",
	orderCalculateUrlParam:"OrderCalculate%3FURL%3DBagNotificationView",
	orderCalculateWithCatentryUrlParam:"OrderCalculate%3Fitem_quantity*%3D%26URL%3DBagNotificationView",
	imageDir: $('_imageDir') ? $('_imageDir').value : '' ,
	bagTitleImg:"bag-icon-itemadded.gif",
	
	initialize:function() {},

	/**
	 * Opens the bag notification panel
	 */
	openBag:function() {
        window.scrollTo(0,0);
		if ((!this.isOpen || $(this.contentElementId).innerHTML != "")) {
			this.isAnimating = true;
			            
			Effect.SlideDown(this.contentElementId,
				{
					duration:0.5,
					afterFinish:this.openBagAfterFinish.bind(this)
				}
			);
		}
	},
 	
	/**
	 * Executes after the bag opening animation finishes
	 */
 	openBagAfterFinish:function() {
		this.isOpen = true;
		this.isAnimating = false;
		this.doOpenBag = false;
		
		var handler = this.checkBag.bind(this);
		
		Event.observe(document, "mousedown", handler);
		Event.observe(this.contentElementId, "mouseover", 
			function() { Event.stopObserving(document, "mousedown", handler); }
		);
		Event.observe(this.contentElementId, "mouseout", 
			function() { Event.observe(document, "mousedown", handler); }
		);
 	},
	
	/**
	 * Closes the bag
	 */
	closeBag:function() {
		if (this.isOpen && !this.isAnimating) {
			this.isAnimating = true;

			Effect.SlideUp(this.contentElementId,
				{
					duration:0.5,
					afterFinish:this.closeBagAfterFinish.bind(this)
				}
			);
		}
	},
	
	/**
	 * Executes after the bag closing animation finishes
	 */
	closeBagAfterFinish:function() {
		this.isOpen = false;
		this.isAnimating = false;
		this.doOpenBag = false;
			
		Event.stopObserving(document, "mousedown", this.checkBag.bind(this));
	},

	/**
	 * Checks if the bag is open before closing it
	 */
	checkBag:function() {
		if (this.isOpen) {
			var bag = this;
			new PeriodicalExecuter(function(pe) {
				bag.closeBag();
				pe.stop();
			}, 0.5);
		}
	}
	
}

var bag = new Bag();

/**
 * Adds an item to the basket via ajax
 */
function addToBag(form) {	
	if (!bag.isAnimating && !bag.doOpenBag) {
		if($("messageerror")){
			$("messageerror").remove();
		}
	  	if (form.forRegistry && form.forRegistry.value) {
  			form.externalId.value = form.forRegistry.value;
  		}
		form.URL.value = bag.orderCalculateUrlParam;
		bag.doOpenBag = true;
		
		new Ajax.Request(
			"OrderItemAdd",
			{
				method: 'post',
				parameters: retrieveFormValues(form),
				onComplete: this.setBag.bind(this)
			}
		);
	}
}

function addAccessoryToBag(form, productId, optionBoxId) {
	if (!bag.isAnimating && !bag.doOpenBag) {
		if (optionBoxId == -1) {
			quantitySelected = 1;
		} else {
			index = eval("$('quantityOptions' + '" + optionBoxId + "').selectedIndex");
			quantitySelected = eval("$('quantityOptions' + '" + optionBoxId + "').options[index].value");
		}
		form.catEntryId.value = productId;
		form.productId.value = productId;
		form.quantity.value = quantitySelected
		
		addToBag(form);
	}
}

function addCatEntryToBag(form, catEntryId, catEntryQuantity) {
	if (!bag.isAnimating && !bag.doOpenBag) {
	  	if (form.forRegistry && form.forRegistry.value) {
  			form.externalId.value = form.forRegistry.value;
  		}
  		if (catEntryQuantity == null || catEntryQuantity == 'undefined') {
			catEntryQuantity = 1;
		}
		form.catEntryId.value = catEntryId;
	    form.quantity.value = catEntryQuantity;
		form.URL.value = bag.orderCalculateWithCatentryUrlParam;
		bag.doOpenBag = true;
		
		new Ajax.Request(
			"OrderItemAdd",
			{
				method: 'post',
				parameters: retrieveFormValues(form),
				onComplete: this.setBag.bind(this)
			}
		);
	}
}

function addCatEntryToBag(form, catEntryId) {
	if (!bag.isAnimating && !bag.doOpenBag) {
		form.catEntryId.value = catEntryId;
		
		addToBag(form);
	}
}

/**
 * Removes an item to the basket via ajax
 */
function removeFromBag(form) {
	if (bag.isOpen && !bag.isAnimating && !bag.doOpenBag) {
		form.orderItemId.value = $('_orderItemId').value;
		form.URL.value = bag.orderCalculateUrlParam;
		bag.doOpenBag = true;
		
		new Ajax.Request(
			"OrderItemDelete",
			{
				method: 'post',
				parameters: retrieveFormValues(form),
				onComplete: this.setBag.bind(this)
			}
		);
	}
}

function setBag(transport) {
	$(bag.contentElementId).update(transport.responseText);	
	if ($('_msg')) {				
		$(bag.itemCountElementId).update($('_itemCount').value);
		$(bag.priceElementId).update($('_price').value);
		// $(bag.titleElementId).setAttribute('src', bag.imageDir + bag.bagTitleImg);
		bag.openBag();
	} else {
		$(bag.contentElementId).update("");	
		handleError(transport);
	}
}

/**
 * Replaces the body with the error page returned in the ajax response
 */
function handleError(transport) {
	$("OrderItemAddForm").insert({ top: transport.responseText });
	bag.doOpenBag = false;
}

function retrieveFormValues(form) {  
	var params = "";  
  	var element = "";  
  	for (var i = 0; i < form.elements.length; i++) {  
   		element = form.elements[i]; 
  		params += element.name + "=" + element.value + "&";  
  	}
  	params = params.substr(0,(params.length - 1));  
  	return params;  
}  

