/** 
* @projectDescription T-Mobile UI Components
*
* @author	Ben Gazzard
* @version	0.1 
*/

(function($){

	/* Array addons */
	Array.implement({
		unique : function(a){
			var r = new Array();
			o:for(var i = 0, n = a.length; i < n; i++){
				for(var x = 0, y = r.length; x < y; x++){
					if(r[x]==a[i]) continue o;
				}
				r[r.length] = a[i];
			}
			return r;
		}
	});
	
	/* String addons */
	String.implement({
		toBool: function(){
			return (this == 'true') ? true : false;
		},
		toFloat: function(){
			return (parseFloat(this) == 'NaN') ? false : parseFloat(this);
		}
	});
	
	/* Element addons */
	Element.implement({
		fancyShow: function() {
			this.fade('in');
		},
		fancyHide: function() {
			this.fade('out');
			this.hide();			
		}
	});
	
	/**
	 * Base class for initializing Carousels on page
	 * @id Carousel
	 * @alias Carousel
	 * @param {object} Togglers (Control elements), Blocks (Elements to be controlled), cssactive (CSS class to be applied to block when toggle is clicked), tween (animation parameters)
	 * @return initialized carousel
	 */	
	this.Carousel = new Class({
		Implements: [Events, Options],
		options:{
			index: 0,
			togglers: 'element-class-name',
			blocks: 'element-class-name',
			cssactive:'active',
			tween: {
				duration : 2000,
				transition : 'quad:in:out'
			}
		},
		initialize: function(options){
			this.setOptions(options),
			this.index = this.options.index;
			this.togglers = $$(this.options.togglers);
			this.blocks = $$(this.options.blocks);
			
			this.blocks.each(function(ele, ind){
				ele.set('opacity',(this.index == ind) ? 1 : 0);
			}.bind(this));
			
			this.togglers.each(function(element, index){
				if(this.index == index) element.addClass(this.options.cssactive)
			}.bind(this));
			
			this.blocks.removeClass('hidden');
			this.blocks.set('tween', this.options.tween);
			
			window.addEvent('keydown', this._keyHandler.bind(this));
		},
		_clickHandler: function(event){
			event.stop();
			this.target = $(event.target).getParent(this.togglers[0].get('tag')) || $(event.target);
		},
		_keyHandler: function(e){
			switch (e.code) {
				case 37:
					this.index = (this.index == 0) ? (this.togglers.length - 1) : (this.index - 1);
					break;
				case 39:
					this.index = (this.index == this.togglers.length - 1) ? 0 : (this.index + 1);
					break;
			}		
			this._transitionHandler();
		},
		_transitionHandler: function(){
			//alert(this.blocks)
			this.blocks.each(function(ele, ind){
				ele.tween('opacity', (ind == this.index) ? 1 : 0);
			}.bind(this));
			
			this.togglers.each(function(ele, ind){
				if(ind == this.index){
					ele.addClass(this.options.cssactive);
				} else {
					ele.removeClass(this.options.cssactive);
				}
			}.bind(this));
		}	
	});
	
	this.Scroller = new Class({
		Extends: Slider,
		options: {/*
			onTick: $empty(intPosition),
			onComplete: $empty(strStep),*/
			onChange: function(step){
				if(this.options.mode == 'horizontal') this.scrollable.setStyle('left', '-'+step+'px')
				else this.scrollable.setStyle('top', '-'+step+'px')
			},
			onTick: function(position){
				if (this.options.snap) position = this.toPosition(this.step);
				this.knob.setStyle(this.property, position);
			},
			snap: false,
			offset: 0,
			range: false,
			wheel: false,
			steps: 100,
			mode: 'horizontal',
			container: '#scroll-content', /*class or id css selector*/
			scrollable: '#phones', /*class or id css selector*/
			uplink: '#lnk-up', /*class or id css selector*/
			downlink: '#lnk-down', /*class or id css selector*/
			track: '#track', /*class or id css selector*/
			items: 'div.handset' /*class or id css selector*/
		},
		initialize: function(parentSelector, options){
			this.setOptions(options)
			
			$$(parentSelector).each(function(item){
				if(item.isVisible()){
					this.knob = item.getElement(this.options.knob);
					
					this.element = item.getElement(this.options.track);
					this.element.setStyle('display','block');
					this.container = item.getElement(this.options.container);
					this.scrollable = item.getElement(this.options.scrollable);
					this.uplink = item.getElement(this.options.uplink) || false;
					this.downlink = item.getElement(this.options.downlink) || false;		
					this.items = this.scrollable.getElements(this.options.items);
					this.isHorizontal = (this.options.mode == 'horizontal');
					this.scrollable.setStyle((this.isHorizontal) ? 'width' : 'height', this.items[(this.isHorizontal) ? 'getWidth' : 'getHeight']().sum())
					this.initKnob();
					this.parent(this.element, this.knob, options);
					this.steps = (this.isHorizontal ? (this.container.getScrollSize().x - this.container.getSize().x) : (this.container.getScrollSize().y - this.container.getSize().y));
					this.element.setStyle('display', (this.steps > 0) ? 'block' : 'none');
					this.clicked = 0;
					this.drag.addEvent('complete', function(element){
						this.clicked = Math.round(this.toPosition(this.step))
					}.bind(this));
					if(this.uplink){
						this.uplink.setStyle('display', (this.steps > 0) ? 'block' : 'none'); 
						this.uplink.addEvent('click', function(event){
							event.stop();
							if(this.clicked >= 0) { this.clicked -= 20; } 
							else { this.clicked = 0; }

							var dir = this.range < 0 ? -1 : 1;
							var position = this.clicked
							position = position.limit(-this.options.offset, this.full -this.options.offset);
								
							this.step = Math.round(this.min + dir * this.toStep(position));
							this.checkStep();
							this.fireEvent('tick', position);
							this.end();
					
						}.bind(this));	
					}
					
					if(this.downlink){
						this.downlink.setStyle('display', (this.steps > 0) ? 'block' : 'none'); 
						this.downlink.addEvent('click', function(event){
							event.stop();									 
							if(this.clicked <= this.full) {	this.clicked += 20;	} 
							else { this.clicked = this.full; }
					
							var dir = this.range < 0 ? -1 : 1;
							var position = this.clicked
							position = position.limit(-this.options.offset, this.full -this.options.offset);
							
							this.step = Math.round(this.min + dir * this.toStep(position));
							this.checkStep();
							this.fireEvent('tick', position);
							this.end();

						}.bind(this));
					}
				}

			}.bind(this))
		},
		initKnob: function(){
			var ch = this.container.getScrollSize()[(this.isHorizontal) ? 'x' : 'y'];
			var mh = this.container.getSize()[(this.isHorizontal) ? 'x' : 'y'];
			var th = this.container.getSize()[(this.isHorizontal) ? 'x' : 'y'];
			
			this.knobsize = Math.floor((th * mh) / ch);
			this.knob.setStyle((this.isHorizontal) ? 'width' : 'height', this.knobsize - 4);
			
			this.knob.setStyles({
				'cursor':'pointer',
				'opacity': 0.6
			});
			
			this.knob.set('tween',{
				duration:'short',
				transition:'quad:in:out'
			});
			
			this.knob.addEvents({
				'mouseover':function(){
					this.knob.tween('opacity',1);
				}.bind(this),
				'mouseout': function(){
					this.knob.tween('opacity',0.6);
				}.bind(this)
			});
		}
	});


	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * Initializes carousel 
	 * @id SimpleGallery
	 * @alias SimpleGallery
	 * @inherits Carousel
	 * @param {object} Togglers (Control elements), Blocks (Elements to be controlled), cssactive (CSS class to be applied to block when toggle is clicked), tween (animation parameters)
	 * @return initialized carousel
	 */
	this.SimpleGallery = new Class({
		Extends: this.Carousel,
		options: {
			index: 0,
			togglers: 'element-class-name',
			blocks: 'element-class-name',
			cssactive: 'active',
			tween: {
				duration : 2000,
				transition : 'quad:in:out'
			}
		},
		initialize: function(options){
			this.parent(options);
			this.togglers.addEvent('click', this._clickHandler.bind(this));
		},
		_clickHandler: function(event){
			this.parent(event);
			this.index = this.togglers.indexOf(this.target);
			this._transitionHandler();
		}
		
	});
	
	this.xmasGallery = new Class({
		Extends: this.Carousel,
		options: {
			index: 0,
			parentDiv : 'element-class-name',
			togglers: 'element-class-name',
			blocks: 'element-class-name',
			leftClick : 'prev',
			rightClick:'next',			
			cssactive: 'active',
			tween: {
				duration : 2000,
				transition : 'quad:in:out'
			}
		},
		initialize: function(options){
			this.parent(options);
			$$(options.leftClick).addClass('disabled');
			$$(options.rightClick).removeClass('disabled');
			$$(options.leftClick).addEvent('click', this._leftClickHandler.bind(this));
			$$(options.rightClick).addEvent('click', this._rightClickHandler.bind(this));
			this.progressHandler(this.options.parentDiv);
		},
		_leftClickHandler: function(event){
			event.stop();
			var element = event.target
			element.removeClass('disabled');
			$$(this.options.rightClick).removeClass('disabled');
			(this.index-1 >= 0 )? this.index-- : this.disabledHandler(element);
			if(this.index == 0) element.addClass('disabled');
			this._transitionHandler();
			this.progressHandler();
		},
		_rightClickHandler: function(event){
			event.stop();
			var element = event.target;
			element.removeClass('disabled');
			$$(this.options.leftClick).removeClass('disabled');
			(this.index < ($$(this.blocks).length-1) )? this.index++ : this.disabledHandler(element);
			if(this.index == ($$(this.blocks).length-1)) element.addClass('disabled');
			this._transitionHandler();
			this.progressHandler();
		},
		disabledHandler : function(element){
			element.addClass('disabled'); 
			return this.index;
		},
		progressHandler : function(carouselOverlay){
			var progressDiv = $('progress');
			var currentSlide = this.index + 1;
			var slidesTotal = $$(this.blocks).length;
			var progress = document.createTextNode(currentSlide + ' of ' + slidesTotal);
			var carousel = (carouselOverlay) ? carouselOverlay : this.options.parentDiv;
					
			if(progressDiv && progressDiv.hasChildNodes()){
				while (progressDiv.childNodes.length >= 1){
        			progressDiv.removeChild(progressDiv.firstChild);       
   				} 
			}
			
			progressDiv.appendChild(progress);
			$(carousel).appendChild(progressDiv);
		}
	});	
	/**
	 * Initializes carousel 
	 * @id LandingGallery
	 * @alias LandingGallery
	 * @inherits Carousel
	 * @param {object} Togglers (Control elements), Blocks (Elements to be controlled), links (additional elements to ), cssactive (CSS class to be applied to block when toggle is clicked), tween (animation parameters)
	 * @return initialized carousel
	 */	
	this.LandingGallery = new Class({
		Extends: this.Carousel,
		options: {
			index: 0,
			togglers: 'element-class-name',
			blocks: 'element-class-name',
			links: 'element-class-name',
			directionbtn: '.direction-btn',
			cssactive: 'active',
			tween: {
				duration : 2000,
				transition : 'quad:in:out'
			},
			transport:{
				autoplay:true,
				duration: 4500,
				linkid:'transport',
				cssplay:'play',
				csspause:'pause'
			}			
		},
		initialize: function(options){
			this.parent(options);
			this.links = $$(this.options.links);
			this.links.set('tween', this.options.tween);
			
			this.directionbtn = $$(this.options.directionbtn);

			this.links.each(function(ele, ind){
				ele.setStyle('opacity', (ind == this.index) ? 1 : 0);
			}.bind(this));
			
			this.prevbtn = this.directionbtn.filter(function(item){	return item.get('rel') == 'prev';})
			this.nextbtn = this.directionbtn.filter(function(item){	return item.get('rel') == 'next';})
			this.prevbtn.addClass('disabled');
			
			this.togglers.addEvent('click', this._clickHandler.bind(this));
			this.directionbtn.addEvent('click', this._clickHandler.bind(this));
			
			if(this.options.transport) {
				this.transportlink = $(this.options.transport.linkid);
				if(this.transportlink){
					this.transportlink.addEvent('click', this._transportHandler.bind(this));
					if(this.options.transport.autoplay){
						this.transportlink.addClass(this.options.transport.csspause);
						this.periodical = this._transport.periodical(this.options.transport.duration, this);
					} else {
						this.transportlink.addClass(this.options.transport.cssplay);
						this.periodical = '';
					}
				}
			}
		},
		
		_clickHandler: function(event){
			this.parent(event);
			if(this.options.transport){
				this.transportlink.addClass(this.options.transport.cssplay);
				this.transportlink.removeClass(this.options.transport.csspause);
				clearInterval(this.periodical);
			}

			var targetel = event.target.getParent(this.options.directionbtn) || event.target;
			var direction = targetel.get('rel');
			
			if (direction === 'next'){	
				if (this.blocks.length-1 !== this.index) {
					this.index++;
					if(this.index+1 == this.blocks.length) {
						targetel.addClass('disabled');
						this.prevbtn.removeClass('disabled');
					} else {
						this.directionbtn.removeClass('disabled');
					}
				} else {
					targetel.addClass('disabled');
				}
			} else if (direction === 'prev'){
				if(this.blocks.length !== this.index+this.blocks.length ) {
					this.index--;
					if(this.index == 0) {
						targetel.addClass('disabled');
						this.nextbtn.removeClass('disabled');
					} else {
						this.directionbtn.removeClass('disabled');
					}
				} else {
					targetel.addClass('disabled');
				}
			} else {
				this.index = this.togglers.indexOf(this.target);
							
				if(this.index+1 == this.blocks.length) {
					this.nextbtn.addClass('disabled');
					this.prevbtn.removeClass('disabled');
				} else if(this.index == 0){
					this.prevbtn.addClass('disabled');
					this.nextbtn.removeClass('disabled');
				} else {
					this.directionbtn.removeClass('disabled');
				}
			}
			
			this._transitionHandler();
		},
		_transitionHandler: function(){
			this.parent();
			this.links.each(function(ele, ind){
				ele.tween('opacity', (ind == this.index) ? 1 : 0);
			}.bind(this));
		},
		_transportHandler: function(event){
			event.stop();
			if(event.target.hasClass(this.options.transport.cssplay)){
				event.target.removeClass(this.options.transport.cssplay);
				event.target.addClass(this.options.transport.csspause);
				this._transport();
				this.periodical = this._transport.periodical(this.options.transport.duration, this);
			} else{
				event.target.addClass(this.options.transport.cssplay);
				event.target.removeClass(this.options.transport.csspause);
				clearInterval(this.periodical);
			}
		},
		_transport: function(){
			this.index += 1;
			if(this.index > (this.togglers.length-1)){
				this.index = 0;
			}
			this._transitionHandler();
		}
	});
	/* End Carousel plugins */	
	
	/**
	 * Class for initializing expandable areas on page 
	 * @id Expandables
	 * @alias Expandables
	 * @param {object} Togglers (Control elements), Blocks (Elements to be controlled), cssactiveblock (CSS class to be applied to block when toggle is clicked), cssactivetogger (CSS class to be applied to toggle when class is initialized)
	 * @return 
	 */
	this.Expandables = new Class({
		Implements: [Events, Options],
		options:{
			index: 0,
			togglers: 'element-class-name',
			blocks: 'element-class-name',
			cssactiveblock: 'active-block',
			cssactivetoggle: 'active-toggle',
			morph: {
				duration : 2000,
				transition : 'quad:in:out'
			}
		},
		initialize: function(options){
			this.setOptions(options);
			this.index = this.options.index;
			this.togglers = $$(this.options.togglers);
			this.blocks = $$(this.options.blocks);
			
			this.blocks.each(function(element, index){
				//element.setStyle('position','absolute');
				element.store('height', element.getSize().y);
				element.setStyle('position','relative');
			}.bind(this));
			
			this.blocks.each(function(block, index){
				if(!block.hasClass('ignore')){
					this.togglers[index].store('expanded', false);
					this.togglers[index].set('title','Expand this panel');
					block.setStyles({
				'height': 0,
				'overflow':'hidden'
			});
				} else {
					this.togglers[index].addClass(this.options.cssactivetoggle)
					this.togglers[index].store('expanded', true);
					this.togglers[index].set('title','Collapse this panel');
					block.addClass(this.options.cssactiveblock)
					block.setStyles({
						'overflow':'hidden'
					});
				}
			}.bind(this));
			
			this.blocks.set('morph', this.options.morph);
			this.togglers.addEvent('click', this._clickHandler.bind(this));
		},
		_clickHandler: function(event){
			event.stop();
						
			this.target = $(event.target).getParent(this.options.togglers) || $(event.target);
			this.index = this.togglers.indexOf(this.target);
			
			this.togglers.each(function(element, index){
				if (index == this.index) {
					if(element.hasClass(this.options.cssactivetoggle)){
						element.removeClass(this.options.cssactivetoggle);
						element.store('expanded', false);
						element.set('title','Expand this panel');
					} else {
						element.addClass(this.options.cssactivetoggle);
						element.store('expanded', true);
						element.set('title','Collapse this panel');
					}
				}
			}.bind(this));
			
			this.blocks.each(function(element, index){
				if(index == this.index){
					
					if(element.hasClass(this.options.cssactiveblock)){
						element.removeClass(this.options.cssactiveblock);
					} else {
						element.addClass(this.options.cssactiveblock);
					}
					
					element.morph({
						'height': (this.togglers[this.index].hasClass(this.options.cssactivetoggle)) ? element.retrieve('height') : 0
					});
				} 
			}.bind(this));
			
			this.fireEvent('onClick',[event])
		}
	});
	
	/**
	 * Base class for toggling classes on page 
	 * @id ShowHide
	 * @alias ShowHide
	 * @param {object} Togglers (Control elements), Blocks (Elements to be controlled), csson (CSS class to be applied to block when toggle is clicked), cssoff (CSS class to be applied to block when class is initialized)
	 * @return 
	 */
	this.ShowHide = new Class({
		Implements : [Events, Options],
		options: {
			toggle: false,
			togglers: '.element-class-name',
			blocks: '.element-class-name',
			csson: 'onstyle',
			cssoff: 'offstyle'
		},
		initialize: function(options){
			this.setOptions(options);
			this.togglers = $$(this.options.togglers);
			this.blocks = $$(this.options.blocks);
			this.blocks.addClass(this.options.cssoff);
		},
		_clickHandler: function(event){
			event.stop();
			this.target = $(event.target).getParent(this.togglers[0].get('tag')) || $(event.target);
		}
	});
	
	this.FilterQuickView = new Class({
		Extends: this.ShowHide,
		options:{
			togglers: '.element-class-name',
			blocks: '.element-class-name',
			csson: 'onstyle',
			cssoff: 'offstyle'
		},
		initialize: function(options){
			this.parent(options);
			this.togglers.addEvents({
				'mouseover': this._mouseoverHandler.bind(this),
				'mouseout': this._mouseoutHandler.bind(this)
			});
		},
		_mouseoverHandler: function(event){
			event.stop();
			var target = $(event.target).getParent(this.togglers[0].get('tag')+this.options.togglers) || $(event.target);
			this.index = this.togglers.indexOf(target);
			this.blocks[this.index].addClass(this.options.csson);
		},
		_mouseoutHandler: function(event){
			event.stop();
			var target = $(event.target).getParent(this.togglers[0].get('tag')+this.options.togglers) || $(event.target);
			this.index = this.togglers.indexOf(target);
			this.blocks[this.index].removeClass(this.options.csson);		
		}
	})

	/**
	 * Logic and events for dealing with tab based navigation 
	 * @id Tabs
	 * @alias Tabs
	 * @inherits ShowHide
	 * @param {object} Togglers (Control elements), Blocks (Elements to be controlled), csson (CSS class to be applied to block when toggle is clicked), cssoff (CSS class to be applied to block when class is initialized), cssactive (CSS class applied to toggler if active), index (element to be shown fist)
	 * @return Initialized tab based navigation
	 */
	this.Tabs = new Class({
		Extends: this.ShowHide,
		options: {
			toggle: false,
			togglers: '.element-class-name',
			blocks: '.element-class-name',
			csson: 'onstyle',
			cssoff: 'offstyle',
			cssactive: 'activestyle',
			index : 0,	
			regex : /#tab-/		
		},
		initialize: function(options){
			this.parent(options);
			this.index = this.options.index;

			/*if(location.hash && location.hash != '#'){
				this.hash = location.hash.replace(this.options.regex, '');
				this.index = (this.hash > (this.togglers.length - 1)) ? this.togglers.length - 1 : this.hash;
			}*/

			this._setBlock();
			
			this.togglers.each(function(element, index){
				if(!element.hasClass('ignore')) element.addEvent('click', this._clickHandler.bind(this));					
			}.bind(this));
			

		},
		_clickHandler: function(event){
			event.stop();
			this.parent(event);
			this.index = this.togglers.indexOf(this.target);
			this._setBlock();
		},
		_setBlock: function(){
			this.blocks.each(function(element, index){
				if(index == this.index){
					this.togglers[this.index].getParent('li').addClass(this.options.cssactive);
					element.addClass(this.options.csson)
				} else {
					if(this.togglers[index]){		
					this.togglers[index].getParent('li').removeClass(this.options.cssactive);
					}
					element.removeClass(this.options.csson)
				}
			}.bind(this));
		}
	});
	
	this.Tabs.implement({
		setBlock: function(index){
			this.index = (index > (this.togglers.length - 1)) ? this.togglers.length - 1 : index;
			this._setBlock();
		},
		getBlock: function(){
			return this.index;
		}
	})
	
	/**
	 * Logic and events for dealing a set of togglers on a page
	 * @id Togglers
	 * @alias Togglers
	 * @inherits ShowHide
	 * @param {object} Togglers (Control elements), Blocks (Elements to be controlled), csson (CSS class to be applied to block when toggle is clicked), cssoff (CSS class to be applied to block when class is initialized), cssactive (CSS class applied to toggler if active)
	 * @return Initialized togglers
	 */
	this.Togglers = new Class({
		Extends: this.ShowHide,
		options: {
			toggle: true,
			togglers: '.element-class-name',
			blocks: '.element-class-name',
			csson: 'onstyle',
			cssoff: 'offstyle',
			cssactive: 'activestyle'			
		},
		initialize: function(options){
			this.parent(options);
			this.togglers.addEvent('click', this._clickHandler.bind(this));
		},
		_clickHandler: function(event){
			event.stop();
			this.parent(event);
			this.blocks.each(function(element, index){
				if(this.togglers.indexOf(this.target) == index){
					if(element.hasClass(this.options.csson)){
						this.target.removeClass(this.options.cssactive);
						element.removeClass(this.options.csson);	
					} else {
						element.addClass(this.options.csson);
						this.target.addClass(this.options.cssactive);
					}
				}
			}.bind(this));
		}
	});
	
	this.Togglers.implement({
		setBlock: function(index){
			if(!this.blocks[index].hasClass(this.options.csson)){
				this.blocks[index].addClass(this.options.csson);
			}
		},
		getBlocks: function(){
			var opened = [];
			this.blocks.each(function(element, index){
				if(element.hasClass(this.options.csson)){
					opened.push(element)
				}
			}.bind(this));
			return $$(opened);
		}
	});
		
	/**
	 * Logic and events for dealing a set of tips on a page
	 * @id TipsBase
	 * @alias TipsBase
	 * @param {object} elements - elements to target, classname - class  name of tip
	 * @return Initialized tips
	 */
	this.TipsBase = new Class({
		Implements:[Events, Options],
		options:{
			elements: 'a.standard-tips',
			classname:'standard-tip',
			onClick: function(){}
		},
		initialize: function(options){
			this.setOptions(options);
			this.elements = $$(this.options.elements);
			this._genHTML();
			this.elements.addEvents({
				'mouseover': this._mouseoverHandler.bind(this),
				'mouseout': this._mouseoutHandler.bind(this),
				'click': this._clickHandler.bind(this)
			});
		},
		_genHTML: function(){
			this.title = new Element('div', {'class': 'title'});
			this.content = new Element('div', {'class': 'content'});
			this.tip = new Element('div', {'class' : this.options.classname}).adopt(
				new Element('div',{'class': 'tip-top'}).adopt(this.title, this.content), 
				new Element('div',{'class':'tip-bottom'})
			).inject(document.body);
			
			//ie6 select option stack bug, fix
			if (!window.XMLHttpRequest && (document.location.href).indexOf('mobile-tariffs') !== -1) {
				var width = this.tip.offsetWidth,
					height = this.tip.offsetHeight,
					left = this.tip.offsetLeft,
					top = this.tip.offsetTop;
				this.iframe = new Element('iframe', {'frameborder':'0','src':'#'});
					this.iframe.setStyles({'position': 'absolute', 'top': top, 'left': left, 'background-color':'transparent', 'width': width, 'height': height, 'z-index': '0'})
					this.iframe.inject(this.tip, 'top');
			}
			
			
			
		},
		_clickHandler: function(event){
			event.stop();
			this.fireEvent('click');
		},
		_mouseoverHandler: function(event){
			var target = $(event.target).getParent(this.elements[0].get('tag')) || $(event.target);
			
			this.tip.setStyle('display','block');
			var targetPos = target.getPosition();
			var targetSize = target.getSize();
			var tipSize = this.tip.getSize();
			
			this.tip.setStyles({
				top: targetPos.y - tipSize.y,
				left: Math.floor(targetPos.x - (tipSize.x / 2) + (targetSize.x / 2))
			});
			
			//ie6 select option stack bug, fix
			if (!window.XMLHttpRequest && (document.location.href).indexOf('mobile-tariffs') !== -1) {
				var width = this.tip.offsetWidth,
					height = this.tip.offsetHeight;
				
				this.iframe.setStyles({width: width, height: height-5});
			}
			
		},
		_mouseoutHandler: function(event){
			this.tip.setStyle('display','none');
		}
	});	

	/**
	 * Logic and events for dealing a set of tips on a page that runs off title and rel
	 * @id StaticTip
	 * @alias StaticTip
	 * @inherits TipsBase
	 * @param {object} elements - elements to target, classname - class  name of tip
	 * @return Initialized tips
	 */
	this.StaticTip = new Class({
		Extends: this.TipsBase,
		options:{
			elements: 'a.standard-tips',
			classname:'standard-tip'
		},
		initialize: function(options){
			this.parent(options);
			this.setOptions(options);
			this.elements.each(function(element, index){
				element.store('tiptitle', element.get('title'));
				element.store('tipcontent', element.get('rel'));
				element.set('rel','');
				element.set('title','');
			});
		},
		_mouseoverHandler: function(event){
			var target = $(event.target).getParent(this.elements[0].get('tag')) || $(event.target);
			this.title.set('html', target.retrieve('tiptitle'));
			this.content.set('html', target.retrieve('tipcontent'));
			this.parent(event);
		}
	});
	
	/**
	 * Logic and events for dealing a set of tips on a page that runs off title and associated content
	 * @id ExtendedTip
	 * @alias ExtendedTip
	 * @inherits TipsBase
	 * @param {object} elements - elements to target, tipcontent - div containing content for tip, classname - class  name of tip
	 * @return Initialized tips
	 */	
	this.ExtendedTip = new Class({
		Extends: this.TipsBase,
		options:{
			elements: 'a.extended-tips',
			tipcontent: 'div.tip-content',
			classname:'extended-tip'
		},
		initialize: function(options){
			this.parent(options);
			this.tipContent = $$(this.options.tipcontent);
		},
		_mouseoverHandler: function(event){
			var target = event.target.getParent(this.elements[0].get('tag')) || event.target;
			this.content.set('html', this.tipContent[this.elements.indexOf(event.target)].get('html'));
			this.parent(event);
		}
	});	
	
	
	
 	this.Overlay = new Class({
        Implements: [Events, Options],
        options: {
            tween: {
                duration: 100,
                transition: 'quad:in:out'
            },
            morph: {
                duration: 500,
                transition: 'quad:in:out'
            }
        },
        initialize: function(options){
			this.newtop = this.newleft = this.topposition = this.leftposition = this.imageheight = this.imagewidth = 0;
			this.currentIndex = 0;
            this.setOptions(options);
			this.visible = false;
			this._genOverlay();
            this._genHTML();
			window.addEvent('resize', this._resize.bind(this));
			
       	},
		_genOverlay: function(){
			this.overlay = new Element('div', {
                'id': 'overlay',
                'class': (Browser.Platform.mac && Browser.firefox) ? 'overlayMacFFBGHack' : 'overlayBG',
                'events': {
                    'click': this._removeOverlay.bind(this)
                },
				'styles': {
					'opacity': 0,
					'display':'none'
				},
				'tween': this.options.tween
            }).inject(document.body);
		},
		_genHTML: function(){
			this.lightbox = new Element('div',{
				'id': 'lightbox',
				'styles':{
					'opacity':0,
					'display':'none'
				},
				'tween': this.options.tween
			}).inject(document.body);
		},
		_setSize: function(){
			this.lightbox.setStyle('display','block');
			var lightboxsize = this.lightbox.getSize();
			var windowScroll = window.getScroll();
			var windowsize = window.getSize();
			var windowScrollSize = window.getScrollSize();
			
			this.topposition = (windowsize.y / 2) - (lightboxsize.y / 2)
			this.leftposition = (windowsize.x / 2) - (lightboxsize.x / 2)
			
			if(Browser.ie6){
				this.lightbox.setStyles({
					'left': this.leftposition,
					'top': (windowScroll.y) + (windowsize.y / 2) - (lightboxsize.y / 2)
				});
			} else {
				this.lightbox.setStyles({
					'top': this.topposition, 
					'left': this.leftposition
				});
			}
		},
        _initOverlay: function(){
			this.visible = true;
			var lightboxsize = this.lightbox.getSize();
			var windowScroll = window.getScroll();
			var windowsize = window.getSize();
			var windowScrollSize = window.getScrollSize();
						
			if(Browser.ie6){
				$$('body', 'html').setStyles({
					'overflow':'hidden',
					'width':'100%',
					'height':'100%'
				});

				this.lightbox.setStyles({
					'position': 'absolute',
					'top': (windowScroll.y) + (windowsize.y / 2) - (lightboxsize.y / 2)
				})
				this.overlay.setStyles({
					'position': 'absolute',
					'height': windowScrollSize.y,
					'width': windowScrollSize.x
				});
				$$('select').setStyle('visibility','hidden');
			}			
			
            this.overlay.setStyles({
				'opacity': 0.75,
				'display':'block'
			});
			this.lightbox.setStyles({
				'opacity': 1,
				'display':'block'
			});
        },
        _removeOverlay: function(){
			
			this.visible = false;
			
			if(Browser.ie6){
				$$('body', 'html').set('style','');
				$$('select', 'input').setStyle('visibility','visible')
			}	
	
			this.overlay.setStyles({
				'opacity': 0,
				'display':'none'
			});
			this.lightbox.setStyles({
				'opacity': 0,
				'display':'none'
			});
			
        },
		_resize: function(){
			this._setSize();
		}
    });
	
	this.ModalWindow = new Class({
		Extends: Overlay,
		options:{ width: 500, closeTop:false },
		initialize: function(options){
			this.parent(options);
			this.lightbox.set('id','modal-lightbox');
			this.overlay.set('id','modal-overlay');
			if(this.closeTop)this.overlay.removeEvents('click');
		},
		_initOverlay: function(){
			this.lbheader.set('html', this.target.get('title'))
			this.content.removeProperty('style');
			this.content.set('html', $(this.target.get('href').replace('#','')).get('html'));
			this._setSize();
			this.parent();
		},
		_genHTML: function(){
			this.parent();
			this.lightbox.setStyles({'width': this.options.width});
			this.content = new Element('div',{'id':'modal-lb-content'});		
			this.lbheader = new Element('div',{'id':'modal-lb-hdr-content'});
			if(this.options.closeTop){
				var that = this;
				this.closebtn = new Element('a',{
								'id':'modal-lb-close-btn',
								'events': {
									'click': function(event){
												event.stop();
												that._removeOverlay();
												
											}
								}											
							});	
							
							this.closebtnTxt = new Element('a', {
								'id':'modal-lb-close-btn-txt',
								'html':'Close',
								'href':'#',
								'events': {
									'click': function(event){
												event.stop();
												that._removeOverlay();
												
											}
								}								
							});
				}	
			
			this.lightbox.adopt(
				new Element('div',{'id':'modal-lb-hdr-left-bdr'}).adopt(
					new Element('div',{'id':'modal-lb-hdr-right-bdr'}).adopt(
						this.lbheader,
						this.closebtn,
						this.closebtnTxt
					)
				),
				new Element('div',{'id':'modal-lb-btm-bdr'}).adopt(this.content)
			).inject(document.body);
		},
		_removeOverlay: function(){
			this.parent();
			this.content.empty();
        },
		_onCancel: function(event){
			event.stop();
			this.modalOptions.onCancel();
			this._removeOverlay();

		},
		_onConfirm: function(event){
			event.stop();
			this.modalOptions.onConfirm();
			this._removeOverlay();				
		},
		Open: function(modalOptions){
			this.modalOptions = modalOptions

			
			this.lbheader.set('html', this.modalOptions.title)
			
			this.text = new Element('div', { 'styles':{'position':'relative'} });
			this.text.set('html', this.modalOptions.text);
			
			/*$$(this.closebtn, this.closebtnTxt).removeEvents('click');
			$$(this.closebtn, this.closebtnTxt).addEvent('click', this._onCancel.bind(this));*/
			if(this.modalOptions.confirm){
				this.confirmBtn = new Element('a', {
					'href': '#',
					'class':'rdbtn btn-magenta',
					'styles':{
						'float':'right'
					},
					'events': {
						'click': this._onConfirm.bind(this)
					}
				}).adopt(
					new Element('span', {'class':'btn-corner-br'}).adopt(
						new Element('span', {'class':'btn-corner-bl'}).adopt(
							new Element('span', {'class':'btn-corner-tr'}).adopt(
								new Element('span', {'class':'btn-corner-tl'}).adopt(
									new Element('span', {'class':'padding','html': this.modalOptions.confirm})
								)
							)
						)
					)
				);			
			}
			
			if(this.modalOptions.cancel){
				this.cancelBtn = new Element('a', {
					'href': '#',
					'class':'rdbtn btn-white-highlight',
					'styles':{
						'float':'right'
					},
					'events': {
						'click': this._onCancel.bind(this)
					}
				}).adopt(
					new Element('span', {'class':'btn-corner-br'}).adopt(
						new Element('span', {'class':'btn-corner-bl'}).adopt(
							new Element('span', {'class':'btn-corner-tr'}).adopt(
								new Element('span', {'class':'btn-corner-tl'}).adopt(
									new Element('span', {'class':'padding','html': this.modalOptions.cancel})
								)
							)
						)
					)
				);
			}
			
			this.clearer = new Element('div',{'class':'clear'});
			
			if(this.options.closeTop){
				this.content.adopt(this.text, this.clearer);			
			}else{
				this.content.adopt(this.text, this.confirmBtn, this.cancelBtn, this.clearer);				
				}


			
			this._setSize();
			
			this.visible = true;
			var lightboxsize = this.lightbox.getSize();
			var windowScroll = window.getScroll();
			var windowsize = window.getSize();
			var windowScrollSize = window.getScrollSize();
						
			if(Browser.ie6){
				$$('body', 'html').setStyles({
					'overflow':'hidden',
					'width':'100%',
					'height':'100%'
				});
				

				this.lightbox.setStyles({
					'position': 'absolute',
					'top': (windowScroll.y) + (windowsize.y / 2) - (lightboxsize.y / 2)
				})
				
				this.overlay.setStyles({
					'position': 'absolute',
					'height': windowScrollSize.y,
					'width': windowScrollSize.x
				});
				$$('select', 'input').setStyle('visibility','hidden');
			}			
			
			
            this.overlay.setStyles({'opacity': 0.75, 'display':'block'});
			this.lightbox.setStyle('opacity', 1);
			if(this.modalOptions.setFocus == 'Confirm'){
				this.confirmBtn.focus();
				}
			else if(this.modalOptions.cancel){
				this.cancelBtn.focus();
				}
			
			
		}
	});		
	
	
	this.HTMLbox = new Class({
		Extends: this.Overlay,
		options:{
			elements: 'a[rel="htmlbox"], a[rel="swiffbox"]',
			width: 500,
			funcOnComplete: null
		},
		initialize: function(options){
			
			this.parent(options);
			this.elements = $$(this.options.elements);	
			this.elements.addEvent('click', this._clickHandler.bind(this));
		},
		_clickHandler: function(event){
	
			event.stop();
			this.target = $(event.target).getParent(this.elements[0].get('tag')) || $(event.target);
			this.currentIndex = this.elements.indexOf(this.target); 
			this._initOverlay();		
			if(typeof this.options.funcOnComplete === 'function'){
				this.options.funcOnComplete();
			}
		},
		_initOverlay: function(){
			this.lbheader.set('html', this.target.get('title'))

			if(this.target.get('rel')=='swiffbox'){
				this.swiff = new Swiff(this.target.get('href'),{
					id: 'swiffbox',
					width: this.options.width - 40,
					height: this.options.height - 40,
					container: this.content
				});
			
				this.content.setStyles({
					'width':this.options.width - 40,
					'height': this.options.height - 40
				});
			
			} else {
				this.content.removeProperty('style');
				//there was a bug on ie when lighbox is fired from ajax success function
				//this.content.set('html', $(this.target.get('href').replace('#','')).get('html'));
				this.content.set('html', $(this.target.get('href').substring(this.target.get('href').indexOf('#')+1)).get('html'))
			}
			
			this._setSize();
			this.parent();
			this.fireEvent('open'); 
		},
		_genHTML: function(){
			this.parent();
			this.lightbox.setStyles({'width': this.options.width});
			this.content = new Element('div',{'id':'lb-content'});		
			this.lbheader = new Element('div',{'id':'lb-hdr-content'});
			this.closebtn = new Element('a',{
				'id':'lb-close-btn',
				'events':{
					'click': this._removeOverlay.bind(this)
				}
			});	
			
			this.closebtnTxt = new Element('a', {
				'id':'lb-close-btn-txt',
				'text':'Close',
				'href':'#',
				'events':{
					'click': this._removeOverlay.bind(this)
				}
			});
			
			this.lightbox.adopt(
				new Element('div',{'id':'lb-hdr-left-bdr'}).adopt(
					new Element('div',{'id':'lb-hdr-right-bdr'}).adopt(
						this.lbheader,
						this.closebtn,
						this.closebtnTxt
					)
				),
				new Element('div',{'id':'lb-btm-bdr'}).adopt(this.content)
			).inject(document.body);
		},
		_removeOverlay: function(e){
			e.stop();
			this.parent();
			if(this.swiff) this.swiff = null;
			
			this.content.set('html','');
        },
			OpenLighbox: function(elementId, title){

        this.lbheader.set('html', title)

        this.content.removeProperty('style');
				this.content.set('html', $(elementId).get('html'));
			if(this.content.getElement(this.options.closelink)) {
				this.content.getElements(this.options.closelink).addEvent('click', this._removeOverlay.bind(this)) 
			}

        this._setSize();
        this.visible = true;
        var lightboxsize = this.lightbox.getSize();
        var windowScroll = window.getScroll();
        var windowsize = window.getSize();
        var windowScrollSize = window.getScrollSize();

		

        if(Browser.ie && Browser.version < 6){
              $$('body', 'html').setStyles({
                     'overflow':'hidden',
                     'width':'100%',
                     'height':'100%'
              });
             this.lightbox.setStyles({
                     'position': 'absolute',
                     'top': (windowScroll.y) + (windowsize.y / 2) - (lightboxsize.y / 2)
              })
              this.overlay.setStyles({
                     'position': 'absolute',
                     'height': windowScrollSize.y,
					 'width':windowScrollSize.x
              });
				$$('select', 'input').setStyle('visibility','hidden');
				alert(windowScrollSize.x)
        }

        this.overlay.setStyle('opacity', 0.75);
		this.overlay.setStyle('display','block');
      	this.lightbox.setStyle('opacity', 1);

      }
	});	
	
	this.Lightbox = new Class({
		Extends: this.Overlay,
		options:{
			elements: 'a[rel="lightbox"]'
		},
		initialize: function(options){
			this.parent(options);
			this.elements = $$(this.options.elements);
			this.elements.addEvent('click', this._clickHandler.bind(this));
		},
		_genHTML: function(){
			this.parent();
			this.lightbox.setStyles({
				'background-color':'#FFF',
				'width': 200,
				'height': 200
			});
			this.content = new Element('div',{
				'id':'lb-content',
				'tween':this.options.morph
			});
			this.lightbox.set({
				'tween':$merge(this.options.tween,{
					onComplete: function(){
						if(this.lightbox.getStyle('opacity') == 1){
							this.lightbox.addClass('image-loading')
							this._loadImage();
						} else {
							this.content.empty();
						}
					}.bind(this)
				}),
				'morph':$merge(this.options.morph,{
					onComplete: function(){
						this.topposition = this.newtop;
						this.leftposition = this.newleft;
						this.content.tween('opacity', 1)
					}.bind(this)
				})
			});
			
			this.content.set('opacity',0)
			this.lightbox.adopt(this.content);
			this._setSize();
		},
		_initOverlay: function(){
			this.parent()
		},
		_removeOverlay:function(){
			this.parent();
			this.content.setStyles({
				'visibility':'hidden',
				'opacity':0
			})
			this.content.empty();
			
		}
	});
	
	/* Lightbox additional utils */
	this.Lightbox.implement({
		_loadImage : function(){
			var element = Asset.images([this.elements[this.currentIndex].get('href')], {
				onComplete: function(){
					this.lightbox.removeClass('image-loading')
					this.content.empty();
					this.content.adopt(element[0]);
					this.imageheight = element[0].get('height').toInt();
					this.imagewidth = element[0].get('width').toInt();
					this.newtop = (window.getSize().y / 2) - (this.imageheight / 2);
					this.newleft = (window.getSize().x / 2) - (this.imagewidth / 2);
					
					if(this.leftposition != this.newleft && this.topposition != this.newtop){
						this.lightbox.morph({
							'top':this.newtop - 15,
							'left':this.newleft - 15,
							'width':this.imagewidth + 30,
							'height':this.imageheight + 30
						})	
					} else {
						this.content.tween('opacity', 1);
					}
					this._setSize();
				}.bind(this)
			});			
		}
	})
	
	/* Lightbox Event handlers */
	this.Lightbox.implement({
		_clickHandler: function(event){
			event.stop();
			this.target = $(event.target).getParent(this.elements[0].get('tag')) || $(event.target);
			this.currentIndex = this.elements.indexOf(this.target)
			this._initOverlay();
		}
	})
	
	
	this.MakeClickable = new Class({
		Implements: [Events, Options],
		options: {
			elements : 'li.tab'
		},
		initialize: function(options){
			this.setOptions(options);
			this.elements = $$(this.options.elements);
			this.elements.setStyle('cursor','pointer');
			this.elements.addEvent('click', this._clickHandler.bind(this));
		},
		_clickHandler: function(event){
			event.stop();
			var target = $(event.target).getParent(this.options.elements) || $(event.target);
			var atag = target.getElement('a');
			window.location = atag.get('href');
		}
	});


	this.Timer = new Class({
		Implements:[Options],
		options:{
			timerContent : 'on-timer-content',
			finishedContent : 'off-finish-content',
			lowerContent: 'lower-content',
			container: 'timer',
			timeContainer: '#time',
			countDownTo : 'Thu Mar 25 2010 22:00:00 GMT+0000 (BST)',
			period: 500
		},
		initialize: function(options){
			this.setOptions(options);
			this.container = $(this.options.container);
			this.timerContent = $(this.options.timerContent);
			this.finishedContent = $(this.options.finishedContent);
			this.lowerContent = $(this.options.lowerContent);
			this.timeContainer = this.container.getElement(this.options.timeContainer);
			this._setDates();
		},
		_setDates: function(){
			this.now = new Date();
			this.dateTo = new Date();
			this.dateTo.parse(this.options.countDownTo);
			
			if(this.now.getHours() >= this.dateTo.getHours() && this.now.getMinutes() >= this.dateTo.getMinutes()){
				this.timerContent.setStyle('display', 'none');
				this.finishedContent.setStyle('display', 'block');	
				this.lowerContent.setStyle('display', 'none');
			} else {
				this.timer = this._timerStart.periodical(this.options.period, this);	
			}
		},
		_timerStart: function(){
			this.now = new Date();
			this.counter = new Date(this.dateTo - this.now);
			

			if((this.counter.getUTCHours() == 0 && this.counter.getUTCMinutes() == 0)){
				
				this.timerContent.setStyle('display','none');
				this.finishedContent.setStyle('display','block');
				this.lowerContent.setStyle('display','none');
				clearInterval(this.timer);
			} else {
				this.timeHour = (this.counter.getHours().toString().length < 2) ? '0' + this.counter.getHours() : this.counter.getHours();
				this.timeMins = (this.counter.getMinutes().toString().length < 2) ? '0' + this.counter.getMinutes() : this.counter.getMinutes();
				this.timeSecs = (this.counter.getSeconds().toString().length < 2) ? '0' + this.counter.getSeconds() : this.counter.getSeconds();
				this.timeHour += ':';
				this.timeMins += ':';
				this.timeSecs += '';
				this.timeContainer.set('html', this.timeHour + this.timeMins +  this.timeSecs);					
			}
		}
	});

	this.TimerExtended = new Class({
		Implements: Options,
		options:{
			to:'Mar 25 2010 10:0:00',
			length:'Mar 25 2010 22:00:00',
			contentPre: 'content-pre',
			contentDuring: 'content-during',
			contentAfter: 'content-after'
		},
		initialize: function(timer, options){
			this.setOptions(options);
			this.timer = $$(timer);
			this.contentPre = $(this.options.contentPre);
			this.contentDuring = $(this.options.contentDuring);
			this.contentAfter = $(this.options.contentAfter);
			
			this.to = new Date().parse(this.options.to)
			this.length = new Date().parse(this.options.length)
			
			this.to = this.to.getTime();
			this.length = this.length.getTime();
			this.now = new Date().getTime();
			
			if (this.now < this.to) {
				this.periodical = this.preOfferTimer.periodical(1000, this);
				if(this.contentPre) this.contentPre.setStyle('display','block');
				if(this.contentDuring) this.contentDuring.setStyle('display','none');
				if(this.contentAfter) this.contentAfter.setStyle('display','none');
			} else if(this.now > this.length && this.now > this.to){
				if(this.contentPre) this.contentPre.setStyle('display','none');
				if(this.contentDuring)this.contentDuring.setStyle('display','none');
				if(this.contentAfter) this.contentAfter.setStyle('display','block');
			} else if(this.now < this.length && this.now > this.to){
				this.periodical = this.duringOfferTimer.periodical(1000, this);
				if(this.contentPre) this.contentPre.setStyle('display','none');
				if(this.contentDuring) this.contentDuring.setStyle('display','block');
				if(this.contentAfter) this.contentAfter.setStyle('display','none');
			}
		},
		preOfferTimer: function(){
			
			dateFuture = this.to;

	        dateNow = new Date(); 						 
	        amount = dateFuture - dateNow.getTime();  	 
	
	        if(amount < 0){ 
	            this.contentPre.setStyle('display','none');
				this.contentDuring.setStyle('display','block');
				clearInterval(this.periodical);   
				this.periodical = this.duringOfferTimer.periodical(1000, this);
	        } else{ 
			
                var days=0,hours=0,mins=0,secs=0,out="";

                amount = Math.floor(amount/1000);

                days = Math.floor(amount/86400); 
                amount = amount%86400;

                hours = Math.floor(amount/3600); 
                amount = amount%3600;

                mins = Math.floor(amount/60); 
                amount = amount%60;
				
                secs = Math.floor(amount);
                
				hours += (days * 24)
				
                out += (hours.toString().length > 1) ? hours.toString() + ':' : '0' + hours.toString() + ':';
                out += (mins.toString().length > 1) ? mins.toString() + ':' : '0' + mins.toString() + ':';
                out += (secs.toString().length > 1) ? secs.toString() : '0' + secs.toString(); 
                
				this.timer.set('html', out);
	        } 
			
		},
		duringOfferTimer: function(){
			dateFuture = this.length;
	        dateNow = new Date(); 
	        amount = dateFuture - dateNow.getTime();
	
	        if(amount < 0){ 
				this.contentDuring.setStyle('display','none');
				this.contentAfter.setStyle('display','block');
				clearInterval(this.periodical);   
	        } else{ 
                days=0;hours=0;mins=0;secs=0;out="";
                amount = Math.floor(amount/1000);

                days=Math.floor(amount/86400); 
                amount=amount%86400;

                hours=Math.floor(amount/3600); 
                amount=amount%3600;

                mins=Math.floor(amount/60); 
                amount=amount%60;

                secs=Math.floor(amount);

                hours += (days * 24)
                out += (hours.toString().length == 1) ? '0' + hours + ':' : hours + ':';
                out += (mins.toString().length == 1) ? '0' + mins +":" : mins + ':';
                out += (secs.toString().length == 1) ? '0' + secs.toString() : secs.toString();  
                
				this.timer.set('html', out);
	        } 
		}
	});
	
	this.megaNav = new Class({
	
		Implements : [Events, Options],
	
		options : {
			header : '#header',
			meganavShop : 'ul.primary-nav #meganav-shop-top',
			meganavHS : 'ul.primary-nav #meganav-hs-top',
			shopTab : '.primary-nav li#phones, .primary-nav li#shop',
			inquiraTab : '.primary-nav li#inquira',
			phonesSpan : 'ul.primary-nav li#phones a.phones span',
			shopSpan : 'ul.primary-nav li#shop a.shop span',
			inquiraSpan : 'ul.primary-nav li#inquira a.inquira span'
		},
		
		initialize : function(options){
		
			this.setOptions(options);
			this.u = navigator.userAgent.toLowerCase();
			this.ie6 = (this.u.indexOf('msie 6') != -1); 
			this.ie7 = (this.u.indexOf('msie 7') != -1); 			
			this.fadeInShopTimer;
			this.fadeOutShopTimer;
			this.fadeInHSTimer;
			this.fadeOutHSTimer;
			this.cm;			
			this.clicked = false;
			this.header = $$(this.options.header);
			this.meganavShop = $$(this.options.meganavShop);
			this.meganavHS = $$(this.options.meganavHS);
			this.shopTab = $$(this.options.shopTab);
			this.inquiraTab = $$(this.options.inquiraTab);
			this.phonesSpan = $$(this.options.phonesSpan);
			this.shopSpan = $$(this.options.shopSpan);
			this.inquiraSpan = $$(this.options.inquiraSpan);
			this.meganavShop.setStyle('opacity', 0);
			this.meganavHS.setStyle('opacity', 0);	
			if(this.header){
				if(!this.ie6) this.header.removeClass('js-disabled');
				this.header.addClass('js-enabled');
			}
			this.shopTab.addEvent('mouseenter', this.fadeInShopHandler.bind(this));	
			this.shopTab.addEvent('mouseleave', this.fadeOutShopHandler.bind(this));	
			this.shopTab.addEvent('contextmenu', this.contextmenuHandler.bind(this));
			this.inquiraTab.addEvent('mouseenter', this.fadeInHSHandler.bind(this));	
			this.inquiraTab.addEvent('mouseleave', this.fadeOutHSHandler.bind(this));	
			this.inquiraTab.addEvent('contextmenu', this.contextmenuHandler.bind(this));			
		},
		
		fadeInShopHandler : function(e){
			var that = this;
			clearTimeout(this.fadeOutShopTimer);
			this.fadeInShopTimer = setTimeout(function(){that.fadeInShop();}, 200);
		},
		
		fadeOutShopHandler : function(e){
			var that = this;
			if(this.clicked) {
				this.clicked = false;
			} else {		
				clearTimeout(this.fadeInShopTimer);
				this.fadeOutShopTimer = setTimeout(function(){that.fadeOutShop();}, 500);		
			}
		},
		
		fadeInHSHandler : function(e){
			var that = this;
			clearTimeout(this.fadeOutHSTimer);
			this.fadeInHSTimer = setTimeout(function(){that.fadeInHS();}, 200);
		},
		
		fadeOutHSHandler : function(e){
			var that = this;
			if(this.clicked) {
				this.clicked = false;
			} else {		
				clearTimeout(this.fadeInHSTimer);
				this.fadeOutHSTimer = setTimeout(function(){that.fadeOutHS();}, 500);		
			}
		},		
		
		fadeInShop : function(){
			this.meganavShop.set('tween', {duration: 100});
			this.meganavShop.tween('opacity', 1);
			this.phonesSpan.tween('color', '#E20074');	;	
			this.shopSpan.tween('color', '#E20074');				
			this.shopSpan.setStyle('background-image', 'none');		
		},
		
		fadeOutShop : function(){
			this.meganavShop.set('tween', {duration: 100});
			this.meganavShop.tween('opacity', 0);
			this.phonesSpan.tween('color', '#E20074');
			this.phonesSpan.setStyle('url(/common/redesign-img/templates/nav-sprite.jpg) no-repeat')
			this.shopSpan.tween('color', '#FFFFFF');
			this.shopSpan.setStyle('background-image', 'url(/common/redesign-img/meganav/bg_white_arrow2.gif)');				
		},
		
		fadeInHS : function(){
			this.meganavHS.set('tween', {duration: 100});
			this.meganavHS.tween('opacity', 1);
			this.inquiraSpan.tween('color', '#E20074');
			this.inquiraSpan.setStyle('background-image', 'none');	
		},
		
		fadeOutHS : function(){
			this.meganavHS.set('tween', {duration: 100});
			this.meganavHS.tween('opacity', 0);
			this.inquiraSpan.tween('color', '#FFFFFF');
			this.inquiraSpan.setStyle('background-image', 'url(/common/redesign-img/meganav/bg_white_arrow2.gif)');			
		},
		
		contextmenuHandler : function(e){
			if(e.rightClick){
				this.clicked = true;
			}		
		}
		
	});

})(document.id)



