/** Refactored version of miniBasket: splits the formHandler functions from the miniBasket class */
OrangeShop.formHandler = Class.create({
	initialize: function(options) {
		this.options = Object.extend({
			submitMethod: Prototype.emptyFunction
		}, options || {});
		this.options.submitMethod = this.submit;
		if (this.options.element) { this.options.element = $(this.options.element); }
	},

	/** form handler methods */
	attachAddItemHandlers: function(aElements) {
		// This line added to fix Opera xpath bug - opera cannot cope with .select('.class element'), only .select('.class')
		aElements.each( function(e) { e = e.down('a'); });
		aElements.invoke('observe', 'click', function(evt){
			Event.stop(evt);
			// This if/else added for the cases where the a tag wraps an img tag that sees itself as the event element.
			if (evt.element().tagName.toLowerCase() == 'a')
				var url = (evt.element().href + "&ajax=yes");
			else
				var url = (evt.element().up('a').href + "&ajax=yes");
			// fix to prevent IE caching of request
			if(Prototype.Browser.IE) {
				var d = new Date();
				var randomNum = (Math.floor(Math.random() * 101)) + (d.getSeconds() * 0xFFFFF);
				url += "&jsNoCache=" + randomNum;
			}
			this.notify('submitMethod', url);
			return false;
		}.bind(this))
	},
	attachPlanChoiceHandlers: function(aElements) {
		// This line added to fix Opera xpath bug - opera cannot cope with .select('.class element'), only .select('.class')
		aElements.each( function(e) { e = e.down('a'); });
		aElements.invoke('observe', 'click', function(evt){
			Event.stop(evt);
			// This if/else added for the cases where the a tag wraps an img tag that sees itself as the event element.
			if (evt.element().tagName.toLowerCase() == 'a')
				var url = (evt.element().href + "&ajax=yes");
			else
				var url = (evt.element().up('a').href + "&ajax=yes");
			new ajaxModal(url);
			return false;
		}.bind(this))
	},
	attachPlanChoiceHandlersToInputs: function(inputElements) {
		inputElements.invoke('observe', 'click', function(evt){
			Event.stop(evt);
			var parentForm = evt.element().up('form');
			var url = parentForm.action + "?ajax=yes&" + parentForm.serialize();
	
			new Ajax.Request(url, {
				method: 'get',
				onSuccess: function(response) {
					if (response.responseText.isJSON()) {
						this.displayJSONmessage(response.responseText.evalJSON(true));
					} else {
						new openModalWithContent(response.responseText);
					}
				}.bind(this)
			});
			return false;
		}.bind(this))
	},
	attachAddItemHandlersToInputs: function(iElements) {
		iElements.invoke('observe', 'click', function(evt){
			Event.stop(evt);
			this.serializeAndSend(evt);
			return false;
		}.bindAsEventListener(this))
	},
	attachAddItemHandlersToRadios: function(rElements) {
		rElements.invoke('observe', 'click', function(evt){
			this.serializeAndSend(evt);
			return false;
		}.bindAsEventListener(this))
	},
	attachAddItemHandlersToSelects: function(sElements) {
		sElements.invoke('observe', 'change', function(evt){
			Event.stop(evt);
			this.serializeAndSend(evt);
			return false;
		}.bindAsEventListener(this))
	},

	/** form submitter methods */
	serializeAndSend: function(evt) {
		var parentForm = evt.element().up('form');
		var url = parentForm.action + "?ajax=yes&" + parentForm.serialize();

		var type = evt.element().type;
		if (type == 'image' || type == 'button' || type == 'submit') {
			url += this.getClickPos(evt);
		}
		this.notify('submitMethod', url);
		return;
	},
	getClickPos: function(evt) {
		var elem = Event.element(evt);
		elemPos = elem.cumulativeOffset();
		var pos = "&" + elem.name + "_x=" + (evt.pointerX()-elemPos.left) + "&" + elem.name + "_y=" + (evt.pointerY()-elemPos.top);
		return pos;
	},
	submit: function(url){
		new Ajax.Request(url, {
			onLoading: function () {
				if(this.options.element) {
					//this.options.element.update('<p class="ajax_loader"><span>LOADING</span><p>')
				}
			}.bind(this),
			method: 'get',
			onComplete: function(response) {
				if (response.responseText.isJSON()) {
					this.displayJSONmessage(response.responseText.evalJSON(true));
				} else {
					if (this.options.element) {
						try {
							this.options.element.update(response.responseText);
							if (this.options.onUpdateBasket)
								this.notify('onUpdateBasket');
						} catch(e) {
							/* In case the element is not defined properly */
						}
					}
					if (this.options.confirmationUrl)
						this.displayConfirmation(this.options.confirmationUrl);

					if (this.options.onUpdate)
						this.options.onUpdate;
					if (this.options.afterSubmit)
						this.attachHandlersToCheckoutLinks('.mini-basket .checkoutBtn','div.extras');
				}

			}.bind(this)
		});
	},
	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;
		}
	},

	/** After form methods*/
	displayConfirmation: function(url) {
		if (this.options.itemAddedConfirmationTarget)
			new Ajax.Updater(this.options.itemAddedConfirmationTarget, url, {
				evalScripts: true,
				method: 'get',
				parameters: '?isAjax=true'
			})
		else
			new ajaxModal(url)
	},

	/** For JSON responses */
	displayJSONmessage: function(JSON) {
		// Change of confirmationUrl.
		if (JSON.redirect) { this.displayConfirmation(JSON.redirect); }
		// Error message returned
		else if (JSON.errormsg) { new openModalWithContent(JSON.errormsg, { message: true });	}
	}
});

