(function() {
	var request;
	var rel;
	var defaultSeries;
	var productId;
	var productName;
	var History = new HistoryManager();
	History.addEvent('onStateChange',function() {
		if (History.iframe) {
			History.iframe.setStyles({'position':'absolute','left':'-15000px'});
		}
	});
	function loadBluetooth(e) {
		var evt;
		var vals;
		if (e) {
			evt = new Event(e);
			evt.stop();
			vals = evt.target.get('rel').split('-');
			rel = vals[0];
			defaultSeries = vals[1];
			
			//webtrends
			var p1 = 'Connect my Bluetooth for ' + e.target.textContent;
			var p2 = e.target.textContent;
			var p3 = 'Connect My Bluetooth;Related Links;' + e.target.textContent + ';' + document.window.location;		
			dcsMultiTrack('WT.ti', p1, 'WT.cg_n', 'Connect My Bluetooth', 'WT.cg_s', p2, 'DCSext.action', p3);
		}
		request.send();
	}
	function autoSizeArrowLink(arrowLink) {
		var aSize = arrowLink.getElement('li a').getSize().x;
		if (Browser.Engine.trident4) {
			aSize = aSize - 2;
			if (aSize > 0) { arrowLink.setStyle('width',aSize); }
		}
	}
	motorola.pages.BluetoothPairing = new Class({
		Implements: [Events, Options],
		options: {
			bluetoothLinkClass: '',
			connectBluetoothUrl: '',
			instructionDataUrl: '',
			pairingPageTitle: '',
			pairingProductId: '',
			printUrlBase: '',
			productDataUrl: '',
			type: ''
		},
		events: {
			resize: null
		},
		fx: {
			elements: null
		},
		backButtonClass: 'back',
		cache: {},
		dataRequest: null,
		defaultPageTitle: '',
		destroyables: [],
		dropdown: null,
		forwardButtonClass: 'forward',
		htmlLoaded: false,
		instructionRequest: null,
		instructionScroller: null,
		instructionTemplate: null,
		lastResponse: null,
		lastVisibleRow: 2,
		overlay: null,
		productCache: {},
		productHistory: null,
		productList: null,
		scrollBarClass: 'scrollBar',
		scrubberClass: 'scrubber',
		thumbProductOptions: {
			highlightedStyles: {
				'border-width': '2px',
				'border-style': 'solid',
				'border-color': '#c6dde8'
			},
			unhighlightedStyles: {
				'border-width': '2px',
				'border-style': 'solid',
				'border-color': '#fff'
			}
		},
		textProductOptions: {
			highlightedStyles: {},
			unhighlightedStyles: {}
		},
		trackBarClass: 'track',
		productsPerRow: 4,
		slider: null,
		tabHistory: null,
		type: null,
		visible: false,
		selectedProductId: null,
		selectedProductName: null,

		initialize: function(options) {
			this.setOptions(options);
			request = new Request({
				'url': this.options.connectBluetoothUrl,
				'method': 'get',
				'onSuccess': this.setupConnect.bindWithEvent(this)
			});
			this.dataRequest = new Request({
				'url': this.options.productDataUrl,
				'method': 'get',
				'headers': {
					'ajax': 'true'
				},
				'onSuccess': this.update.bindWithEvent(this)
			});
			this.instructionRequest = new Request({
				'url': this.options.instructionDataUrl,
				'method': 'get',
				'headers': {
					'ajax': 'true'
				},
				'onSuccess': this.updateInstructions.bindWithEvent(this)
			});
			this.events.resize = this.fixOverlay.bind(this);
			this.thumbProductOptions.onSelect = this.productSelect.bind(this);
			this.textProductOptions.onSelect = this.productSelect.bind(this);
			this.type = this.options.type === 'bluetooth' ? 'accessoriesBluetooth' : 'phonesBluetooth';
			addEvent('domready',this.domready.bind(this));
			addEvent('load',this.load.bind(this));
			addEvent('beforeunload',this.destroy.bind(this));
		},

		initHistory: function() {
			History.initialize();
			this.tabHistory = History.register(
				'tab',
				[''],
				function(values) {
					var value = values[0];
					if (this.htmlLoaded && !value) { return this.hide(); }
					else if (!value) { return; }
					rel = value;
					var related;
					if (this.htmlLoaded) {
						related = $('bluetoothPairing').getElement('input[value='+rel+']');
						if (related) {
							related = related.getParent();
							this.tabSelect(related);
						}
						if (!this.visible) {
							this.show();
						}
					} else {
						loadBluetooth();
					}
				}.bind(this),
				false,
				false
			);
			this.productHistory = History.register(
				'product',
				[''],
				function(values) {
					var value = values[0];
					if (!value) { return; }
					productId = value;
					if (this.htmlLoaded) {
						this.getInstructions(productId);
						if (!this.visible) {
							this.show();
						}
					} else {
						loadBluetooth();
					}
				}.bind(this),
				false,
				false
			);
			History.start();
		},

		domready: function() {
			this.defaultPageTitle = document.getElement('title').get('html');
			this.initHistory();
			if (request.response) {
			} else {
				document.getElements('.' + this.options.bluetoothLinkClass).addEvent('click', loadBluetooth);
			}
		},

		load: function() { },

		setupConnect: function(text, xml) {
			this.htmlLoaded = true;
			document.getElements('.' + this.options.bluetoothLinkClass)
							.removeEvent('click', loadBluetooth)
							.addEvent('click',this.show.bind(this));
			var el = new Element(this.processHTML(text).childNodes[0]);
			$(document.body).adopt(el);
			el.getElements('.bluetoothProducts .tabs li').each(function(li) {
				var p = li.getElement('p');
				var span = new Element('span');
				li.adopt(span.clone().addClass('left'));
				li.adopt(span.clone().addClass('right'));
				p.adopt(span.clone().addClass('left'));
				p.adopt(span.clone().addClass('right'));
				if (li.getElement('img')) { li.addClass('hasImage'); }
				if (Browser.Engine.trident4) {
					li.addEvents({
						'mouseenter': function() { if (this.hasClass('selected')) { this.addClass('selected-hover'); } },
						'mouseleave': function() { this.removeClass('selected-hover').removeClass('hover'); }
					});
				}
				var clickEvent = this.tabSelect.pass([li],this);
				li.store('clickEvent',clickEvent);
				li.addEvent('click',clickEvent);
			},this);

			// setup elements needed for the display and functionality
			this.setupTemplate(
				$(this.type).setStyle('display','block').getElement('ol')
			);
			var overlay = new Element('div',{
				'id': 'bluetoothPairingOverlay',
				'events': {
					'click': this.hide.bind(this)
				}
			}).injectInside(document.body);
			this.overlay = motorola.utils.generateElementId(overlay);
			window.addEvent('contentVisible',this.fixOverlay.bind(this));
			this.setupDropdown();
			this.instructionTemplate = $('instructionTemplate').get('html');
			motorola.utils.domUpdated();
			// setup up events to remove product
			$('bluetoothSelected').getElement('.arrowLink li').addEvent('click',this.productDeselect.bind(this));
			$('bluetoothClose').addEvent('click',this.hide.bind(this));
			// setup printevents
			$('printPairing').addEvents({
				'click': this.printPreview.bind(this),
				'mouseenter': function() {
					var roll = this.getElement('.roll');
					var over = this.getElement('.preloader');
					roll.store('originalSrc',roll.get('src'));
					roll.set('src',over.get('src'));
				},
				'mouseleave': function() {
					var roll = this.getElement('.roll');
					var over = this.getElement('.preloader');
					roll.set('src',roll.retrieve('originalSrc'));
				}
			});
			// setup mousewheel events
			
			$(this.productList).getParent().getParent().addEvents({
				'mouseenter': document.addEvent.pass(['mousewheel',this.mousewheelScroller.bindWithEvent(this,['slider'])],document),
				'mouseleave': document.removeEvents.pass(['mousewheel'],document)
			});

			// initialize for a tab if one should be selected
			var related;
			var extraSuccessEvent;
			if (rel) {
				related = el.getElement('input[value='+rel+']');
				if (related) {
					// initialize for a product if one should be selected
					if (productId) {
						extraSuccessEvent = this.getInstructions.pass([productId],this);
						this.dataRequest.addEvent('onSuccess',extraSuccessEvent);
						this.dataRequest.addEvent('onSuccess',this.dataRequest.removeEvent.pass(['onSuccess',extraSuccessEvent],this.dataRequest));
					}
					related = related.getParent();
					this.tabSelect(related);
				}
			}

			// display the elements
			var els = new Elements([overlay,el]);
			this.fx.elements = new Fx.Elements(els,{
				'duration': Browser.Engine.trident ? 0 : motorola.fxoptions.duration,
				'transition': motorola.fxoptions.transition
			}).set({
				'0': { 'opacity': '0' },
				'1': { 'opacity': '0' }
			});
			this.show();
		},

		setupDropdown: function() {
			this.onDropdownChange = this.dropdownChange.bind(this);
			var selectOptions = $extend($clone(motorola.fxoptions),{
				'duration': 250,
				'animate': Browser.Engine.webkit,
				'onChange': this.onDropdownChange,
				'onExpand': function() {
					this.cache[this.lastResponse.category].searcher.quitSearch();
				}.bind(this)
			});
			if (defaultSeries) { selectOptions.defaultValue = selectOptions.initialValue = defaultSeries; }
			var dropdown;
			var type = this.type;
			var count = 0;
			$$('select.styledDropdown').each(function(dd) {
				var firstOption;
				if (dd.getParent('.bluetoothProducts').get('id') === type) {
					if (!defaultSeries) {
						firstOption = dd.getFirst('option');
						selectOptions.defaultValue = selectOptions.initialValue = firstOption.get('value') || '';
					}
					dd.removeClass('styledDropdown');
					dropdown = new MOTO.StyledForm.Dropdown(dd,selectOptions);
					dropdown.dropdown.store('styledDropdown',dropdown);
					if (count > 0) { dropdown.dropdown.setStyle('position','absolute'); }
					count = count + 1;
				}
			});
			this.dropdown = dropdown;
		},

		dropdownChange: function(dropdown) {
			this.filter(this.lastResponse.category);
			this.lastResponse.searcher.reset();
		},

		onDropdownChange: $empty, // set in setupDropdown

		setupTemplate: function(list) {
			this.productList = motorola.utils.generateElementId(list);
			motorola.controls.template = $('productListTemplate').dispose().getFirst();
		},

		update: function(res) {
			var response;
			if ($defined(res)) {
				if (typeof res === 'object') {
					response = res;
				} else {
					response = JSON.decode(res);
				}
				this.lastResponse = response;
			} else {
				response = this.lastResponse;
			}
			var productsData = response.productsData;
			if (response.productIds) {
				response.searcher.reset();
				response.searcher.enable();
				return this.filter(response.category);
			}
			var productIds = response.productIds = [];
			var cache = response.cache = {'_defaultSeries':[]};
			var seriesNames = response.seriesNames = [];
			var structure = $(this.type);
			var searcher = response.searcher = new motorola.controls.ProductSearcher(structure.getElement('.modelFilter'),structure.getElement('.modelFilterSearchResults'),{
				'onSelect': this.searcherProductSelect.bind(this),
				'scrollEnableCount': 10
			});
			this.cache[response.category] = response;
			var displayThumbnails = true;
			var productId, productData, product, series, seriesCache;
			for (productId in productsData) {
				productData = productsData[productId];
				productData.productId = productId;
				productIds.push(productId);
				displayThumbnails = displayThumbnails && productData.imageUrl;
				searcher.products.push(productData);
				series = productData.seriesOrManufacturer;
				if (series) {
					cache[series] = seriesCache = cache[series] ? cache[series] : [];
					seriesNames.include(series);
				} else {
					seriesCache = cache['_defaultSeries'];
				}
				seriesCache.push(productId);
			}
			seriesNames.sort().push('_defaultSeries');
			response.displayThumbnails = $defined(response.thumbsDisplay) ? response.thumbsDisplay : displayThumbnails;
			this.filter(response.category);
		},

		filter: function(category) {
			var response = this.cache[category];
			var productIds = response.productIds;
			var productsData = response.productsData;
			var displayThumbnails = response.displayThumbnails;
			var productOptions = displayThumbnails ? this.thumbProductOptions : this.textProductOptions;
			var i = 0;
			var productsShown = 0;
			var totalProducts = 0;
			var listParent = $(this.productList).getParent();
			var list = $(this.productList).dispose().setStyle('top','0px');
			list.getChildren().dispose();
			if (response.displayThumbnails) {
				listParent.removeClass('noThumbs');
			} else {
				listParent.addClass('noThumbs');
			}
			var dropdownValue = null;
			if (this.dropdown && this.dropdown.value)
					dropdownValue = this.dropdown.value;
			var productCache = this.productCache;
			$('instructions').setStyle('display','none');
			var selectedProduct = $('bluetoothSelected').getElement('.selected');
 			if (selectedProduct) {
 				selectedProduct.removeClass('selected').addClass('empty');
				selectedProduct.getElement('.productName').dispose();
				selectedProduct.getElements('img.productImage').dispose();
 			}			
			
			$(this.type).setStyle('display','block');
			var maxSeenProducts = displayThumbnails ? this.productsPerRow * this.lastVisibleRow : 12;
			var productId, productData, inSeries, el, product;
			do {
				productId = productIds[i];
				productData = productsData[productId];
				inSeries = !dropdownValue || dropdownValue === productData.seriesOrManufacturer.toLowerCase();
				if (!productData.elementId) {
					el = inSeries ? motorola.controls.template.clone() : null;
					if (inSeries) { el.store('productId',productId); }
					productCache[productId] = el;
					if (productsShown < maxSeenProducts && inSeries) {
						productOptions.el = el;
						product = new motorola.controls.SupportProduct(productData,productOptions);
						productsShown = productsShown + 1;
					}
				} else {
					if (inSeries) {
						el = productCache[productId];
						productsShown = productsShown + 1;
					}
				}
				if (inSeries) { totalProducts = totalProducts + 1; }
				if (el) {
					if (totalProducts % 2) { el.addClass('odd'); }
					list.grab(el);
				}
				i = i + 1;
			} while (i - productIds.length);
			list.grab(new Element('li',{'class':'clear'}));
			listParent.grab(list,'top');
			this.addTabEvents();
			var rowSize = list.getFirst().getSize().y;
			var viewableProducts = list.getChildren().length - 1;
			if (this.slider) {
				this.slider.destroy();
				list.setStyle('marginRight','0px');
				this.slider = null;
			}
			if (viewableProducts > maxSeenProducts) {
				list.setStyle('marginRight','15px');
				this.setupScroller.delay(50,this,[rowSize, displayThumbnails]);
			} else {
				this.hideLoading();
			}
		},

		createScrollBar: function(scrollBarHeight) {
			// Create scroll bar
			var scrollBar = new Element('div',{
				'class': this.scrollBarClass,
				'styles': {
					'height': scrollBarHeight
				}
			});
		
			// Setup back button
			var backButton = new Element('a',{
				'href': '#',
				'class': this.backButtonClass
			});
			backButton.addEvents({
				'mouseenter': backButton.addClass.pass([this.backButtonClass + 'Over'],backButton),
				'mouseleave': backButton.removeClass.pass([this.backButtonClass + 'Over'],backButton)
			});
			scrollBar.grab(backButton);
		
			// Setup track
			var track = new Element('div', {
				'class': this.trackBarClass
			});
		
			// Setup scrubber
			var scrubber = new Element('div',{
				'class': this.scrubberClass
			});
			track.grab(scrubber);
			scrollBar.grab(track);
		
			// Setup forward button
			var forwardButton = new Element('a',{
				'href': '#',
				'class': this.forwardButtonClass
			});
			forwardButton.addEvents({
				'mouseenter': forwardButton.addClass.pass([this.forwardButtonClass + 'Over'],forwardButton),
				'mouseleave': forwardButton.removeClass.pass([this.forwardButtonClass + 'Over'],forwardButton)
			});
			scrollBar.grab(forwardButton);

			return scrollBar;
		},

		createSlider: function(scrollBar, el, sliderOptions) {
			var scrollBarHeight = scrollBar.getStyle('height').toInt();
			var backButtonHeight = scrollBar.getElement('.' + this.backButtonClass).getSize().y;
			var forwardButtonHeight = scrollBar.getElement('.' + this.forwardButtonClass).getSize().y;
			var trackHeight = scrollBarHeight - backButtonHeight - forwardButtonHeight;
			scrollBar.getElement('.' + this.trackBarClass).setStyles({
				'height': trackHeight,
				'top': backButtonHeight
			});

			// Create slider
			var scrubberRatio = trackHeight / el.getScrollSize().y; 
			var slider = new MOTO.StyledForm.Slider(scrollBar,scrubberRatio,sliderOptions);
		
			// Setup mousewheel events
			slider.boundMousewheel = slider.mouseWheel.bindWithEvent(slider);

			return slider;
		},

		setupScroller: function(productHeight,snapTo) {

			var list = $(this.productList);
			var listParent = $(this.productList).getParent();

			var scrollBar = this.createScrollBar('309px');
		
			listParent.getParent().grab(scrollBar); 
		
			var sliderOptions = {
				'itemSize': productHeight,
				'horizontal': false,
				'onSlideTo': this.moveContent.bindWithEvent(this,['slide']),
				'onMoveTo': this.moveContent.bindWithEvent(this,['move']),
				'onReachedEnd': this.checkLastRows.bind(this),
				'snapTo': snapTo
			};

			this.slider = this.createSlider(scrollBar,listParent,sliderOptions);
		
			listParent.removeEvents('mouseenter');
			listParent.removeEvents('mouseleave');

			this.hideLoading();
		},

		mousewheelScroller: function(e,property) {
			if (this[property]) { this[property].mouseWheel(e); }
		},

		updateInstructions: function(res) {
			var response;
			if ($defined(res)) {
				if (typeof res === 'object') {
					response = res;
				} else {
					response = JSON.decode(res);
				}
			} else {
				throw new Error('response is not valid JSON');
			}

			//webtrends :: onload event
			if(isAccessory) {
				dcsMultiTrack('WT.ti', 'Connect My Bluetooth - Step 2', 'WT.cg_n', 'Connect My Bluetooth', 'WT.cg_s', 'Pairing Action', 'DCSext.action', 'Connect My Bluetooth;Product 2 Selection', 'WT.pn.id', this.productName + ';' + supportName, 'DCSext.cmbpair', '1', 'WT.si_n', 'Connect my Bluetooth', 'WT.si_x', '3', 'WT.si_cs', '1');
			}
			else {
				dcsMultiTrack('WT.ti', 'Connect My Bluetooth - Step 2', 'WT.cg_n', 'Connect My Bluetooth', 'WT.cg_s', 'Pairing Action', 'DCSext.action', 'Connect My Bluetooth;Product 2 Selection', 'WT.pn.id', supportName + ';' + this.productName, 'DCSext.cmbpair', '1', 'WT.si_n', 'Connect my Bluetooth', 'WT.si_x', '3', 'WT.si_cs', '1');
			}
			
			var instructions = $('instructions');
			var instructionSteps = $('instructionSteps').dispose().empty();
			var temp = new Elements();
			var steps = response.Steps;
			var stepsLength = steps.length;
			var i, step, li, html;
			for (i = 0; i < stepsLength; i = i + 1) {
				step = steps[i];
				html = '<div class="cap top"></div>';
				html = html + '<div>';
				html = html + '<div class="cap topCap"></div>';
				html = html + '<p class="stepNumber">' + (i + 1) + '. </p>';
				html = html + '<p class="stepText"><span class="titleText">' + step.title + '</span>';
				if (step.titleImage) {
					html = html + '<img src="' + step.titleImage + '" alt="' + step.title + '" />';
				}
				html = html + '</p>';
				if (!Browser.Engine.trident) { html = html + '<div class="clear"></div>'; }
				html = html + '<div class="cap bottomCap"></div>';
				html = html + '</div>';
				html = html + '<div class="cap bottom"></div>';
				li = new Element('li',{
					'html': html,
					'class': 'hoverable ' + (step.titleImage ? 'titleImage' : 'title')
				});
				li.addEvent('click', this.instructionSelect.pass([li,step],this))
				temp.push(li);
			}
			instructionSteps.adopt(temp);
			instructions.grab(instructionSteps,'top');
			motorola.utils.domUpdated();
			this.instructionSelect(temp[0].addClass('first'),steps[0]);

			// hide the tabs and products
			$(this.type).setStyle('display','none');
			instructions.setStyle('display','block');
			$('bluetoothPairing').getElements('.arrowLink').each(autoSizeArrowLink);
		},

		show: function(e) {
			var overlay = $(this.overlay);
			var pairing = $('bluetoothPairing');
			var evt;
			if (e) {
				evt = new Event(e).stop();
				rel = evt.target.get('rel');
			} else {
				rel = null;
			}
			var related;
			if (rel) {
				related = pairing.getElement('input[value='+rel+']');
				if (related) {
					related = related.getParent();
					this.tabSelect.run([related],this);
				}
			}
			var winSize = getScrollSize();
			var fxelements = this.fx.elements;
			fxelements.removeEvents('onStart').removeEvents('onComplete');
			fxelements.addEvent('onStart',overlay.setStyles.pass([{'display': 'block'}],overlay))
								.addEvent('onStart',this.events.resize)
								.addEvent('onStart',pairing.setStyles.pass([{'display': 'block'}],pairing))
								.addEvent('onStart',function() { $('bluetoothPairing').getElements('.arrowLink').each(autoSizeArrowLink); });
			window.addEvent('resize',this.events.resize);
			fxelements.start({
				'0': { 'opacity': '.4' },
				'1': { 'opacity': '1' }
			});
			this.visible = true;
			
			//webtrends :: onload event
			if(isAccessory) {
				dcsMultiTrack('WT.ti', 'Connect My Bluetooth Step 1', 'WT.cg_n', 'Connect My Bluetooth', 'WT.cg_s', 'Accessories Selection', 'DCSext.action', 'Connect My Bluetooth;Product 1 Selection', 'WT.pn.id', supportName, 'DCSext.cmbmobilephone', '', 'DCSext.cmbaccessories', 'initial', 'WT.si_n', 'Connect My Bluetooth', 'WT.si_x', '1', 'WT.si_cs', '0');
			}
			else {
				dcsMultiTrack('WT.ti', 'Connect My Bluetooth Step 1', 'WT.cg_n', 'Connect My Bluetooth', 'WT.cg_s', 'Mobile Phone Selection', 'DCSext.action', 'Connect My Bluetooth;Product 1 Selection', 'WT.pn.id', supportName, 'DCSext.cmbmobilephone', 'initial', 'DCSext.cmbaccessories', '', 'WT.si_n', 'Connect My Bluetooth', 'WT.si_x', '1', 'WT.si_cs', '0');
			}
		},

		hide: function(e) {
			motorola.utils.stopEvent(e);
			var overlay = $(this.overlay);
			var pairing = $('bluetoothPairing');
			var fxelements = this.fx.elements;
			fxelements.removeEvents('onStart').removeEvents('onComplete');
			fxelements.addEvent('onComplete',overlay.setStyles.pass([{'display': 'none','width': '1px', 'height': '1px'}],overlay))
								.addEvent('onComplete',pairing.setStyles.pass([{'display': 'none'}],pairing));
			fxelements.start({
				'0': { 'opacity': '0' },
				'1': { 'opacity': '0' }
			});
			this.visible = false;
			this.productHistory.setValue(0,'');
			this.tabHistory.setValue(0,'');
			document.title = this.defaultPageTitle;
			removeEvent('resize',this.events.resize);
			this.resetDropdown();
		},

		resetDropdown: function() {
			var dropdown = this.dropdown;
			if (dropdown && dropdown.value !== dropdown.defaultValue) {
				dropdown.removeEvent('onChange',this.onDropdownChange);
				dropdown.selectListOption(dropdown.listOptions[dropdown.defaultValue].displayElement);
				dropdown.addEvent('onChange',this.onDropdownChange);
			}
		},

		fixOverlay: function(e) {
			if (!motorola.globals.contentVisible) { return; }
			var wrapPosition = document.getElement('.wrap').getPosition();
			$('bluetoothPairing').setStyle('left',(wrapPosition.x + 65) + 'px');
			var overlay = $(this.overlay);
			overlay.setStyle('display','none');
			var winSize = getScrollSize();
			overlay.setStyles({position:'absolute','display':'block','width': winSize.x,'height': winSize.y});
		},

		moveContent: function(positionRatio,mode) {
			var list = $(this.productList);
			var listParent = list.getParent();
			var position = -positionRatio * list.getScrollSize().y;
			var response = this.lastResponse;
			var productsData = response.productsData;
			var displayThumbnails = response.displayThumbnails;
			var productOptions = displayThumbnails ? this.thumbProductOptions : this.textProductOptions;
			var parentSize = listParent.getSize();
			list.getChildren().each(function(li) {
				var productPosition = li.getPosition(list).y;
				var newProductPosition = productPosition + position;
				var productId, productData, product;
				if (newProductPosition >= 0 && newProductPosition < parentSize.y && !li.hasClass('clear')) {
					productId = li.retrieve('productId');
					productData = productsData[productId];
					if (!productData.elementId) {
						productOptions.el = li;
						product = new motorola.controls.SupportProduct(productData,productOptions);
					}
				}
			});
			mode === 'slide' ? list.tween('top', position) : list.setStyle('top', position);
		},

		moveInstructions: function(positionRatio,mode) {
			var content = $('instructionTemplate').getElement('.instructionWrapper div');
			var position = -positionRatio * content.getScrollSize().y;
			mode === 'slide' ? content.tween('top', position) : content.setStyle('top', position);
		},

		checkLastRows: function() {
			var list = $(this.productList);
			var response = this.lastResponse;
			var productsData = response.productsData;
			var productOptions = this.thumbProductOptions;
			var children = list.getChildren();
			var i = children.length;
			var stopAt = i - 9;
			var li, productId, productData, product;
			if (i) {
				do {
					i = i - 1;
					li = children[i];
					if (li.hasClass('clear')) { continue; }
					productId = li.retrieve('productId');
					productData = productsData[productId];
					if (!productData.elementId) {
						productOptions.el = li;
						product = new motorola.controls.SupportProduct(productData,productOptions);
					}
				} while (i && (i - stopAt));
			}
		},

		processHTML: function(text) {
			// this function is taken right from Request.HTML of mootools-core
			var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
			text = (match) ? match[1] : text;
			var container = new Element('div'), root = '<root>' + text + '</root>', doc;
			try {
				if (Browser.Engine.trident){
					doc = new ActiveXObject('Microsoft.XMLDOM');
					doc.async = false;
					doc.preserveWhiteSpace = true;
					doc.validateOnParse = false;
					doc.loadXML(root);
					if (doc.parseError.errorCode) throw new Error(doc.parseError.reason);
					root = doc.documentElement;
				} else {
					doc = new DOMParser().parseFromString(root, 'text/xml');
					root = doc.documentElement;
					if (root.nodeName == 'parsererror') throw new Error(element.firstChild.nodeValue);
				}
				for (var i = 0, k = root.childNodes.length; i < k; i++){
					var child = Element.clone(root.childNodes[i], true, true);
					if (child) container.grab(child);
				}
			} catch (e){
				this.fireEvent('onError', [e, doc]);
				container.set('html', text);
			}
			return container;
		},

		tabSelect: function(li) {
			this.removeTabEvents();
			var input = li.getElement('input');
			var tabTitle = input.get('title');
			var tabValue = input.get('value');
			var bluetoothProducts = $(this.type).addClass(tabValue);
			var ul = li.addClass('selected-hover').getParent();
			var lastSelected = ul.getElement('.selected');
			if (lastSelected) {
				this.cache[lastSelected.getElement('input').get('value')].searcher.disable();
				lastSelected.removeClass('selected').removeClass('selected-first').removeClass('selected-hover')
										.addEvent('click',this.tabSelect.pass([lastSelected],this));
			}
			li.removeEvents('click');
			if (li.hasClass('first')) {
				li.addClass('selected-first');
			}
			li.addClass('selected');
			this.lastPageTitle = this.options.pairingPageTitle + ' | ' + tabTitle;
			document.title = this.lastPageTitle;
			var dropdowns = bluetoothProducts.getElements('.dropdown').setStyles({'position':'absolute','left':'-15000px'});
			var dropdown = dropdowns.filter(function(dropdown) { return dropdown.hasClass(tabValue); })[0];
			if (dropdown) {
				dropdown.setStyles({'position':'relative','left':'auto'});
				this.dropdown = dropdown.retrieve('styledDropdown');
			}
			this.tabHistory.setValue.delay(25,this.tabHistory,[0,tabValue]);
			this.showLoading();
			if (this.cache[tabValue]) {
				this.update(this.cache[tabValue]);
			} else {
				this.dataRequest.get({'category':tabValue,'type':this.options.type,'productId':this.options.pairingProductId});
			}
			
			//webtrends
			var destinationUrl = this.options.productDataUrl + '&category=' + tabValue + '&type=' + this.options.type + '&productId=' + this.options.pairingProductId;
			dcsMultiTrack('WT.ti', 'Connect my Bluetooth - Bluetooth Accessories tab for ' + tabTitle, 'WT.cg_s', 'Tab Selection', 'DCSext.action', 'Connect my Bluetooth;Accessories Tab;' + tabTitle + ';' + destinationUrl, 'WT.pn.id', supportName);
		},

		removeTabEvents: function() {
			$('bluetoothPairing').getElements('.bluetoothProducts .tabs li').each(function(li) {
				var clickEvent = li.retrieve('clickEvent');
				li.removeEvent('click',clickEvent);
			});
		},

		addTabEvents: function() {
			$('bluetoothPairing').getElements('.bluetoothProducts .tabs li').each(function(li) {
				if (li.hasClass('selected')) { return; }
				var clickEvent = li.retrieve('clickEvent');
				li.addEvent('click',clickEvent);
			});
		},

		showLoading: function() {
			var type = $(this.type);
			if (Browser.Engine.trident) {
				type.getElement('ol.products').setStyle('visibility','hidden');
				if (this.slider) { type.getElement('.scrollBar').setStyle('display','none'); }
			}
			if (Browser.Engine.trident4) {
				type.getElement('.bluetoothLoading').setStyle('display','block');
			}
		},

		hideLoading: function() {
			$(this.type).getElement('ol.products').setStyle('visibility','visible');
			$(this.type).getElement('.bluetoothLoading').setStyles({'display':'none','visibility':'hidden'});
		},

		productSelect: function(e,product) {
			var evt = new Event(e);
			evt.stop();
			this.selectedProductId = product.productData.productId;
			this.selectedProductName = product.productData.name;
			if (product.productData.productUrl) {
				window.open(product.productData.productUrl,"","menubar=1,resizable=1,scrollbars=1,status=1,width=1004,height=600,top=10,left=10");
				return;
			}
			this.hideLoading();
			// no product url means send the request to get the instructions
			document.title = this.options.pairingPageTitle + ' | ' + product.productData.name;
			this.getInstructions(product.productData.productId);
		},

		searcherProductSelect: function(searcher) {
			//webtrends
			var isAccessory = 'false';
			var productFamily = 'Mobile Phones;'
			var isAccessoryInput = document.getElementById('isAccessory');
			if(isAccessoryInput){
				isAccessory = isAccessoryInput.value;
				if(isAccessory == 'true'){
					productFamily = '';
				}
			}
			dcsMultiTrack('WT.ti', 'Support- Model Search Field Click','WT.cg_s', 'Product Search Field', 'DCSext.action', 'Connect My Bluetooth;'+ productFamily +'Model Search Field','WT.z_evt2','12');
			
			var clicked = searcher.highlighted ? searcher.highlighted : searcher.found[0];
			var data = clicked.retrieve('productData');
			if (data.productUrl) {
				location.href = data.productUrl;
			} else {
				this.getInstructions(data.productId);
			}
		},

		getInstructions: function(productId) {
			this.productHistory.setValue(0,productId);
			var productData = this.lastResponse.productsData[productId];
			
			//webtrends
			this.productName = productData.name;
			
			var productName = new Element('p',{
				'class': 'productName',
				'html': productData.name
			});
			if (!$('bluetoothSelected').getElement('.empty')) {
				return;
			}
			var emptyProduct = $('bluetoothSelected').getElement('.empty').grab(productName, 'top');
			var productImage;
			if (productData.imageUrl && productData.imageUrl !== '') {
				productImage = new Element('img',{
					'src': productData.imageUrl,
					'alt': productData.name,
					'class': 'productImage'
				});
				emptyProduct.grab(productImage, 'top');
			} else {
				emptyProduct.addClass('noImage');
			}
			emptyProduct.removeClass('empty').addClass('selected').store('productId',productId);
			if (this.options.type === 'bluetooth') {
				this.instructionRequest.get({'bluetooth': productId, 'phone': this.options.pairingProductId});
			} else {
				this.instructionRequest.get({'bluetooth': this.options.pairingProductId, 'phone': productId});
			}
		},

		productDeselect: function(e) {
			motorola.utils.stopEvent(e);
			var el = $('bluetoothSelected').getElement('.selected').removeClass('noImage');
			if (Browser.Engine.trident4) {
				el.removeClass('hover')
					.removeEvents('mouseenter').removeEvents('mouseleave')
					.removeEvents('mousedown').removeEvents('mouseup');
				document.getElements('#bluetoothPairing .arrowLink li').addClass('hover').removeClass('hover');
			}
			this.hideLoading();
			this.productHistory.setValue(0,'');
			document.title = this.lastPageTitle;
			this.update();
			
			//webtrends
			dcsMultiTrack('WT.ti', 'Connect my Bluetooth - Change Product ' + this.selectedProductId, 'WT.cg_n', 'Connect my Bluetooth', 'WT.cg_s', 'Change Pairing', 'DCSext.action', 'Connect my Bluetooth;Change Product;' + this.selectedProductName, 'WT.pn.id', this.selectedProductId);
		},

		instructionSelect: function(li,step) {
			li.getParent().getChildren().removeClass('selected').removeClass('selected-first');
			li.addClass('selected');
			if (li.hasClass('first')) { li.addClass('selected-first'); }
			var instructionTemplate = $('instructionTemplate');
			instructionTemplate.set('html',this.instructionTemplate.template(step));
			if (!step.instructionImage) { instructionTemplate.getElement('.instructionImage').dispose(); }
			this.scrollInstructions.delay(10,this);
			
			//webtrends
			dcsMultiTrack('WT.ti', 'Connect my Bluetooth - Pairing Steps for ' + step.title, 'WT.cg_n', 'Connect my Bluetooth', 'WT.cg_s', 'Pairing Steps', 'DCSext.action', 'Connect my Bluetooth;Pairing Steps;' + step.title + ';' + document.window.location);
		},

		scrollInstructions: function() {
			var inner = $('instructionTemplate').getElement('.inner');
			var innerDiv = inner.getElement('div');
			var instructionsHeight = innerDiv.getSize().y;
			if (instructionsHeight < 230) { return inner.setStyle('visibility','visible'); }
			// if too big create a wrapper for '#instructionTemplate .inner div' with appropriate overflow and height
			// so actual instructions can be moved and the wrapper used as a mask
			inner.setStyle('marginRight','45px');
			var wrapperSize = 340 - inner.getElement('h2').getSize().y;
			innerDiv.setStyle('position','relative');
			var wrapper = new Element('div',{
				'class': 'instructionWrapper',
				'styles': {
					'height': wrapperSize
				}
			});
			wrapper.wraps(innerDiv);

			var scrollBar = this.createScrollBar(wrapperSize - 2); // subtract two for border size
			inner.grab(scrollBar);

			var sliderOptions = {
				'horizontal': false,
				'onSlideTo': this.moveInstructions.bindWithEvent(this,['slide']),
				'onMoveTo': this.moveInstructions.bindWithEvent(this,['move']),
				'snapTo': false
			};

			this.instructionSlider = this.createSlider(scrollBar,wrapper,sliderOptions);

			wrapper.addEvents({
				'mouseenter': document.addEvent.pass(['mousewheel',this.mousewheelScroller.bindWithEvent(this,['instructionSlider'])],document),
				'mouseleave': document.removeEvents.pass(['mousewheel'],document)
			});

			inner.setStyle('visibility','visible');
		},

		printPreview: function(e) {
			motorola.utils.stopEvent(e);
			var width = 970; //window.getSize().x;
			var height = screen.height || window.getSize().y;
			var url = this.options.printUrlBase;
			var productId = $('bluetoothSelected').getElement('.selected').retrieve('productId');
			if (this.options.type === 'bluetooth') {
				url = url + '&bluetooth=' + productId + '&phone=' + this.options.pairingProductId;
			} else {
				url = url + '&bluetooth=' + this.options.pairingProductId + '&phone=' + productId;
			}
			var popup = new MOTO.Popup(url, {
				'width': width,
				'height': height,
				'name': 'pairing',
				'scrollbars': 'yes',
				'resizeable': 'yes'
			});
		},

		destroy: function() {
			if ($('bluetoothPairing')) {
				$$('#bluetoothPairing .dropdown').each(function(dropdown) {
					var styledDropdown = dropdown.retrieve('styledDropdown');
					if (styledDropdown) { styledDropdown.destroy(); }
				});
				$('bluetoothPairing').destroy();
			}
		}
	});
})();

