/*
 * Behaviours for adding item from a list screen or detail screen that will then
 * be added to the cart i.e. CPD, Shop, Events
 */


var Cart =  {
	// button that triggers adding activities/items to the cart
	addItemEl: 'a.grey-button',
	// class that gives style for tr when activity/item has been added
	addedClass: 'item-added',
	// element that triggers the removal of items from the cart
	removeItemEl: 'a.trash-item',
	// elements that link, from the items, to the next step of the for on pay now
	payNowEl: 'span a.grey-button-pay',
	// elements that link, from the cart summary, to the next step of the for
	// on pay now
	summaryPayNowEl: 'a.grey-button-pay',
	// the product quantity form element selector
	quantitySelect: 'select[name*=product-qty-]',

	shopQtyArg: '',

	// add events to the relevant elements on the page
	init: function () {

		// adds the events for the 'Add Activity' buttons
		Cart.addItemEvents();
		// adds the events for the 'Remove Activity' icons
		Cart.removeItemEvents();
		// add events for the pay now buttons
		Cart.payNowEvents();
	},

	addItemEvents: function() {
		// if we are on a shop page ensure that the hover event isn't triggered for the qty input
		var shopQty = $$(Cart.quantitySelect);
		if($chk(shopQty)) {
			shopQty.addEvent('click', function(ev){
				ev.stop();
			});
			Cart.updateQuantity();
		}

		var buttonEls = $$(Cart.addItemEl);
		if(buttonEls) {
			// add events to all buttons on the page
			buttonEls.addEvents({
				'click': function(e) {

					var buttonText = this.getElement('span').get('text');
					if(buttonText.contains('Register') || buttonText.contains('Download')) {

						// button leads to registration page rather than adding to cart
						//window.location = '/conferences/personal';
					} else {
						// stop propogation and bubbling of events
						e = new Event(e).stop();


						// adding and activity or event
						// if when the page was drawn there was no cart-summary div
						// ensure there is one now
						Cart.addCartSummaryContainer();

						// send request that adds item to the cart object
						var requestState = Cart.sendRequest('add', Cart.getItemId(this), Cart.getItemType(this));
						if(requestState) {
							// kill the event that is doing the hovers states on rollover
							// so the green shows straight away for some reason removeEvent
							// doesn't work
							Cart.removeMouseOver(this);
							// switch the element to display activity added
							Cart.hideAddButton(this);
							//  on request success change the parent
							Cart.setAddedColor(this);
						}

					}
				}
			});
		}
	},

	updateQuantity :function()
	{
		var quantitySelects = $$(Cart.quantitySelect);

		quantitySelects.addEvent('change', function(ev) {
			// only add and remove if the item has already been added
			selectValue = this.get('value');
			selectId = this.get('id')
			if (selectValue == 0) {
				this.set('value', 1);
				alert('Please select the number of products you would like to purchase.');
				return false;
			} else if($chk(this.getNext('a')) && this.getNext('a').hasClass('hidden')) {
				Cart.sendRequest('add', selectId.split('-')[2], 'Product')
				/*if (Cart.sendRequest('remove', selectId.split('-')[2], 'Product')) {
					setTimeout("Cart.sendRequest('add', selectId.split('-')[2], 'Product')", 100);
				}*/
			} else if ($chk(this.getParent('td')) &&  this.getParent('td').hasClass('quantity')) {
				Cart.sendRequest('add', selectId.split('-')[2], 'Product')
				/*if (Cart.sendRequest('remove', selectId.split('-')[2], 'Product')) {
					setTimeout("Cart.sendRequest('add', selectId.split('-')[2], 'Product')", 100);
				}*/
				//Cart.sendRequest('remove', this.get('id').split('-')[2], 'Product').sendRequest('add', this.get('id').split('-')[2], 'Product');
			//	Cart.sendRequest('remove', this.get('id').split('-')[2], 'Product');
			//	Cart.sendRequest('add', this.get('id').split('-')[2], 'Product');
			}
			return true;

		});
	},

	addCartSummaryContainer: function() {

		if(!$('column-right').getElement('.cart-summary')) {

			var myPanel = new Element('div', {
				'class': 'section cart-summary'
			});

			var parts = location.href.split('index.html');
			if($chk(parts[4])) { // checking to see if we are on a cpd detail page
				myPanel.inject($('column-right'), 'top');
			} else {

				myPanel.inject($('column-right'), 'bottom');
				CartSummary.init();
			}


		}
	},

	removeItemEvents: function() {
		var removeItemEls = $$(Cart.removeItemEl);
		removeItemEls.addEvents({
			'click': function(e) {
				// stop propogation and bubbling of events
				e = new Event(e).stop();
				Cart.removeMouseOver(this);
				// show the remove item button and activity added text
				Cart.showAddButton(this);
				// send request that removes item to cart obejct
				Cart.sendRequest('remove', Cart.getItemId(this), Cart.getItemType(this));
				// on success remove the color
				Cart.removeAddedColor(this);
			}
		});
	},

	payNowEvents: function() {

		var payNowEls = $$(Cart.payNowEl);
		payNowEls.addEvents({
			'click': function(e) {
				/*e = new Event(e).stop();
				if(window.location.href.contains('cpd-activities')) {
					window.location = "/cpd-activities/benefits";
				} else if(window.location.href.contains('events-and-conferences')) {
					window.location = "/events/personal";
				}*/

			}
		});
		// separate add for the pay now button in the cart summary
		Cart.summaryPayNowEvent();
	},

	summaryPayNowEvent: function() {
		if($('column-right') && $('column-right').getElement(Cart.summaryPayNowEl)) {
			$('column-right').getElement(Cart.summaryPayNowEl).addEvent('click', function(e){

				//e = new Event(e).stop();
				if(window.location.href.contains('cpd-activities')) {
					window.location = "/cpd-activities/benefits";
				} else if(window.location.href.contains('cpd-private-study')) {
					window.location = "/cpd-private-study/benefits";
				}else if(window.location.href.contains('events-and-conferences') || window.location.href.contains('events')) {
					window.location = "/events/personal";
				} else if (window.location.href.contains('member-events')) {
					window.location = "/mymia-events/requests";
				} else if (window.location.href.contains('shop')) {
					window.location = "/shop/personal";
				}
			});
		}
	},

	setAddedColor: function(el) {
		if(el.getParent('tr')) {
			el.getParent('tr').addClass(Cart.addedClass);
		} else if (el.getParent('div')) {
			el.getParent('div').addClass(Cart.addedClass);
		}
	},

	removeAddedColor: function(el) {
		if(el) {
			if(el.getParent('tr')) {
				el.getParent('tr').removeClass(Cart.addedClass);
				el.getParent('tr').highlight('#FF9F9F');
			} else if(el.getParent('div')) {
				el.getParent('div').removeClass(Cart.addedClass);
				el.getParent('div').highlight('#FF9F9F');
			}
			attach_rollovers.delay('500');
		}
	},
	/**
	 * Function returns the id of the item
	 */
	getItemId: function(buttonEl) {

		// if the button is on the list page
		if(buttonEl.getParent('table.list-results')) {
			return buttonEl.getParent('tr').get('id').split('-')[1];
		// else it's on the detail page
		} else if(buttonEl.getParent('.columns')) {
			return buttonEl.getParent('.columns').get('id').split('-')[1];
		// else it on the checkout view
		} else {
			return buttonEl.get('id').split('-')[1];
		}
		return false;
	},


	getItemType: function(buttonEl) {

		if(buttonEl.getParent('table.list-results')) {
			return buttonEl.getParent('tr').get('id').split('-')[0];
		// else it's on the detail page
		} else if(buttonEl.getParent('.columns')) {
			return buttonEl.getParent('.columns').get('id').split('-')[0];
		// else it on the checkout view
		} else {
			return buttonEl.get('id').split('-')[0];
		}
		return false;
	},

	removeMouseOver: function(el) {
		if(el.getParent('tr')){
			el.getParent('tr').onmouseover = null;
		}
	},

	// hides the add Button and shows the Activity added text
	// todo: break into two parts
	hideAddButton: function(el) {
		el.addClass('hidden');
		el.getNext().removeClass('hidden');
	},

	showAddButton: function(el) {
		if(el.getParent('table.list-results') || el.getParent('.columns')) {
			el.getParent('span').addClass('hidden');
			el.getParent('span').getPrevious().removeClass('hidden');
		}
	},

	sendRequest: function(action, id, addItemType)
	{
		//shop has a qty so we need to check what it has been set to
		var shopQty = $$('select[name*=product-qty-' + id + ']').get('value');

		if($chk(shopQty) && shopQty > 0) {
			this.shopQtyArg = '&itemQty=' + shopQty;
		}

//return false;
		// used for the special case  of removal on the review/cart page
		if($chk($('item-' + id))) {
			var itemEl = $('item-' + id);
			var itemType = itemEl.getParent('tr').getElement('td.item span').get('class');
			requestArgs = 'itemAction=' + action + '&itemId=' + id + '&itemType=' + itemType + this.shopQtyArg;
		} else if (action == 'add' || action == 'remove') {
			itemType = addItemType;
			var requestArgs = 'itemAction=' + action + '&itemId=' + id + '&itemType=' + itemType + this.shopQtyArg;
		}
		var myReq = new Request.HTML({
			url: '/ajax/ajaxModule/ModuleCart/',
			method: 'get',
			link: 'chain',
			onComplete: function() {
			},
			onSuccess: function(response) {

				// if we are on list or detail page
				if($('column-right').getElement('.cart-summary')) {
					$('column-right').getElement('.cart-summary').empty();
					$$(response).inject($('column-right').getElement('.cart-summary'));
				// if we are on the cart review page
				} else {
					Cart.removeAddedColor(itemEl);
					try {
						if (itemType == 'Membership') {
							itemEl.getParent('table').getElement('.JoiningFee').getParent('tr').dispose();
						}
						window.location.href = window.location.href;
					} catch(e) {
						window.location.href = window.location.href;
					}
					itemEl.getParent('tr').dispose();
				}
				CartItemTip.init();
				Cart.summaryPayNowEvent();
			},
			onFailure: function () {

			}
		}).send(requestArgs);

		return true;
	}
}

var CartItemTip = {

	init: function() {
		$$('#content div.cart-summary li a').each(function(el) {
			var title = el.get('title');
			if ($chk(title)) {
				el.store('tip:title',title);
				el.store('tip:text','');
			}
        });

        // add tips
        var tip = new Tips($$('#content div.cart-summary li a'), {
			className:'headerTip',
			showDelay: 50
        });

	}
}
window.addEvent('domready', function() {
	Cart.init();
	CartItemTip.init();
});
