(function ($) {
    Dropdown = function Dropdown (node, type) {
        this.node = node;
        this.id = node.attr('id');
		this.type = type;
        
        this.select = node.find('.select');
        this.select.click($.proxy(this._onClick, this));
		
        this.drop = node.find('.dropdown');
		
        if (type == 'register') {
			this.drop.find('a').click($.proxy(this._onSelect, this));
			
			var val = node.find('input').val(),
				li = node.find('li a[rel="' + val + '"]'),
				name = li.attr('name'),
				height = li.height(),
				insert = li.html();

			if (val != 0) {
				if (name) insert = '<img src="/images/flags/' + (height < 32 ? '24' : '32') + '/' + name + '.png" alt="' + insert + '" />' + insert;
				node.find('.sel').removeClass('sel');
				li.parent().addClass('sel');
				node.find('.select').attr('rel', val).find('span span').html(insert);
			}
		}
		else this.drop.find('a').click($.proxy(this._onChange, this));
		
		$(document).bind('keypress', $.proxy(this._onKey, this));
		
		//Get all values
		var self = this, title;
		this.values = [];
		this.drop.find('a').each(function (i) {
			title = $(this).html();
			self.values.push({'text': title, 'index': i, 'normalized': title.toLowerCase()});
		});
    };

    Dropdown.prototype = {
        id: null,
        select: null,
        drop: null,
        off: null,
        active: null,
		type: null,
		
		typed: '',
		typeTimer: null,
        values: [],
		
        _onClick: function () {
            if (this.off == 1) return;
            this.off = 1;
            var self = this;
            
            this.active = (this.active == 1 ? 0 : 1);
            if (this.active == 1) {
                if (!window.zi) window.zi = $('.country:last').css('z-index') || 10;
                this.node.css({'z-index': ++window.zi});
                this.select.addClass('active');

				this.drop.show();
				var list = this.drop.find('ul'),
					height = list.height();
				if (height < list.parent().height()) list.parent().css({height: height}).parent().css({padding: 0});
				this.drop.hide();
				
                this.drop
                    .slideDown(function () {
                        self.off = 0;
                    })
                    .find('.holder')
                    .jScrollPane({
                        verticalDragMinHeight: 19,
                        verticalDragMaxHeight: 19,
                        verticalGutter: 30
                    });
                $(document).mousedown(function (e) {
                    var target = $(e.target);
					self.off = 0;
                    if (self.off == 1 || target.parents('#' + self.id).size() == 1) return;
                    self.select.trigger('click');
                });
            } else {
                $(document).unbind('mousedown');
                this.drop
                    .slideUp('fast', function () {
                        self.off = 0;
                        self.select.removeClass('active');
                    });
            }
        },
		
		_onKey: function (e) {
			if (this.active) {
				var key = e.charCode || e.keyCode;
				
				//48 to 122 - character range
				//32 - spacebar
				if (!e.altKey && (key >= 48 && key <= 122 || key == 32 || key > 255)) {
					this.typed += String.fromCharCode(key).toLowerCase();
					
					var values = this.values,
						i = 0,
						ii = values.length;
					
					for(; i<ii; i++) {
						if (values[i].normalized.indexOf(this.typed) === 0) {
							//Jump to item
							var element = this.drop.find('li').eq(values[i].index),
								offset = element.offset().top - element.parent().offset().top;
							
							this.drop.find('div.holder').data().jsp.scrollToY(offset);
							break;
						}
					}
					
					//Reset value after 1.5 seconds
					if (this.typeTimer) clearTimeout(this.typeTimer);
					this.typeTimer = setTimeout($.proxy(function () {
						this.typeTimer = null;
						this.typed = '';
					}, this), 1500);
					
					return false;
				}
			}
		},

        _onChange: function (e) {
            var self = this;
            
            var target = $(e.currentTarget),
				country = target.attr('rel'),
				height = target.parent().height(),
				name = target.attr('name'),
				insert = target.html();

			if (name) insert = '<img src="/images/flags/' + (height < 32 ? '24' : '32') + '/' + name + '.png" alt="' + insert + '" />' + insert;

			self.select.attr('rel', country).trigger('click').find('span span').html(insert);
			self.drop.find('li').removeClass('sel');
			target.parent().addClass('sel');

			if (this.type == 'calculator') {
				var data = {
					country_reg: $('#country-reg .select').attr('rel'),
					country_in: $('#country-in .select').attr('rel'),
					country_out: $('#country-out .select').attr('rel')
				};
				
				if(data.country_in)
				{
					$('.incoming-calls').text(data.country_in.toUpperCase());
					$('.outgoing-calls').text(data.country_in.toUpperCase());
				}

				if (!data.country_reg || !data.country_in || !data.country_out) return;

				$.post('/ajax/index-calc.php', data, function (data) {
					window.price_airbaltic = [data.airbaltic[0], data.airbaltic[1]];
					window.price_other = [data.other[0], data.other[1]];

					$('#calculator').data('calculator').price();
				}, 'json');
			}

			if (this.type == 'tariffs') {
				var country_in = $('#country-in .select').attr('rel'),
					country_out = $('#country-out .select').attr('rel');

				if (!country_in || !country_out) return;

				$('#tariffs').data('tariffs')._onCountryChange();
			}
        },

		_onSelect: function (e) {
            if (this.off == 1) return;
			
            var target = $(e.currentTarget),
				value = target.attr('rel'),
				name = target.attr('name'),
				insert = target.html(),
				height = target.height();

			if (name) insert = '<img src="/images/flags/' + (height < 32 ? '24' : '32') + '/' + name + '.png" alt="' + insert + '" />' + insert;
			
			this.select.attr('rel', value).trigger('click').find('span span').html(insert);
			this.drop.find('li').removeClass('sel');
			target.parent().addClass('sel');

			this.select.next().val(value);
		}
    };

    $.fn.dropdown = function (type) {
        $(this).each(function () {
            var node = $(this);
            node.data('dropdown', new Dropdown(node, type));
        });

        return $(this);
    };
})(jQuery);
