var OrangeExtras = {}

OrangeExtras.addDescription = Class.create({
	initialize: function (descriptionElements, options) {
		this.descriptionElement = descriptionElements;
		this.options = Object.extend({}, options || {});

		this.modalHeader = '<div class="modal description"><div class="modal-title-bar" onclick="Control.Modal.close(); return false;"><p><a class="close" onclick="Control.Modal.close(); return false;" href="#">close</a></p></div><div id="modal-window">';
		this.modalFooter = '</div></div>';
		this.alertBoxHtml = this.modalHeader + this.modalFooter;

		this.descriptionElement.each(function(i) {
			i.down('.desc').hide();
			i.down('.bundle_action').insert({ bottom:'<p class="details"><a href="#" class="show_overlay">more about this accessory</a></p>'});
			this.addClickHandler(i);
		}.bind(this));

	},
	addClickHandler: function(element) {
		element.select('a', '.show_overlay').invoke('observe', 'click', this.show.bindAsEventListener(this));
	},
	show: function(event) {
		var i = event.element();
		this.alertBoxHtml = this.modalHeader + (i.up('.bundle_action').previous('.h4').innerHTML) + (i.up('.bundle_action').next('.desc')).innerHTML + this.modalFooter;
		new openModalWithContent(this.alertBoxHtml);
		Event.stop(event);
		return false;
	}
});

OrangeExtras.toggleByRadioButtonsYesNo = Class.create({
	initialize: function (radioName, yesToggleElements, noToggleElements, itemsToFade){
		this.yesTogglingElement = yesToggleElements;
		this.noTogglingElement = noToggleElements;
		this.radioElements = $$('input[name=' + radioName + ']');
		this.itemsToFade = itemsToFade;

		this.noTogglingElement.each(Element.hide);
		this.yesTogglingElement.each(Element.hide);
		this.itemsToFade.each(function(e) { e.setOpacity(0.3) });

		this.toggle();
		this.addHandlerToRadios();
	},
	toggle: function(){
		var p = $$('.get_broadband');
		this.radioElements.each(function(r){
			if ((r.value == 'no') && r.checked) {
				$A(this.yesTogglingElement).invoke('hide');
				$A(this.noTogglingElement).invoke('show');
				$A(this.itemsToFade).each( function(e) { e.setOpacity(1); });

				$A(p).each( function(e) {
					e.down('a').show();
					if (e.previous('.tempDisabled')) {
						e.previous('.tempDisabled').hide();
					}
				});
			}
			else if ((r.value == 'yes') && r.checked) {
				$A(this.yesTogglingElement).invoke('show');
				$A(this.noTogglingElement).invoke('hide');
				$A(this.itemsToFade).each( function(e) { e.setOpacity(0.3); });

				$A(p).each( function(e) {
					e.down('a').hide();
					if (e.previous('.tempDisabled')) {
						e.previous('.tempDisabled').show();
					} else {
						var image = Element('img', { 'class':'tempDisabled', 'src':'/shop/library/images/broadband/btn_get_broadband_off.gif'} );
						e.insert({ before:image });
					}
				});

			}
		}.bind(this));
	},
	addHandlerToRadios: function() {
		this.radioElements.invoke('observe', 'click', this.toggle.bind(this));
	}
});

OrangeExtras.addJSOptions = Class.create({
	/**
	* 	This class unhides additional links to section areas, and
	* 	adds the checkout button to bottom of the main content - after the additional links
	*/
	initialize: function(options) {
		this.options = Object.extend({
			// options go here
		}, options || {});

		($('inner').down('.section-links')).removeClassName('hide');
	}
});

OrangeExtras.observeQuantity = Class.create({
	initialize: function(elements, maxQuantity, options) {
		this.elements = $$(elements);
		this.maxQuantity = maxQuantity;
		this.currQuantities = {};

		this.options = Object.extend({
			overMaximumError : '<span class="plain">You have already reached the maximum number of accessories. If you wish to add more, you will first need to remove one or more of the items you\'ve already selected.</span>',
			atMaximumWarning : '<span class="plain">You now have maximum number of accessories in your basket. If you wish to add more, you will first need to remove one or more of the items you\'ve already selected.</span>',
			onSuccessfulCheck : Prototype.emptyFunction,
			unMarkedQuantity : 0
		}, options || {});

		this.addCheckQuantityHandler();
		this.checkQuantities();
	},

	addCheckQuantityHandler: function() {
		this.elements.invoke('observe', 'change', this.checkQuantities.bindAsEventListener(this));
		this.elements.each( function(elem) { this.currQuantities[elem.id] = parseInt(elem.getValue()); }.bind(this));
	},

	checkQuantities: function(evt) {
		var totalSelected = 0;
		var submitAllowed = true;
		totalSelected = this.getTotalSelected();

		// Following section checks the element being currently selected and sets it to what it was
		// before change if the change takes the total above the maximum quantity.
		if ((evt != null) && (totalSelected > this.maxQuantity)) {
			overElem = Event.element(evt);
			if(this.currQuantities[overElem.id]) {
				overElem.setValue(this.currQuantities[overElem.id]);
			} else {
				overElem.setValue(0);
			}
			new openModalWithContent(this.options.overMaximumError, { message: true });
			totalSelected = this.getTotalSelected();
			submitAllowed = false;
		}
		if (evt != null) {
			overElem = Event.element(evt);
			this.currQuantities[overElem.id] = parseInt(overElem.getValue());
		}

		var remainingQuantity = this.maxQuantity - totalSelected;
		// Update the dropdowns to reflect the quantity available
		this.elements.each( function(elem, i) {
			var currQuantity = parseInt(elem.getValue());
			var totalAllowed = currQuantity + remainingQuantity;

			// Iterate through options amending classnames
			elem.select('option').each( function(opt, j) {
				if (parseInt(opt.text) > totalAllowed) {
					opt.style.color = '#CCCCCC';
				    if (window.opera) { opt.style.display = 'block'; opt.style.display = 'inline'; }
				}
				else if (parseInt(opt.text) <= totalAllowed) {
					opt.style.color = '#333333';
					if (window.opera) { opt.style.display = 'block'; opt.style.display = 'inline'; }
				}
			}.bind(this));
		}.bind(this));

		// Form is only submitted if the user has changed something, and if the total did not exceed the maximum
		if ((evt != null) && submitAllowed) {
			var elem = evt.element();
			var url = elem.up('form').action + "?ajax=yes&submit_update_basket=update_basket&" + elem.up('form').serialize();
			this.notify('onSuccessfulCheck', url);

			if (remainingQuantity == 0) {
				new openModalWithContent(this.options.atMaximumWarning, { message: true } );
			}
		}
	},

	getTotalSelected: function() {
		// Check current quantity of items selected
		var totalSelected = 0;
		this.elements.each( function(elem, k) {
			totalSelected = totalSelected + parseInt(elem.getValue());
		}.bind(this));
		totalSelected = totalSelected + this.options.unMarkedQuantity;
		return totalSelected
	},
	notify: function(event_name){
		try{
			if(this.options[event_name])
				return [this.options[event_name].bindAsEventListener(this).apply(this.options[event_name],$A(arguments).slice(1))];
		}catch(e){
			if(e != $break)
				throw e;
			else
				return false;
		}
	},
	setUnMarkedQuantity: function(newQuantity) {
		this.options.unMarkedQuantity = newQuantity;
		this.checkQuantities(null);
	},
	getUnMarkedQuantity: function() {
		return this.options.unMarkedQuantity;
	}
});