Browser.extend({
	fixPNG: function(el) {
		try {
			
			if (Browser.ie6){
		
				el = document.id(el);
				if (!el) return el;
				
				if (el.get('tag') == "img" && el.get('src').test(".png")) {
					var vis = el.isDisplayed();
					try { //safari sometimes crashes here, so catch it
						dim = el.getSize();
					}catch(e){}
					if (!vis){
						var before = {};
						//use this method instead of getStyles 
						['visibility', 'display', 'position'].each(function(style){
							before[style] = this.style[style]||'';
						}, this);
						//this.getStyles('visibility', 'display', 'position');
						this.setStyles({
							visibility: 'hidden',
							display: 'block',
							position:'absolute'
						});
						dim = el.getSize(); //works now, because the display isn't none
						this.setStyles(before); //put it back where it was
						el.hide();
						
					}
					var replacement = new Element('span', {
						id:(el.id)?el.id:'',
						'class':(el.className)?el.className:'',
						title:(el.title)?el.title:(el.alt)?el.alt:'',
						styles: {
							display: vis?'inline-block':'none',
							width: dim.x,
							height: dim.y,
							filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader (src='" 
								+ el.src + "', sizingMethod='scale');"
						},
						src: el.src
					});
					if (el.style.cssText) {
						try {
							var styles = {};
							var s = el.style.cssText.split(';');
							s.each(function(style){
								var n = style.split(':');
								styles[n[0]] = n[1];
							});
							replacement.setStyle(styles);
						} catch(e){ dbug.log('fixPNG1: ', e)}
					}
					if (replacement.cloneEvents) replacement.cloneEvents(el);
					replacement.replaces(el);
					// adding class to avoid clashes with css
					replacement.addClass('fixedPng')
				} else if (el.get('tag') != "img") {
				 	var imgURL = el.getStyle('background-image');
					
				 	if (imgURL.test(/\((.+)\)/)){
		
				 		el.setStyles({
				 			background: '',
				 			filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true', sizingMethod='crop', src=" + imgURL.match(/\((.+)\)/)[1] + ")"
				 		});
						
				 	};
				}
			}
		} catch(e) {}
	},
  pngTest: /\.png$/, // saves recreating the regex repeatedly
  scanForPngs: function(el, className) {
    className = className||'fixPNG';
    //TODO: should this also be testing the css background-image property for pngs?
    //Q: should it return an array of all those it has tweaked?
    if (document.getElements){ // more efficient but requires 'selectors'
      el = document.id(el||document.body);
      el.getElements('img[src$=.png]').addClass(className);
    } else { // scan the whole page
      var els = $$('img').each(function(img) {
        if (Browser.pngTest(img.src)){
          img.addClass(className);
        }
      });
    }
  }
});

//(function($){
	window.addEvent('domready', function(){
		var mega = new megaNav();
	});
//})(document.id)

