﻿if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this === void 0 || this === null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n !== n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

if(!String.prototype.trim) {
	String.prototype.trim = function () {
		return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
	};
}
/**
 * jQuery mousehold plugin - fires an event while the mouse is clicked down.
 * Additionally, the function, when executed, is passed a single
 * argument representing the count of times the event has been fired during
 * this session of the mouse hold.
 *
 * @author Remy Sharp (leftlogic.com)
 * @date 2006-12-15
 * @example $("img").mousehold(200, function(i){  })
 * @desc Repeats firing the passed function while the mouse is clicked down
 *
 * @name mousehold
 * @type jQuery
 * @param Number timeout The frequency to repeat the event in milliseconds
 * @param Function fn A function to execute
 * @cat Plugin
 */
jQuery.fn.mousehold = function(timeout, f) {
	if (timeout && typeof timeout == 'function') {
		f = timeout;
		timeout = 100;
	}
	if (f && typeof f == 'function') {
		var timer = 0;
		var fireStep = 0;
		return this.each(function() {
			jQuery(this).mousedown(function() {
				fireStep = 1;
				var ctr = 0;
				var t = this;
				timer = setInterval(function() {
					ctr++;
					f.call(t, ctr);
					fireStep = 2;
				}, timeout);
			});

			var clearMousehold = function() {
				clearInterval(timer);
				if (fireStep == 1) {
					f.call(this, 1);
				}
				fireStep = 0;
			};
			
			jQuery(this).mouseout(clearMousehold);
			jQuery(this).mouseup(clearMousehold);
		});
	}
};
/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window)._scrollable();
	};

	// Hack, hack, hack :)
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn._scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this._scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					max = $scrollTo.max(elem, axis);

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
				}else{ 
					var val = targ[pos];
					// Handle percentage values
					attr[key] = val.slice && val.slice(-1) == '%' ? 
						parseFloat(val) / 100 * max
						: val;
				}

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

		}).end();
	};
	
	// Max scrolling position, works on quirks mode
	// It only fails (not too badly) on IE, quirks mode.
	$scrollTo.max = function( elem, axis ){
		var Dim = axis == 'x' ? 'Width' : 'Height',
			scroll = 'scroll'+Dim;
		
		if( !$(elem).is('html,body') )
			return elem[scroll] - $(elem)[Dim.toLowerCase()]();
		
		var size = 'client' + Dim,
			html = elem.ownerDocument.documentElement,
			body = elem.ownerDocument.body;

		return Math.max( html[scroll], body[scroll] ) 
			 - Math.min( html[size]  , body[size]   );
			
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
// had to change the name of the function because it was causing problems
var freeCookies=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

XH = {
	settings: { },
	defaults: { }
};

XH.defaults.deviceSelector = {
	buttonScrolls: '1items',
	itemWidth: 100,
	autoSelect: true,
	autoScroll: true,
	animationLength: 200,
	deviceTemplate: [
		'<a href="#" id="ds-item-{device id}">',
			'<img src="{device image}" alt="{device name}" />',
			'<br />',
			'{device name}',
		'</a>'
	].join('')
};

XH.DeviceSelector = function(id, settings) {
	/** preparations **/
	var s = this,
		isOtherDrag = true;
	/** aquire settings **/
	s.settings = $.extend({ }, XH.defaults.deviceSelector, settings);
	/** adjusting settings **/
	s.settings.buttonScroll = s.settings.buttonScrolls.toLowerCase();
	s.settings.buttonScrollValue = parseInt(s.settings.buttonScrolls, 10);
	s.settings.buttonScrollValue = isNaN(s.settings.buttonScrollValue) ? 0 : s.settings.buttonScrollValue;
	
	if(s.settings.buttonScroll.indexOf('items') !== -1) {
		s.settings.buttonScrollType = 'items';
	}
	else if(s.settings.buttonScroll.indexOf('%') !== -1) {
		s.settings.buttonScrollType = 'percent';
	}
	else { // pixels
		s.settings.buttonScrollType = 'pixels';
	}
	/** aquire elements **/
	s.qWrapper = $('#' + id);
	s.qWrapper.show();
	s.qSelectorView = $('.ds-device-container', s.qWrapper);
	s.qDeviceList = $('ul.ds-device-list', s.qSelectorView);
	s.qListItems = $('li', s.qDeviceList);
	s.qNotFoundCont = $('.ds-not-found', s.qWrapper);
	s.qLoadingCont = $('.ds-loading', s.qWrapper);
	s.qSlider = $('.ds-slider', s.qWrapper);
	s.qSliderPane = $('.ds-slider-pane', s.qSlider);
	s.qSliderHandle = $('.ds-slider-handle', s.qSliderPane);
	s.qSliderLeftButton = $('.ds-slider-left-button', s.qSlider);
	s.qSliderRightButton = $('.ds-slider-right-button', s.qSlider);
	s.qShowAllDevicesBtn = $('.ds-btn-show-all-devices', s.qWrapper);
	s.qSearchInput = $('input.ds-search', s.qWrapper);
	/** set selector values **/
	s.scrollPaneWidth = s.qSliderPane.width();
	s.scrollHandleWidth = s.qSliderHandle.width();
	s.scrollAreaWidth = s.scrollPaneWidth - s.scrollHandleWidth;
	s.deviceListWidth = s.qDeviceList.width();
	s.viewWidth = s.qSelectorView.width();
	s.viewWidthPercent = (s.viewWidth / s.deviceListWidth) * 100;
	s.viewArea = s.deviceListWidth - s.viewWidth;
	
	if(s.settings.rtl) {
		s.qSelectorView.attr('dir', 'ltr');
		s.qNotFoundCont.attr('dir', 'rtl');
	}
	
	s.lastPositionInPercent = 0;
	s.searchTextPrefills = [ ];
	s.buttonScrollPercent = 0;
	s.devices = { };
	s.elemSelected = null;
	s.cookieName = 'XHSelectedDevice';
	s.cookieValue = freeCookies(s.cookieName) || '';
	
	/** add events to elements **/
	s.qSearchInput.each(function (i) {
		s.searchTextPrefills[i] = this.value;
		
		$(this).keyup(function (e) {
			s.searchFor(this.value);
		});
		
		$(this).focus(function (e) {
			if(this.value === s.searchTextPrefills[i]) {
				this.value = '';
			}
		});
		
		$(this).blur(function (e) {
			if(this.value === '') {
				this.value = s.searchTextPrefills[i];
			}
		});
		
		this.value = s.searchTextPrefills[i];
	});
	s.qShowAllDevicesBtn.click(function (e) {
		s.searchFor('');
		
		s.qSearchInput.each(function (i) {
			$(this).val(s.searchTextPrefills[i]);
		});
		
		e.preventDefault();
	});
	s.qSliderLeftButton.mousehold(s.settings.animationLength, function (e) {
		s.slideToDirection(s.buttonScrollPercent, 'left', true);
	});
	s.qSliderRightButton.mousehold(s.settings.animationLength, function (e) {
		s.slideToDirection(s.buttonScrollPercent, 'right', true);
	});
	s.qSliderPane.click(function (e) {
		var qTarget = $(e.target),
			offset,
			clickPosition,
			clickPositionInPercent,
			direction;
		
		if(qTarget.is('.ds-slider-pane')) {
			offset = qTarget.offset();
			
			clickPosition = e.pageX - offset.left;
			
			clickPositionInPercent = s.paneClickPercent(clickPosition);
			
			direction = (s.lastPositionInPercent > clickPositionInPercent) ? 'left' : 'right';
			
			clickPositionInPercent = (direction === 'left' ?  s.lastPositionInPercent - s.viewWidthPercent : s.lastPositionInPercent + s.viewWidthPercent);
			
			s.slideToPosition(clickPositionInPercent, true);
		}
	});
	s.qDeviceList.delegate('a', 'click', function(e) {
												  
		// triggers tnt call
		if(typeof(mboxSelectDevice) != 'undefined') {
			mboxSelectDevice($(this).text());
		}
		
		window.setTimeout(function () {
			if(s.settings.autoScroll) {
				$.scrollTo(s.qWrapper, 300);
			}
		}, s.settings.animationLength);
		
		if(s.elemSelected && $('a', s.elemSelected).attr('id') === this.id) {
			s.unselect(this.id.substring(8));
		}
		else {
			s.select(this.id.substring(8));
		}
		
		e.preventDefault();
	});
	s.qSliderHandle.draggable({
		containment: '.ds-slider-pane',
		axis: 'x',
		distance: 10,
		drag: function (e, ui) {
			var paneOffset,
				handleOffset,
				leftPos;
			
			if(isOtherDrag) {
				paneOffset = s.qSliderPane.offset();
				handleOffset = s.qSliderHandle.offset();
				
				leftPos = handleOffset.left - paneOffset.left;
				s.slideToPosition(s.getSliderAreaPercentPosition(leftPos));
				isOtherDrag = false;
			}
			else {
				isOtherDrag = true;
			}
		},
		stop: function (e, ui) {
			var paneOffset = s.qSliderPane.offset(),
				handleOffset = s.qSliderHandle.offset(),
				leftPos;
			
			leftPos = handleOffset.left - paneOffset.left;
			s.slideToPosition(s.getSliderAreaPercentPosition(leftPos));
		}
	});
	/** custom events **/
	s.select(function (e, id) {
		var element = s.devices[id],
			children,
			x, lex,
			index,
			destinationPercent,
			indexPixels;
		
		if(element) {
			element = element.element;
			children = s.qDeviceList.get(0).childNodes;
			
			for(x = 0, lex = children.length; x < lex; x++) {
				if(children[x] === element) {
					index = s.qListItems.index(element);
					
					if(index !== -1) {
						index -= Math.floor(s.viewWidth / (2 * s.settings.itemWidth));
						index = index < 0 ? 0 : index;
						/*
						index -= 2;
						index = index < 0 ? 0 : index;
						*/
						indexPixels = (index * s.settings.itemWidth);
						
						destinationPercent = (indexPixels / s.viewArea) * 100;
						
						s.slideToPosition(destinationPercent, true);
					}
				}
			}
		}
		
		if(s.elemSelected) {
			$(s.elemSelected).removeClass('selected');
		}
		
		s.elemSelected = element;
		$(s.elemSelected).addClass('selected');
		
		s.cookieValue = id;
		freeCookies(s.cookieName, id, { path: '/' });
	});
	s.unselect(function (e, id) {
		if(s.elemSelected) {
			$(s.elemSelected).removeClass('selected');
		}
		
		s.elemSelected = null;
	});
	/** set element visibilities **/
	s.qWrapper.show();
	s.qLoadingCont.show();
	s.qDeviceList.hide();
	s.qNotFoundCont.hide();
	s.qSlider.css('visibility', 'hidden');
};

XH.DeviceSelector.prototype.select = function (aArg) {
	if(typeof aArg === 'function') {
		this.qDeviceList.bind('selectdevice', aArg);
	}
	else {
		this.qDeviceList.trigger('selectdevice', aArg);
	}
};

XH.DeviceSelector.prototype.unselect = function (aArg) {
	if(typeof aArg === 'function') {
		this.qDeviceList.bind('unselectdevice', aArg);
	}
	else {
		this.qDeviceList.trigger('unselectdevice', aArg);
	}
};

XH.DeviceSelector.prototype._refresh = function () {
	var newDeviceListWidth;
	
	this.qDeviceList.show();
	this.qListItems = $('li:visible', this.qDeviceList);
	newDeviceListWidth = this.qListItems.length * this.settings.itemWidth;
	
	if($.browser.msie && $.browser.version < 7) { // IE6 duplicate text bugfix
		newDeviceListWidth += 10;
	}
	
	newDeviceListWidth = newDeviceListWidth < this.viewWidth ? this.viewWidth : newDeviceListWidth;
	this.qDeviceList.css('width', newDeviceListWidth);
	this.deviceListWidth = this.qDeviceList.width();
	this.viewWidthPercent = (this.viewWidth / this.deviceListWidth) * 100;
	this.viewArea = this.deviceListWidth - this.viewWidth;
	
	if(this.settings.buttonScrollType === 'items') {
		this.buttonScrollPercent = ((this.settings.buttonScrollValue * this.settings.itemWidth) / this.viewArea) * 100;
	}
	else if(this.settings.buttonScrollType === 'percent') {
		this.buttonScrollPercent = this.settings.buttonScrollValue;
	}
	else { // pixels
		this.buttonScrollPercent = (this.settings.buttonScrollValue / this.viewArea) * 100;
	}
	
	if(this.qListItems.length === 0) {
		this.qNotFoundCont.show();
		this.qDeviceList.hide();
	}
	else {
		this.qNotFoundCont.hide();
		this.qDeviceList.show();
	}
	
	this.qLoadingCont.hide();
	this.qSlider.css('visibility', this.deviceListWidth > this.viewWidth ? 'visible' : 'hidden');
	
	if(this.settings.rtl) {
		this.slideToPosition(100, true);
	} else {
		this.slideToPosition(0, true);
	} 

	//this.slideToPosition(0, true);
};

XH.DeviceSelector.prototype.paneClickPercent = function (positionInPixels) {
	return (positionInPixels / this.scrollPaneWidth) * 100;
};

XH.DeviceSelector.prototype.getSliderAreaPixelPosition = function (positionInPercent) {
	return (this.scrollAreaWidth / 100) * positionInPercent;
};

XH.DeviceSelector.prototype.getViewAreaPixelPosition = function (positionInPercent) {
	return (this.viewArea / 100) * positionInPercent;
};

XH.DeviceSelector.prototype.getSliderAreaPercentPosition = function (positionInPixels) {
	return (positionInPixels / this.scrollAreaWidth) * 100;
};

XH.DeviceSelector.prototype.slideToPosition = function (positionInPercent, animate) {
	var sliderPositionInPixels,
		viewPositionInPixels;
	
	positionInPercent = positionInPercent > 100 ? 100 : positionInPercent;
	positionInPercent = positionInPercent < 0 ? 0 : positionInPercent;
	
	sliderPositionInPixels = this.getSliderAreaPixelPosition(positionInPercent);
	viewPositionInPixels = this.getViewAreaPixelPosition(positionInPercent);
	
	if(animate) {
		this.qSliderHandle.animate({'left': sliderPositionInPixels + 'px'}, this.settings.animationLength);
		this.qDeviceList.animate({'margin-left': -viewPositionInPixels + 'px'}, this.settings.animationLength);
	}
	else {
		this.qSliderHandle.css({'left': sliderPositionInPixels + 'px'});
		this.qDeviceList.css({'margin-left': -viewPositionInPixels + 'px'});
	}
	
	this.lastPositionInPercent = positionInPercent;
};

XH.DeviceSelector.prototype.slideToDirection = function (positionInPercent, direction, animate) {
	var newPositionInPercent = direction === 'left' ? this.lastPositionInPercent - positionInPercent : this.lastPositionInPercent + positionInPercent;
	this.slideToPosition(newPositionInPercent, animate);
};

XH.DeviceSelector.prototype.searchFor = function (aQuery) {
	var prop,
		device,
		devices = this.devices;
		//qVis;
	
	aQuery = aQuery.toLowerCase();
	
	for(prop in devices) {
		if(devices.hasOwnProperty(prop)) {
			device = devices[prop];
			
			if(device.name.indexOf(aQuery) !== -1) {
				$(device.element).show();
			}
			else {
				$(device.element).hide();
			}
		}
	}
	
	this._refresh();
	/* this was the "select when only one device is in the list" feature
	qVis = this.qDeviceList.find('li:visible');
	
	if(!this.settings.dontAutoSelect && qVis.length === 1) {
		this.select($('a', qVis).get(0).id.substring(8));
	}
	else {
		this.unselect();
	}*/
};

XH.DeviceSelector.prototype.addAll = function (aIdList, aDevices) {
	var li,
		x, lex,
		template = '',
		deviceSerieLetter,
		device,
		letterDevices = [ ], numberDevices = [ ], netbooks = [ ];
	
	aIdList.sort();
	
	for(x = 0, lex = aIdList.length; x < lex; x++) {
		deviceSerieLetter = aIdList[x].charAt(6).toLowerCase();
		if(isNaN(deviceSerieLetter)) {
			if(deviceSerieLetter !== 'b') {
				letterDevices.push(aIdList[x]);
			}
			else {
				netbooks.push(aIdList[x]);
			}
		}
		else {
			numberDevices.push(aIdList[x]);
		}
	}
	
	aIdList = letterDevices.concat(numberDevices, netbooks);
	
	if(this.settings.rtl) {
		aIdList.reverse();
	}
	
	for(x = 0, lex = aIdList.length; x < lex; x++) {
		li = document.createElement('li');
		template = this.settings.deviceTemplate;
		device = aDevices[aIdList[x]];
		
		if(device && device.name && device.image) {
			device.id = aIdList[x];
			
			li.innerHTML = XH.supplement(template, { device: device });
			/*
			template.replace(/\{device name\}/g, device.name)
				.replace(/\{device image\}/g, device.image)
				.replace(/\{device id\}/g, aIdList[x]);
			*/
			this.qDeviceList.append(li);
			
			this.devices[aIdList[x]] = {
				name: device.name.toLowerCase(),
				element: li,
				index: $(this.qDeviceList).get(0).childNodes.length - 2
			};
		}
	}
	
	this._refresh();
	this.searchFor('');
	
	if(this.settings.autoSelect) {
		this.autoSelectDevice();
	}
};

XH.DeviceSelector.prototype.clear = function () {
	this.qDeviceList.html('');
	this.devices = [ ];
	this._refresh();
};

XH.DeviceSelector.prototype.autoSelectDevice = function () {
    var sr = location.search,
		seek = sr.substring(1, (sr.indexOf('&') !== -1 ? sr.indexOf('&') : sr.length)).replace(/=/g, ''),
		str = seek.split(""),
		pos = 0,
        num, afternum, fullname = "";
		
    seek = seek.toLowerCase();
    seek = seek.replace(/[^a-z 0-9\-]+/g, '');
    var idConvTable = {
        '8800carbonarte': 'nokia-8800-carbon-arte',
        '8800goldarte': 'nokia-8800-gold-arte',
        'c3': 'nokia-c3-00',
        'c6-00': 'nokia-c6-00',
        'e71x': 'nokia-e71x',
        'n86': 'nokia-n86-8mp',
        'x3': 'nokia-x3-00',
        'nx6': 'nokia-x6-00'
    };
    if (idConvTable[seek]) {
        fullname = idConvTable[seek];
    } else {

        //conversion - all ids to new ones
        if (seek.indexOf("nokia") != -1) {
            fullname = seek;
        } else {
            for (var x = 0, lex = str.length; x < lex; x++) {
                if (!isNaN(str[x])) {
                    pos = x;
                }
                var last = x;
            }

            if ((seek.substr(pos + 1, 1) == "i")) {
                num = (seek.substring(0, pos + 2));
                afternum = (seek.substring(pos + 2, last + 1));
            } else {
                num = (seek.substring(0, pos + 1));
                afternum = (seek.substring(pos + 1, last + 1));
            }

            if (!afternum == "") {
                fullname = "nokia-" + num + "-" + afternum;
            } else {
                fullname = "nokia-" + num;
            }
        }
        //end of conversion
    }
    var device = $('#ds-item-' + fullname).get(0);
    var dev = this;
	
	if(!device) {
		device = $('#ds-item-' + this.cookieValue).get(0);
		fullname = this.cookieValue;
	}
	
    if (device) {
        setTimeout(function () {
            dev.select(fullname);
        }, 250);
    }
};



XH.Package = function (files, selector) {
	this.id = +new Date();
	this.files = files;
	this.selector = selector;
	this.documents = [ ];
	this.data = { };
	this.lists = { };
	this.defaults = { };
	this.groups = { };
	
	var that = this;
	

	

	
	function loadFiles(files, whenReady) {
		var fileData = [ ],
			x, lex;
		
		function areAllLoaded() {
			for(var x = 0, lex = fileData.length; x < lex; x++) {
				if(!fileData[x].isLoaded) {

					return false;
				}
			}

			return true;
		}
		
		function getDocuments() {
			var result = [ ],
				x, lex;
			
			for(x = 0, lex = fileData.length; x < lex; x++) {
				if(fileData[x].xmlDoc) {
					result.push(fileData[x].xmlDoc);
				}
			}
			

			
			return result;
		}
		
		function loadFile(fd) {
			$.ajax({
				url: fd.url + '?' + (+new Date), // !!! important fix for ie6, prevent ie6 cacheing
				dataType: 'xml',
				complete: function (xhr) {

					fd.xmlDoc = xhr.responseXML;
					fd.isLoaded = true;
					/*
					if(!fd.xmlDoc) {

					}
					*/
					if(areAllLoaded()) {
						if(typeof whenReady === 'function') {
							whenReady(getDocuments());
						}
					}
				}
			});
		}
		
		for(x = 0, lex = files.length; x < lex; x++) {
			fileData[x] = {
				url: files[x],
				isLoaded: false,
				xmlDoc: null
			};
			
			loadFile(fileData[x]);
		}
	}

	loadFiles(files, function (documents) {
		that.documents = documents;
		that.ready();
	});
	
	this.ready(function (e) {

		
		that._processResponse(that.documents, that.selector);
	});
};

XH.Package.prototype.ready = function (callback) {
	if(typeof callback === 'function') {

		$(window).bind('XH.' + this.id + '-ready', callback);
	}
	else {

		$(window).trigger('XH.' + this.id + '-ready');
	}
};

XH.Package.prototype._processResponse = function (documents, selector) {
	var x, lex,
		y, ley,
		docElem,
		docElemChildren,
		child,
		childId,
		elemName,
		elemCont;
		

	
	for(x = 0, lex = documents.length; x < lex; x++) {

		
		if(documents[x]) {

			docElem = documents[x].documentElement;
			docElemChildren = docElem.childNodes;
			
			for(y = 0, ley = docElemChildren.length; y < ley; y++) {
				child = docElemChildren[y];
				if(child.nodeType === 1) {
					childId = child.getAttribute('id');
					if(childId && this._isItForMe(child.getAttribute('for'), child.getAttribute('notFor'))) {

						elemName = docElemChildren[y].nodeName;
						
						if(!this.data[elemName]) {
							this.data[elemName] = { };
							this.lists[elemName] = [ ];
						}
						
						elemCont = this.data[elemName];
						
						if(!elemCont[childId]) {
							this.lists[elemName].push(childId);
						}
						
						this._addItem(elemCont, child, childId);
						
						if(elemName === 'defaults') {
							this._addDefault(this.get('defaults', childId), childId);
						}
						
						if(elemName === 'group') {
							this._addGroup(child, childId);
						}
					}
				}
			}
		}
	}
};

function isElement(node) {
	return node.nodeType === 1;
}

function isWhitespace(str) {
	return str.match(/^\s+$/);
}

XH.Package.prototype._getTextContent = function (node) {
	var children = node.childNodes,
		x, lex,
		content = '';
	
	for(x = 0, lex = children.length; x < lex; x++) {
		if(isElement(children[x])) {
			return null;
		}
		
		if(!isWhitespace(children[x].nodeValue)) {
			content += children[x].nodeValue;
		}
	}
	
	return content;
};

XH.Package.prototype._normalizeAttribute = function (aAttr) {
	return aAttr.replace(' ', '').indexOf(',') === -1 ? aAttr = [aAttr] : aAttr.split(',');
};

XH.Package.prototype._isItForMe = function (aFor, aNotFor) {
	var x, lex;
	
	aFor = this._normalizeAttribute(aFor || 'all');
	aNotFor = this._normalizeAttribute(aNotFor || '');
	

	
	for(x = 0, lex = aNotFor.length; x < lex; x++) {
		if(this._isGroup(aNotFor[x])) {
			if(this._isInGroup(aNotFor[x], this.selector)) {
				return false;
			}
		}
		else {
			if(aNotFor[x] === this.selector) {
				return false;
			}
		}
	}
	
	for(x = 0, lex = aFor.length; x < lex; x++) {
		if(this._isGroup(aFor[x])) {
			if(this._isInGroup(aFor[x], this.selector)) {
				return true;
			}
		}
		else {
			if(aFor[x] === this.selector || aFor[x] === 'all') {
				return true;
			}
		}
	}
	
	return false;
};

XH.Package.prototype._addItem = function (obj, elem, elemId) {
	var textContent = this._getTextContent(elem),
		children,
		child,
		elemName,
		x, lex;
	
	
	if(textContent !== null) {
		obj[elemId] = textContent;
	}
	else {
		children = elem.childNodes;
		if(!obj[elemId]) {
			obj[elemId] = { };
		}
		
		for(x = 0, lex = children.length; x < lex; x++) {
			child = children[x];
			if(child.nodeType === 1) {
				if(this._isItForMe(child.getAttribute('for'), child.getAttribute('notFor'))) {
					elemName = child.nodeName;
					obj[elemId][elemName] = $(child).text();
				}
			}
		}
	}
};

XH.Package.prototype._addDefault = function (obj, elemId) {
	this.defaults[elemId] = obj;
};

XH.Package.prototype._getDefault = function (aName, aFor) {
	if(this.defaults[aName]) {
		return this.defaults[aName][aFor] || '';
	}
	
	return '';
};

XH.Package.prototype._addGroup = function (elem, elemId) {
	this.groups[elemId] = $(elem).text().split(',');
};

XH.Package.prototype._isGroup = function (selector) {
	return selector in this.groups;
};

XH.Package.prototype._isInGroup = function (group, selector) {
	return this.groups[group].indexOf(selector) !== -1;
};

XH.Package.prototype.get = function (type, id) {
	if(id) {
		return this.data[type] ? this.data[type][id] : undefined;
	}
	else {
		return this.data[type] ? this.data[type] : null;
	}
};

XH.Package.prototype.getList = function (type) {
	return this.lists[type];
};

XH.supplement = (function () {
	var matchPattern = /\{(.*?)\}/g,
		separator = ' ',
		currentContext = null;
	
	function replacer(str) {
		var strParts,
			withinBrackets;
		

		
		withinBrackets = str.substring(1, str.length-1); // get rid of the braces
		
		withinBrackets = withinBrackets.replace('#', ' ');
		strParts = withinBrackets.split(' ');
		


		if(typeof currentContext[strParts[0]] === 'undefined') {
			return str;
		}
		
		if(strParts.length === 2 && !(currentContext[strParts[0]] && typeof currentContext[strParts[0]][strParts[1]] === 'string')) {

			return str;
		}
		
		if(strParts.length === 3 && !(currentContext[strParts[0]] && currentContext[strParts[0]][strParts[1]] && typeof currentContext[strParts[0]][strParts[1]][strParts[2]] === 'string')) {

			return str;
		}
		
		if(strParts.length === 2) {
			return XH.supplement(currentContext[strParts[0]][strParts[1]], currentContext);
		}
		else {
			return XH.supplement(currentContext[strParts[0]][strParts[1]][strParts[2]], currentContext);
		}
	}
	
	return function (template, context) {
		currentContext = context;
		return template.replace(matchPattern, replacer);
	};
})();