OrangeShop.continualFormHandler = Class.create(OrangeShop.formHandler, { 
	initialize: function($super, options) {
		$super(options); 
		this.options.submitMethod = this.modalSubmit; 
	}, 
	modalSubmit: function(url){
		var m; 
		if (Control.Modal.current) {
			m = Control.Modal.current;
		} else {
			m = new Control.Modal(false,{
				overlayCloseOnClick: false
			});
		}
		
		new Ajax.Request(url, {
			onLoading: function () {
				//m.update('<p class="ajax_loader"><span>LOADING</span><p>')
			}.bind(this),
			method: 'get',
			onComplete: function(response) {			
				m.open();
				m.update(response.responseText);
			}.bind(this)
		});
	}	
}); 

OrangeShop.miniBasket = Class.create(OrangeShop.formHandler, {
	initialize: function($super, element, options){
		$super(options);
		this.options.element = $(element);

		if (options.itemAddedConfirmationUrl)
			this.options.confirmationUrl = options.itemAddedConfirmationUrl;

		// KM 03/08/09 This block added to try and force IE6 to reload the minibasket. 
		if (this.options.checkBasketURL && Prototype.Browser.IE  && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == '6') {
			new Ajax.Request(this.options.checkBasketURL, {
				method:'get',
				onSuccess: function(response) {
					if (response.responseText.include('true')) {
						new Ajax.Request(this.options.loadBasketURL, {
							onSuccess:function(response) {
								this.options.element.update(response.responseText);
							}.bind(this),
							onComplete: this.loadAdvancedView.bindAsEventListener(this)
						});
					} else {
						if (this.options.hasItems)
							this.loadAdvancedView();
					}
				}.bind(this)
			});
		} else {
			if (this.options.hasItems)
				this.loadAdvancedView();
		}

		this.options.onUpdateBasket = function() {
			this.loadAdvancedView();
		}
	},
	loadAdvancedView: function(){
		if ($('expanded_basket')) {
			var advancedView = $('expanded_basket');
			advancedView.removeClassName('displayNone');
			advancedView.hide();

			this.options.element.select('.advanced-view-link').each( function(e) {
				e.select('a').invoke('observe', 'click', function(event){
					Event.stop(event);
					new Effect.toggle(advancedView, 'slide');
					/**
					 * The following added by KM 13/01/09 in order to counteract IE6 'SELECT' bug.
					 * This bug means that select elements show in front of everything else
					 * (including expanded view mini basket). This adds an iframe underneath
					 * expanded view which hides select when advanced view is opened.
					 */
					if (!advancedView.visible()) {
						elemPos = advancedView.cumulativeOffset();
						var style = 'position:absolute; top:31px; right:0px;';
						style += 'width:' + advancedView.getWidth() + 'px; height:' + (advancedView.getHeight() + 21) + 'px; top:0; display:block; filter:alpha(opacity=0); -moz-opacity: 0.80; opacity: 0.80;';

						var coverFrame = new Element('iframe', {
							'scrolling': 'no',
							'frameborder': 'no',
							'style':style,
							'id': 'coverFrameForExpandedView'
						});
						advancedView.insert({after:coverFrame});
					}
					else {
						setTimeout('removeFrameForIE()', 500);
					}
				});
			});
			if ($$('.customise-offer').length > 0) {
				$$('.customise-offer').each( function(e) {
					e.observe('mouseover', function(evt) { evt.element().up('.extra-item').down('p.re-select-warning').setStyle({'color': '#ff5500'}) });
				}.bind(this));
				$$('.customise-offer').each( function(e) {
					e.observe('mouseout', function(evt) { evt.element().up('.extra-item').down('p.re-select-warning').setStyle({'color': '#000000'}) });
				}.bind(this));
			}
		}
	},
	addToBasket: function(url) {
		this.submit(url);
	}
});

