/**
 * @author alexander.farkas
 */
(function($){
	$.widget('ui.combobox', {
		_init: function(){
			
			var o 			= this.options,
				that 		= this,
				downBtn 	= (o.drawDownBtn) ? '<span>&#9662;</span>' : '',
				items 		= '',
				className 	= this.element.attr('class'),
				corners 	= {
						cb: '',
						list: ''
					}
			;
			
			this.isNativeSelect = $.nodeName(this.element[0], 'select');
			
			if(this.isNativeSelect && !o.data){
				this.createDataFormSelect();
			}
			
			if((o.addRoundedCornerSpans)){
				corners.cb = '<span class="cb-design cb-tl" /><span class="cb-design cb-tr" /><span class="cb-design cb-bl" /><span class="cb-design cb-br" />';
				corners.list = '<span class="dl-design dl-bl" /><span class="dl-design dl-br" />';
			}
			
			this.combobox = $('<div class="combobox"> '+ corners.cb +' <input type="text" role="combobox" readonly="readonly" aria-readonly="false" /> '+ downBtn +'</div>')
								.attr({tabindex: '-1'});
								
			this.dataList = $('<div class="datalist" role="listbox"><div class="datalist-box" role="presentation"><div class="datalist-innerbox" role="presentation">'+ corners.list +'</div></div></div>');
								
			this.textbox = $('input', this.combobox).ownsThis(this.dataList).attr({'aria-expanded': 'false'})
								.attr('unselectable', 'on');
			
			if(className){
				this.combobox.addClass(className);
			}
			if(!o.data || !o.data.items || !o.data.items[0]){
				return;
			}
			
			if(o.data.label && o.data.label[0]){
				this.dataList.labelWith(o.data.label);
				this.textbox.labelWith(o.data.label);
				o.data.label.bind('click', function(e){
					that.combobox.setFocus();
					e.preventDefault();
					return false;
				});
			}
			
			$.each(o.data.items, function(i, item){
				var cN = (item.className) ? 'class="'+ item.className +'" ' : '';
				if(item.val === undefined){
					item.val = item.name;
				}
				items += '<li '+ cN +'data-val="'+ item.val +'" role="listitem"><span>'+ item.name +'</span></li>';
			});
			
			$('div.datalist-innerbox', this.dataList).append('<ul role="presentation">'+ items +'</ul>');
	
			this.items = $('li', this.dataList).attr({tabindex: '-1'});
						
			this.items.getID(true);
			
			this.combobox.insertAfter(this.element);
			
			if($.support.waiAria){
				this.element.hide();
			} else {
				this.textbox.attr({tabindex: '-1'});
				this.element
					.addClass('a11y-hidden')
					.one('focusin', function(){
						that.combobox.hide();
						that.element.removeClass('a11y-hidden');
					});
			}
			
			this.beforeShowVal = false;
			
			this.dataList
				.addClass('a11y-js-overflow')
				.appendTo('body')
				.bind('cOverlaybeforeShow', function(e){
					that.beforeShowVal = that.value;
					if(o.addTextboxWidthToDatalist){
						that.dataList.css( 'width', that.combobox[(o.addTextboxWidthToDatalist === true) ? 'width' : o.addTextboxWidthToDatalist]());
					}
				})
				.bind('cOverlaybeforeHide', function(e){
					if(that.beforeShowVal !== false && that.beforeShowVal !== that.value){
						that._trigger('change', e, that.ui());
						that.element.trigger('change');
					}
				})
				.bind('cOverlayhide', function(e){
					that.textbox.attr({'aria-expanded': 'false'});
					setTimeout(function(){
						that.textbox.removeAttr('aria-activedescendant');
					},1);
					that.dataList.attr({'aria-expanded': 'false'});
					that.combobox.removeClass('js-datalist-visible');
					that.selectedIndex = undefined;
					that.beforeShowVal = false;
					that.items.removeClass('js-selected');
				})
				.bind('cOverlayshow', function(e){
					that.textbox.attr({'aria-expanded': 'true'});
					that.dataList.attr({'aria-expanded': 'true'});
					that.combobox.addClass('js-datalist-visible');
				})
				.cOverlay(o.overlay)
			;
//needed for language preselection
	if (jQuery('select#country').length != 0) {
	var lng_pre = jQuery('select#country option:first').attr('rel');
	var arrLng_pre = lng_pre.split(',');
	var firstElem_pre = "";
	var idA11yWrapper = jQuery('div.sel-lang input').attr('aria-owns');
	var ulList = jQuery('div.a11y-wrapper div#' + idA11yWrapper).children().children().children('ul');
	jQuery(ulList).children().hide();
	for (var i=0; i<arrLng_pre.length; i++) {
		jQuery(ulList).find('li[data-val=' + arrLng_pre[i] + ']').css({'display':'list-item'});
		jQuery(ulList).find('li[data-val=' + arrLng_pre[i] + ']').click(function(){
			var countryWrapper = jQuery('div.sel-country input').attr('aria-owns');
			var countryAbbr = jQuery('div.a11y-wrapper div#' + countryWrapper).find('li.js-checked').attr('data-val').toLowerCase();
			var lngAbbr = jQuery(this).attr('data-val').toLowerCase();
			window.location.href = "http://" + window.location.host + "/ff_" + countryAbbr + "_" + lngAbbr + "/";
		});
		if (i==0) {
			firstElem_pre = arrLng_pre[i];
		}
	}
	var firstVal = jQuery('div.a11y-wrapper div#' + idA11yWrapper).find('li[data-val="' + firstElem_pre + '"]').children('span').text();
	jQuery('.sel-lang input').attr('aria-valuetext',firstVal);
	jQuery('.sel-lang input').val(firstVal);
	}
	
			this.overlayInstance = this.dataList.data('cOverlay');
						
			this.changeIndex(o.data.selectedIndex);
			
			if(this.isNativeSelect){
				this.element.bind('change', function(e){
					if(e && e.originalEvent){
						that.changeIndex(this.selectedIndex);
					}
				});
			}
			
			this.combobox.add(this.dataList)
				.bind('focusin', function(){
					clearTimeout(that.inActiveTimer);
					that.combobox.addClass('combobox-active');
					that.textbox.attr({tabindex: '-1'});
				})
				.bind('focusout', function(e){
					clearTimeout(that.inActiveTimer);
					that.inActiveTimer = setTimeout(function(){
						that.textbox.attr({tabindex: '0'});
						that.combobox.removeClass('combobox-active');
						that.close(e);
					}, 2);
				})
			;
			
			this.combobox
				.bind('mousedown', function(e){
					that.toggleVisibility(e);
					that.combobox.setFocus();
					return false;
				})
				.bind('keypress', function(e){
					var foundItem 	= false,
						code 		= e.charCode || e.which,
						key
					;
					
					if (code && code >= 32) { 
						key = String.fromCharCode(code).toUpperCase();
						that.items.each(function(i){
							var jElm = $(this);
							if(i !== that.checkedIndex && jElm.text().toUpperCase().indexOf(key) === 0){
								if(foundItem === false){
									foundItem = i;
								}
								if(i > that.checkedIndex){
									foundItem = i;
									return false;
								}
							}
						});
	            		
					}
					
					if(foundItem !== false){
						that.select(foundItem, e);
						return false;
					}
				})
				.bind('keydown', function(e){
					var index 		= (isFinite(that.selectedIndex)) ? that.selectedIndex : that.checkedIndex,
						foundItem 	= false,
						key
					;
					if(e.keyCode === $.ui.keyCode.RIGHT || e.keyCode === $.ui.keyCode.DOWN){
						foundItem = index + 1;
					} else if(e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.UP){
						foundItem = index - 1;
					} else if(e.keyCode === $.ui.keyCode.END || e.keyCode === $.ui.keyCode.PAGE_DOWN){
						foundItem = that.items.length -1;
					} else if(e.keyCode === $.ui.keyCode.HOME || e.keyCode === $.ui.keyCode.PAGE_UP){
						foundItem = 0;
					} else if(e.keyCode === $.ui.keyCode.ENTER){
						if(isFinite(that.selectedIndex)){
							that.select(that.selectedIndex, e);
						}
						that.close(e);
						return false; /* SPECIAL: ENTER: select + close */
					}
										
					if(foundItem !== false){
						that.select(foundItem, e);
						return false;
					}
				})
			;
			
			this.items.selector = 'li';
			this.items.context = $('ul', this.dataList)[0];
			
			this.items
				[o.bindStyle]('click', function(e){
					that.select(that.items.index(this), e, true);
					that.combobox.setFocus();
					that.close(e);
				})
				[o.bindStyle]('mouseenter', function(){
					that.selectedIndex = that.items.index(this);
					$(this).addClass('js-selected');
					setTimeout(function(){
						that.textbox.activateThis(that.items.filter(':eq('+ that.selectedIndex +')'));
					}, 1);
				})
				[o.bindStyle]('mouseleave', function(){
					that.selectedIndex = false;
					$(this).removeClass('js-selected');
				})
			;
			
			this._trigger('init', {type:'init'}, this.ui());
		},
		ui: function(obj){
			var ret = {
				instance: this,
				element: this.element,
				combobox: this.combobox,
				dataList: this.dataList,
				items: this.items,
				options: this.options,
				checkedIndex: this.checkedIndex
			};
			if(obj){
				$.extend(ret, obj);
			}
			return ret;
		},
		createDataFormSelect: function(){
			var o = this.options;
			o.data = {
				selectedIndex: this.element[0].selectedIndex,
				label: $('label[for='+this.element.getID()+']', this.element[0].form || document.body),
				items: []
			};
			$('option', this.element[0]).each(function(i){
				var option = $(this);
				o.data.items.push({
					name: option.text(),
					val: option.val(),
					className: this.className
				});
			});
		},
		toggleVisibility: function(e){
			this.overlayInstance[(this.overlayInstance.isVisible) ? 'hide' : 'show'](e, this.ui());
		},
		close: function(e){
			if(this.options.debug){return;}
			this.overlayInstance.hide(e, this.ui());
		},
		open: function(e){
			this.overlayInstance.show(e, this.ui());
		},
		changeIndex: function(i){
			var selected = this.items.filter(':eq('+ i +')');
			if(selected[0] && i > -1){
				this.beforeActiveItem = this.items.filter('.js-checked').removeClass('js-checked');
				this.activeItem = selected.addClass('js-checked');
				this.checkedIndex = i;
				if(this.isNativeSelect){
					this.element.val(selected.attr('data-val'));
					this.activeOption = this.element.find('option:eq('+ this.checkedIndex +')' );
				}
				
				this.text = this.activeItem.text();
				this.value = this.activeItem.attr('data-val');
				this.textbox.val(this.text).attr({'aria-valuetext': this.text});
			}
		},
		select: function(i, e, noFocus){
			e = e || {type: 'select'};
			$.extend(e, {selectboxData: this.ui({nextIndex: i})});
			var that = this;
			if(!this.overlayInstance.isVisible){
				this.open(e);
			}
			
			this.changeIndex(i);
			
			if(!noFocus){
				setTimeout(function(){
					that.textbox.activateThis(that.items.filter(':eq('+ that.checkedIndex +')'));
				}, 1);
			}
			this.selectedIndex = undefined;
			this._trigger('select', e, this.ui());
		}
	});
	
	$.ui.combobox.defaults = {
		overlay: {
			positionType: 'around',
			positionOpts: {
				horizontal: 'sameleft',
				vertical: 'bottom'
			}
		},
		addTextboxWidthToDatalist: false,
		bindStyle: 'bind',
		drawDownBtn: false,
		addRoundedCornerSpans: true,
		data: false,
		debug: false
		/*
		   data: {
					selectedIndex: 0,
					label: false,
					items: [
						{name: 'Option 1', val: 'o1'},
						{name: 'Option 2', val: 'o2'},
						{name: 'Option 3', className: }
						]
				}
		 */
	};
})(jQuery);


