ShopHelperClass = Class.extend( {

	initialize : function() {},
	
	updateGrossPrice : function( nettPriceSelector, grossPriceSelector, vatSource )
	{
		if ( vatSource.toString().charAt(0) == "#" )
		{
			var value = PriceExtractor.parse($(vatSource).val());
		}
		else
		{
			var value = PriceExtractor.parse(vatSource);
		}
		
		var vat = value.getPrice();
		
		var ppc = new PricePercentageCalculator();
		newValue = ppc.calculate( nettPriceSelector, grossPriceSelector, vat, false );
	},

	updateNettPrice : function( grossPriceSelector, nettPriceSelector, vatSource )
	{
		if ( vatSource.toString().charAt(0) == "#" )
		{
			var value = PriceExtractor.parse($(vatSource).val());
		}
		else
		{
			var value = PriceExtractor.parse(vatSource);
		}
		
		var vat = value.getPrice();
		var ppc = new PricePercentageCalculator();
		newValue = ppc.calculate( grossPriceSelector, nettPriceSelector, vat, true );
	}
});

ShopHelper = new ShopHelperClass();



/**
 * Calculates value from source_id modified by modifier, and writes it to destination_id object
 * @param inputSelector jQ selector of element that we get value from
 * @param outputSelector jQ selector of element where calculated value is written to
 * @param percentage percent value 0.22 (22%), 0.03 (3%) etc. 
 * @param reverse whether to: true - output = input * ( 1 + percentage), or false - output = input / ( 1 + percentage )
 */
PricePercentageCalculator = Class.extend( {

	initialize : function() {},
	
	calculate : function( inputSelector, outputSelector, percentage, reverse )
	{
		// in JS float contains "."
		var input = $( inputSelector );
		var output = $( outputSelector );
		
		var value = input.val();
		
		var price = PriceExtractor.parse(value)
		value = price.getPrice();
		var separator = price.getSeparator();
		
		if ( reverse )
		{
			var newValue = value / ( 1 + percentage );
		}
		else
		{
			var newValue = value * ( 1 + percentage );
		}
		
		if ( isNaN( newValue ) )
		{
			newValue = 0.0;
		}
		
		output.val( this.formatCurrency( newValue, separator ) );
	},
	
	formatCurrency : function( value, separator )
	{
		var formatter = new CashNumberFormatter('', 4, separator );
		return formatter.format( value );
	}
	
});
	
	
PriceExtractorClass = Class.extend( {

	initialize : function()
	{
	
	},
	
	parse : function(value)
	{
		var usesPeriod = (value.indexOf('.') != -1);
		var usesComma = (value.indexOf(',') != -1);
		
		// automagically find the separator
		var separator = ".";
		if ( usesComma && ! usesPeriod )
		{
			// 123,321 => 123.321
			// or 
			// 123,456,789 => 123.456789
			separator = ",";
		}
		else if ( usesPeriod && ! usesComma )
		{
			// 123.321 => 123.321
			// or 
			// 123.456.789 => 123.456789
			separator = ".";
		}
		else if ( usesPeriod && usesComma )
		{
			// both characters were used 
			// the last one used will be the separator (1.123,95 => here "," is the decimal separator, others are removed)
			// 1000s separator is being removed
			
			// 123.456,798 => 123456.789
			// 123,456.798 => 123456.789
			var lastSeparator = value.indexOf('.') > value.indexOf(',') ? "." : ",";
			separator = lastSeparator;
		}
	
		// strip all other stuff other than digits and the other separator
		var regexp = new RegExp("[^-0-9" + separator + "]+", "g");
		value = value.replace( regexp, "" );
		// so float parsing will success
		value = value.replace( /,/g, "." ); // , -> .
		
		value = parseFloat( value );
		
		if ( isNaN(value) )
		{
			value = 0.0;
		}
		return new PriceClass(value, separator);
	}
	
});

PriceExtractor = new PriceExtractorClass();


PriceClass = Class.extend( {

	initialize : function(price, separator)
	{
		this.price = price;
		this.separator = separator;
	},
	
	getPrice : function()
	{
		return this.price;
	},
	
	getSeparator : function()
	{
		return this.separator;
	}
	
});
/**
 * Formats cash values - 2 decimal digits + optional currency symbol
 * 
 * vat cnf = new CashNUmberFormatter("PLN");
 * alert( cnf.format( 123.213231 ) ); --> 123.21
 * alert( cnf.format( 123.2 ) ); --> 123.20
 */
CashNumberFormatter = Class.extend( {

	initialize : function(currencySymbol, precision, separator) 
	{
		if ( ! currencySymbol )
		{
			currencySymbol = "";
		}
		this.currencySymbol = currencySymbol;
		
		if ( ! precision )
		{
			precision = 4;
		}
		this.precision = precision;
		this.separator = separator;
	},
	
	format : function(price)
	{
		// clear price
		price = price.toString();
		price = price.replace( /,/g, '.' ).replace( / /g, '' ); // comma to dot, remove spaces
		price = Math.roundWithPrecision( parseFloat( price ), 4 );
		var str = '{value:.' + this.precision + 'f}{currency}';
		var v = $.format( str, {value:price, currency:this.currencySymbol});
		if ( this.separator )
		{
			v = v.replace( /[,.]/g, this.separator );
		}
		return v;
	}
	
});
	
	
/**
 * Math.roundWithPrecision( 123.456, 2 ) ==> 123.46
 */
Math.roundWithPrecision = function( value, precision )
{
	if ( ! precision )
	{
		precision = 1;
	}
	
	// to round with precision of 2:
	// X = X * 100
	// X = round( X )
	// X = x / 100
	var multiplier = Math.pow( 10, precision );
	var v = multiplier * value;
	v = Math.round( v );
	v = v / multiplier;
	
	return v;
}

SimpleProductSearcherClass = Class.extend( {

	initialize : function() 
	{
	},
	
	/**
	 formElement - the form that is being submited
	 targetSelector - jQuery selector that will be filled with search results
	 */
	search : function(formElement, targetSelector)
	{
		var form = $(formElement);
		$.ajax(
		{
			type : 'POST',
			url : form.attr( 'action' ),
			data : form.formSerialize(),
			success : function( data, status )
			{
				$(targetSelector).html( data );
				$(targetSelector).highlightFade();
			}
		});
		return false;
	}
});

SimpleProductSearcher = new SimpleProductSearcherClass();