function removeFrameForIE() {
	if ($('coverFrameForExpandedView'))	$('coverFrameForExpandedView').remove();
}

// loop through all the compare checkboxes on the page and add an onlclick to each
// hide the compare button

// the your comparisons component is part of the catalogue page
// the compare component appears on only 2 pages and has its own js file

/* comparison functions
client side
*/

OrangeShop.comparisons = Class.create({
	initialize: function (element, options){
		this.element = $(element);
		this.options = Object.extend({
			// options go here
		}, options || {});
	},
	attachAddPhoneHandlers: function(aElements) {
		aElements.invoke('observe', 'click', function(evt){
			// Adding phone to comparisons shortlist
			if (evt.element().hasClassName('toggle_compare_off')) {
				if (this.count < 3) { // only add if less than 3 phones in shortlist
					evt.element().removeClassName('toggle_compare_off');
					evt.element().addClassName('toggle_compare_on');
					this.count += 1;
					this.setComparisons(evt.element().href + "&ajax=yes");
				}
				else {
					$('modal-message').removeClassName('displayNone');
					new openModalWithContent($('modal-message').innerHTML);
				}
			}
			// Removing phone from comparisons shortlist
			else if (evt.element().hasClassName('toggle_compare_on')) {
				evt.element().removeClassName('toggle_compare_on');
				evt.element().addClassName('toggle_compare_off');
				this.count -= 1;
				this.setComparisons(evt.element().href + "&pageless=true");
			}

			Event.stop(evt);
			return false;
		}.bindAsEventListener(this))
	},
	setComparisons: function(url){
		new Ajax.Updater(this.element, url, {
			onLoading: function () {
				this.element.update('<p class="ajax_loader"><span>LOADING</span><p>')
			},
			method: 'get',
			onComplete: function() {
				new Effect.Pulsate(this.element, {duration: 1.2})
				if (this.options.onUpdate)
					this.options.onUpdate;
			}.bindAsEventListener(this)
		});
	},
	loadIsFullModal: function(url){
		new ajaxModal(url)
	}
});

var OrangeVas = {}

OrangeVas.miniBasket = Class.create(OrangeShop.miniBasket, {
	attachAddItemHandlersToRadios: function(rElements){
		rElements.each(function(rElement) {
			if(rElement.hasClassName('requires-acceptance')){
				var cbxRequired = rElement.up('fieldset').down('input[type=checkbox]');
				rElement.observe('click', function(evt){
					if(rElement.checked && cbxRequired.checked) {
						this.serializeAndSend(evt);
						return false;
					} else {
						//alert("Orange Care is not added to the mini basket until this checkbox has been filled.");
					}
				}.bind(this));
				cbxRequired.observe('click', function(evt){
					if(rElement.checked) {
						if (cbxRequired.checked) {
							this.serializeAndSend(evt);
							return false;
						} else {
							var itemName = rElement.name;
							alert(itemName + " is not added to the mini basket until this checkbox has been filled.");
							// check the last radio button in the Orange Care group, which we assume is the 'no thanks' option
							var noButton = rElement.up('form').getInputs('radio', itemName).last();
							noButton.click();
							noButton.checked = true;
							this.serializeAndSend(evt);
							return false;
						}
				  }
				}.bind(this));
			} else {
				rElement.observe('click', function(evt){
					this.serializeAndSend(evt);
					return false;
				}.bind(this))
			}
		}.bind(this));
	},
	attachHandlersToCheckoutLinks: function(checkoutLinks,optionsContainer){
		var optContainers = $$(optionsContainer);
		var checkoutLinks = $$(checkoutLinks);
		checkoutLinks.each(function(checkoutLink) {
			checkoutLink.observe('click', function(evt){
				var notFilledCount = 0;

				Event.stop(evt);
				optContainers.each(function(optContainer) {
					var requiredContainer = optContainer.select('input.requires-acceptance');
					requiredContainer.each( function(f) {
						var cbxRequired = f.up('fieldset').down('input[type=checkbox]',0);
						if(f.checked && !cbxRequired.checked) {
							// Item has been picked but related terms not agreed to.
							notFilledCount++;
							var itemName = f.name;
							alert(itemName + " is not added to the mini basket until this checkbox has been filled.");
							return false;
						}
					});
				});
				if (notFilledCount == 0) { location.href = checkoutLink.href + '?referer=vasList.jsp'; }
			})
		})
	}
});