jQuery(document).ready( function(){
//	jQuery('select#country option').each( function(){
//		var optVal = jQuery(this).val();
//		if (pubCountry == optVal) {jQuery(this).attr('selected','selected');}
//	});
//	jQuery('select#language option').each( function(){
//		var optVal = jQuery(this).val();
//		if (pubLng == optVal) {jQuery(this).attr('selected','selected');}
//	});
	
// change available language when country was choosen
	jQuery('select#country').change(function(){
		var lng = jQuery('select#country option:selected').attr('rel');
		var arrLng = lng.split(',');
		if (arrLng.length == 1) {
			var cAbbr = jQuery('select#country option:selected').val().toLowerCase();
			if (cAbbr == 'emea' || arrLng[0] == "") {
				window.location.href = "http://" + window.location.host + "/ff_" + cAbbr + "/";
			} else {
				window.location.href = "http://" + window.location.host + "/ff_" + cAbbr + "_" + arrLng[0].toLowerCase() + "/";
			}
		} else {
			var firstElem = "";
			var idA11yWrapper = jQuery('div.sel-lang input').attr('aria-owns');
			var ulList = jQuery('div.a11y-wrapper div#' + idA11yWrapper).children().children().children('ul');
			jQuery(ulList).children().hide();
			for (var i=0; i<arrLng.length; i++) {
				jQuery(ulList).find('li[data-val=' + arrLng[i] + ']').css({'display':'list-item'});
				jQuery(ulList).find('li[data-val=' + arrLng[i] + ']').click(function(){
					var countryWrapper = jQuery('div.sel-country input').attr('aria-owns');
					var countryAbbr = jQuery('div.a11y-wrapper div#' + countryWrapper).find('li.js-checked').attr('data-val').toLowerCase();
					var lngAbbr = jQuery(this).attr('data-val').toLowerCase();
					window.location.href = "http://" + window.location.host + "/ff_" + countryAbbr + "_" + lngAbbr + "/";
				});
				if (i==0) {
					firstElem = arrLng[i];
				}
			}
			var firstVal = jQuery('div.a11y-wrapper div#' + idA11yWrapper).find('li[data-val="' + firstElem + '"]').children('span').text();
			jQuery('.sel-lang input').attr('aria-valuetext',firstVal);
			jQuery('.sel-lang input').val(firstVal);
		}
	});
	
	jQuery('select#language').change(function(){
		var countryAbbr = jQuery('select#country').val().toLowerCase();
		var languageAbbr = jQuery('select#language').val().toLowerCase();
		if ((countryAbbr != 'emea')&&(countryAbbr != 'home')) {
			window.location.href = "http://" + window.location.host + "/ff_" + countryAbbr + "_" + languageAbbr + "/";
		} else {
			window.location.href = "http://" + window.location.host + "/ff_" + countryAbbr + "/";
		}
	});


});

