var quicklook = Class.create({
	initialize: function (url, options){
		this.url = url;
		this.options = Object.extend({
			// options go here
		}, options || {});

	},
	attachEventHandlers: function(elements){
		elements.each(function(el) {
			el.observe('click', function(event){
				Event.stop(event);
				this.openModal(el);
				return false;
			}.bind(this));
		}.bind(this))
	},
	openModal: function (link) {
		var urlParts = link.href.split('?');
		quickview = (urlParts.length > 0) ? this.url + "?" + urlParts.last() : this.url;
		new ajaxModal(quickview);
	}
});


// ---------------------------------------------------
// START: Filter/phone search

var filter = Class.create({
	initialize: function (form, resulltId, options){
		this.formElement = $(form);
		var hidden = $(Builder.node('input', { type: 'hidden', name: 'ajax', value: 'yes' }));
		this.formElement.appendChild(hidden);
		this.results = $(resulltId);
		this.options = Object.extend({
			afterFilter: Prototype.emptyFunction,
			radioToLinks: false
		}, options || {});
		this.formElement.getInputs('submit').invoke('remove')
		this.formElement.getInputs('checkbox').invoke('observe', 'click', function(){ this.doFilter()}.bind(this))
		if (!this.options.radioToLinks) {
			this.formElement.getInputs('radio').invoke('observe', 'click', function(){ this.doFilter()}.bind(this))
		}
		this.formElement.select('select').invoke('observe', 'change', function(){ this.doFilter()}.bind(this))

		this.connections = 0; // Counts the number of connections to the server at once. Reset after the onComplete call.
		this.minimumWaitTimeBetweenCalls = 0; //Change this to make user 'wait' to make additional connections WARNING - there is no information given to user that this is happening.
	},
	doFilter: function(){
		if (this.connections == 0) {
			this.connections++;
			new Ajax.Updater(this.results, this.formElement.action, {
				evalScripts: true,
				onLoading: function () {
					if (this.options.radioToLinks) {
						this.formElement.getInputs('radio').invoke('disable');
					}
					/* var containerHeight = this.results.getHeight();
					this.results.update('<div id="ajaxLoader" class="ajax_loader"><span>LOADING</span></div>');
					$('ajaxLoader').setStyle({
						height: containerHeight + "px"
					});*/
				}.bind(this),
				method: 'get',
				parameters: this.formElement.serialize(true),
				onComplete: function(){
					setTimeout(this.reduceConnections.bind(this), this.minimumWaitTimeBetweenCalls);
					this.notify('afterFilter')
				}.bindAsEventListener(this)
			});
	//		new Effect.Pulsate(this.results, {duration: 1.2});
		}
	},
	reduceConnections: function() {
		this.connections--;
		if (this.options.radioToLinks) { this.formElement.getInputs('radio').each ( function(e) { if (!e.up('label').hasClassName('disabled')) e.enable(); }); }
	},
	notify: function(event_name){
		try{
			if(this.options[event_name])
				return [this.options[event_name].apply(this.options[event_name],$A(arguments).slice(1))];
		}catch(e){
			if(e != $break)
				throw e;
			else
				return false;
		}
	}
});// END: Filter/phone search

