(function($){
	$.fn.vat = function(options, param){
		var defaults = {
			percent: 18,
			resultLinks: '#result-links',
			round: 2 // default round digits after zero or dot
		};
			
		newOptions = $.extend(defaults, options);
		
		return this.each(function(){
			var el = $(this);
			
			if (el.data('vat')) {
				if (typeof options == 'string'){
					el.data('vat')[options](param);
				} 
				return;
			}
			
			var vat = new Vat(this, newOptions);
			el.data('vat', vat);
		});
	}
	
	var Vat = function(el, options){
		var el = $(el);
		var self = this;
		
		var noVat, vat, withVat, vatPercent;
		
		var inputs;
		var resultLinks;
		var converts = 0;
		
		function init() {
			var o = options;
			
			noVat = el.find('#no-vat-input');
			vatPercent = el.find('#vat-percent-input');
			vat = el.find('#vat-input');
			withVat = el.find('#with-vat-input');			
			
			inputs = el.find('input, select');
			
			resultLinks = $(o.resultLinks);
			
			if(o.percent) {
				vatPercent.val(o.percent);
			}
			
			var uri = window.location.pathname.replace(/\/money\/vat\/?/, '')
			if ((/[0-9]+\/[0-9,]\/?/).test(uri)) {
				uri = uri.split('/')
				var num = get(uri[1]).toFixed(o.round);
				if (num) {
					withVat.val(format(num));
					if (uri[0] && !isNaN(uri[0]))
						vatPercent.val(uri[0]);
				}
			}
			
			
			
			if (vatPercent.get(0).tagName.toLowerCase() == 'select') { // else input
				vatPercent.selectmenu({
					close: function(event, selectmenu) {
						selectmenu.list.shadow('hide');
					},
					format: function(text) {
						return text.replace('%', '<span>%</span>');
					},
					open: function(event, selectmenu) {
						var IE6 = $.browser.msie && $.browser.versionX == 6;
						var IE8 = $.browser.msie && $.browser.versionX == 8;
						var list = selectmenu.list;
						list.css('top', list.position().top - selectmenu.newelement.height() + (IE8 ? 2 : 1));
						if(!IE6) 
							list.width('auto');
						list.shadow();
						list.shadow('show');
					},
					style: 'dropdown'
				});
			}
			
			inputs.bind('keyup input change', function() {
				convert($(this));
			});
			
			inputs.bind('blur', function() {
				var num = get(this.value);
				if (this.id != vatPercent[0].id && num) {
					this.value = format(num.toFixed(options.round));
				}
			});
			
			convert(withVat);
		}
		
		function convert(input) {
			var o = options;
			var round = o.round;
			
			inputs.removeClass('input-disabled').removeClass('input-error');
			
			var inputNum = get(input);
			
			if (inputNum !== false) {
				var isSet = false;
				switch (input[0].id) {
					case noVat[0].id:
						var vatPercentNum = get(vatPercent);
						
						if (vatPercentNum) {							
							var noVatNum = get(noVat);
							
							var vatNum = (noVatNum * (vatPercentNum / 100)).toFixed(round);
							vat.val(format(vatNum));
							
							var withVatNum = (noVatNum * (1 + vatPercentNum / 100)).toFixed(round);
							withVat.val(format(withVatNum));
							
							isSet = true;
						}
						break;
						
					case withVat[0].id:
						var vatPercentNum = get(vatPercent);
						var withVatNum = get(withVat);
						
						var noVatNum = (withVatNum / (1 + vatPercentNum / 100)).toFixed(round);
						noVat.val(format(noVatNum));
						
						var vatNum = (withVatNum * (vatPercentNum / 100) / (1 + vatPercentNum / 100)).toFixed(round);
						vat.val(format(vatNum));
						
						isSet = true;
						
						break;
						
					case vatPercent[0].id:						
						var noVatNum = get(noVat);
						var vatPercentNum = get(vatPercent);
						
						if (noVatNum) {
							var vatNum = (noVatNum * vatPercentNum / 100).toFixed(round);
							vat.val(format(vatNum));
							
							var withVatNum = (noVatNum * (1 + (vatPercentNum / 100))).toFixed(round);
							withVat.val(format(withVatNum));
							
							isSet = true;
						} else {
							var withVatNum = get(withVat);
							
							if (withVatNum) {
								var vatNum = (withVatNum * (vatPercentNum / 100) / (1 + (vatPercentNum / 100))).toFixed(round);
								vat.val(format(vatNum));
								
								var noVatNum = (withVatNum / (1 + (vatPercentNum / 100))).toFixed(round);
								noVat.val(format(noVatNum));
								
								isSet = true;
							}
						}
						break;
						
				}
				
				if(isSet) {
					setResultLinks();					
					converts++;
				}
			} else {
				inputs.filter(':not(#' + input[0].id + ')').addClass('input-disabled');
				input.addClass('input-error');
				
				resultLinks.css('visibility', 'hidden');
			}
		}
		
		function setHash(){
			var o = options;
			var hash = '#' + withVat.val().replace(/\s+/g, '').replace(/,00$/, '');
			if (o.percent && vatPercent.val() != o.percent) {
				hash += '_' + vatPercent.val();
			}
			
			location.hash = hash;
		}
		
		function setResultLinks() {
			var o = options;
			
			var withVatVal = withVat.val();
			var vatPercentVal = vatPercent.val();
			
			//was a condition: <vatPercentVal != o.percent ? '_' + vatPercentVal : ''> - dont know why not just <vatPercentVal> 
			var url = 'http://' + window.BaseServer + '/money/vat/' + vatPercentVal + '/' + withVatVal.replace(/\s+/g, '').replace(/,00$/, ''); 
			
			var codeText = s('vat % of x', vatPercentVal, withVatVal);
			
			resultLinks.find('#result-link-url').val(url);
			resultLinks.find('#result-link-code').val('<a href="' + url + '">' + codeText + '</a>');
			
			resultLinks.css('visibility', 'visible');
		}
		
		function format(num) {
			var str = num.toString().replace('.', ',').replace(/\s+/g, '');
			var arr = str.split(',');
			if(arr[0].length > 3) {
				arr[0] = arr[0].replace(/(\d{1,3}(?=(\d{3})+$))/g,'\$1 ');
			}
			var value = arr.join(',');
			
			return value;
		}
		
		function get(str) {
			if (typeof str == 'object') {
				str = str.val();
			}
			str = str.replace(/\s+/g, '').replace(',', '.');
			if(isNaN(str)) {
				return false;
			} else {
				return Number(str);
			}
		}
		
		init();
	}
})(jQuery);