var OrangeAirtime = {}
OrangeAirtime.miniBasket = Class.create(OrangeShop.miniBasket, {
	attachAddItemHandlersToRadios: function(rElements){
		rElements.each(function(rElement) {
				rElement.observe('click', function(evt){
					this.serializeAndSend(evt);
					return false;
				}.bind(this))
		}.bind(this));
	}
});



var OrangePackage = {}
OrangePackage.formHandler = Class.create(OrangeShop.formHandler, {
	initialize: function($super, element, rElements, options) {
    	$super(options);
    	this.options.element = $(element);
    	this.rElements = rElements;
  	},
	attachAddItemHandlersToPhone: function(){
		this.rElements.invoke('hide');
		this.rElements.each(function(e) {
			if ((!e.up('label').hasClassName('selected'))) { this.updateStyle(e, 'hide'); }

			e.up('label').down('img').observe('mouseover', function(evt) {
				evt.element().up('label').addClassName('mouseover');
				this.updateStyle(evt.element(), 'show');
			}.bind(this));

			e.up('label').down('img').observe('mouseout', function(evt) {
			    var elem = evt.element();
				if (elem.up('label').hasClassName('mouseover')) { elem.up('label').removeClassName('mouseover'); }
				if (!(elem.up('label').hasClassName('selected'))) { this.updateStyle(elem, 'hide'); }
			}.bind(this));

			/** Set up listener on whole phone element - fake click on radio button */
			e.up('div.phone-option').observe('click', function(evt3) {
				evt3.stop();
				var elem = evt3.element();
				elem.up('div').down('input').checked = 'checked';
				elem.up('div').down('input').click();
			}.bind(this));

			/* Set up listener on radio button */
			e.observe('click', function(evt2) {
				this.submitUpdate(evt2);
			}.bind(this));

		}.bind(this));
	},
	submitUpdate: function(evt) {
		var elem = evt.element();

		/* Image tag within label was causing duplicate click event - this check to remove dupes */
		if (elem.tagName != 'IMG') {
			$$('label.selected').each(function(f) {
				f.removeClassName('selected');
				this.updateStyle(f.down(), 'hide');
			}.bind(this));

			elem.up('div').down('label').addClassName('selected');

			this.updateStyle(elem, 'show');
			
			this.serializeAndSend(evt);
			
		}
	},
	updateStyle: function(phoneItem, toggle) {
		if (phoneItem != $$('label.selected img')[0]) {
			if (toggle == 'hide' ) {
				phoneItem.up('label').down('span').setStyle({display:'block', top:'0px', position:'relative'});
				phoneItem.up('label').down('span').style.visibility = 'hidden';
				phoneItem.up('label').down('img').setStyle({/* position: 'relative', top:'20px', */ width:'45px', height:'75px',top:'0px', position:'relative'});
				if ($$('label.selected img')[0]) {
					$$('label.selected img')[0].setStyle({
						width: '57px',
						height: '92px',
						top: '-10px',
						position: 'relative'
					})
					$$('label.selected span')[0].setStyle({ display:'block'});
				};
				
			} else if (toggle == 'show') {
				phoneItem.up('label').down('span').setStyle({display:'block', top:'-10px', position:'relative'});
				phoneItem.up('label').down('span').style.visibility = 'visible';
				phoneItem.up('label').down('img').setStyle({/* position: 'static', top:'0px', */ width:'57px', height:'92px',top:'-10px', position:'relative'});
				if ($$('label.selected img')[0]) {
					$$('label.selected img')[0].setStyle({
						width: '45px',
						height: '75px',
						top: '0px',
						position: 'relative'
					})
					$$('label.selected span')[0].setStyle({ display:'none'});
				};
			}

		}
	}
});