var planFilter = Class.create(filter, {
	initialize: function ($super, form, resulltId, options){
		$super(form, resulltId, options);
		this.options.radioToLinks = true;
		this.radioElements = this.formElement.getInputs('radio');

		//this.setupRadiosToLookLikeLinks();
		//this.setupHoverObservers();
		this.adjustRadiosToMimicSelection();

		this.radioElements.each(function(j) {
			// IE won't trigger clicks on the label if the radio buttons are hidden - this triggers them.
			if (Prototype.Browser.IE) { j.up('label').observe('click', function(){ this.down('input[type=radio]').click(); }); }
		}.bind(this));
		this.radioElements.invoke('observe', 'click', function(evt){ this.checkWhetherSelectionCancelled(evt)}.bind(this))

		// If there is a reset form in the page separate to filter
		if ($(form + '-reset')) {
			this.formReset = $(form + '-reset');
			$(form + '-reset').down('input[type=image]').observe('click', function(evt) {
				evt.stop();
				this.resetFormAndSend();
			}.bind(this));
		}
	},
	setupRadiosToLookLikeLinks: function() {
		// Makes radio buttons mimic links, hide radio button and apply class to label and span in label to change label style.
		// For js version, 'any' option is hidden.
		this.radioElements.each(function(e) {
			if ($(e).id == ($(e).name + '_any')) { e.up('label').hide(); }
			else { e.hide(); }
		}.bind(this));
	},
	setupHoverObservers: function() {
		this.radioElements.each( function(i) {
			var label = i.up('label');
			label.observe('mouseover', function(evt) { label.addClassName('hover'); }.bind(this));
			label.observe('mouseout', function(evt) {label.removeClassName('hover');}.bind(this));

			var span = label.down('span');
			span.observe('mouseover', function(evt) { span.up('label').addClassName('hover'); }.bind(this));
			span.observe('mouseout', function(evt) {span.up('label').removeClassName('hover');}.bind(this));
		}.bind(this));
	},
	adjustSingleRadioToMimicSelection: function(f) {
		// Manages the selected or de-selection of 'link' radio buttons.
		if(f.checked) {	f.up('label').addClassName('selected');	}
		else { f.up('label').removeClassName('selected'); }
	},
	adjustRadiosToMimicSelection: function() {
		this.radioElements.each(function(f) { this.adjustSingleRadioToMimicSelection(f); }.bind(this));
	},
	checkWhetherSelectionCancelled: function(evt) {
		// Go up to label first, in case its span click instead of input
		var clickName = evt.element().up('label').down('input', 0).name;
		if($(clickName + '_any') && !($(clickName + '_any').up('label').hasClassName('selected'))
				&& ($(evt.element()).up('label').hasClassName('selected'))) {
			$(clickName + '_any').click();
		}
		this.adjustRadiosToMimicSelection();
		this.doFilter();
	},
	updateRadioStatus: function(statusOb) {
		// Set all elements to enabled.
		this.radioElements.each( function(g) {
			$(g).enable();
			$(g).up('label').removeClassName('disabled');
		}.bind(this));

		// Change any that should now be disabled.
		var toDisable = statusOb.disabled;
		if (toDisable.length > 0) {
			toDisable.each( function(e) {
				if ($(e)) {
					$(e).disable();
					$(e).up('label').addClassName('disabled');
				}
			}.bind(this));
		}
		this.checkFormResetButton();
	},
	checkFormResetButton: function() {
		if (this.formReset) {
			var numSelectedOptions = 0;
			var radios = new Array();
			this.formElement.getInputs('radio').each(function(g){ radios.push(g.name); });
			radios.uniq().each(function(r) {
				var value = $FR(this.formElement, r);
				if (value != null && value != undefined && value != '_NOFILTER_') {
					numSelectedOptions++;
				}
			}.bind(this));
			if (numSelectedOptions == 0) {
				this.formReset.down('input[type=image]').hide();
			} else {
				this.formReset.down('input[type=image]').show();
			}
		}
	},
	resetFormAndSend: function() {
		this.radioElements.each( function(e) { e.checked = false; });
		// Select all the 'any' options
		this.formElement.select('fieldset').each(function(e){
			if ($(e.down('input[type=radio]').name + '_any')) {
				$(e.down('input[type=radio]').name + '_any').checked = 'selected';
			}
		});
		this.adjustRadiosToMimicSelection();
		this.doFilter();
	}

}); // END: Filter/plan search


/**
* Hides the price filter from all but the PAYG channel searches.
* @param paygRadio The radio button that filters by PAYG channel
* @param priceFilterContainer The element containing the price filter radios
* @param priceFilterAllRadio The default price filter radio that selects
* @param channelRadios All of the channel radios
*/
var priceFilter = Class.create({
	initialize: function (paygRadio, priceFilterContainer, priceFilterAllRadio, channelRadios){
		this.priceFilterEl =  $$(priceFilterContainer);

		// hide price filters if not PAYG channel
		try {
			if(!$$(paygRadio)[0].checked) {
				this.priceFilterEl.invoke('hide');
			}
		} catch(e) {
		}

		$$(channelRadios).invoke('observe', 'click', function(e){
			if (e.element().value === 'PAYGA') {
				this.priceFilterEl.invoke('show');
			} else {
	            // click 'any' price range radio button to reset price filters before hiding
				try {
					$$(priceFilterAllRadio)[0].click();
				} catch(e) {
				}
	            this.priceFilterEl.invoke('hide');
			}
		}.bind(this));
	}
});
