( function( $ ) {

	var calculatorHtml = '';

	// ----------------------------------------------------------------


	$.fn.WarmLossesCalculator = function( options ) {

		var thisObject = $( this );
		
		var containerId = thisObject.attr( 'id' );

		if ( calculatorHtml == '' ) {
			$.ajax({
				url: '/calculatorFormRu.php',
				type: 'get',
				dataType: 'html',
				async: false,
				success: function( responseData ) {
					calculatorHtml = responseData;
				},
				error: function( xhr ) {
					alert( 'Net error' );
				}
			});
		}

		thisObject.html( calculatorHtml );

		var calculatorForm = thisObject.find( 'form' );
		var calculationResultContainer = calculatorForm.find( '.calculationResultContainer' );

		var square = calculatorForm.find( 'input[name=square]' );
		calculatorForm
			.find( 'input[name=square]' )
			.keypress(
				function( event ) {
					if ( event.keyCode == 13 ) {
						calculatorForm.trigger( 'click' );
					}
				}
			);

		var coefficients = {
			windowsTypeK: calculatorForm.find( '*[name=windowsTypeK]' ),
			wallIsolationK: calculatorForm.find( '*[name=wallIsolationK]' ),
			windowsToFloorSquareRatioK: calculatorForm.find( '*[name=windowsToFloorSquareRatioK]' ),
			outDoorsTemperatureK: calculatorForm.find( '*[name=outDoorsTemperatureK]' ),
			wallsToStreetCountK: calculatorForm.find( '*[name=wallsToStreetCountK]' ),
			overHeadRoomTypeK: calculatorForm.find( '*[name=overHeadRoomTypeK]' ),
			roomHeightK: calculatorForm.find( '*[name=roomHeightK]' )
		};

		calculatorForm
			.find( 'input[name=calculateButton]' )
			.click(
				function( event ) {
					var squareValue = square.val();
					if ( squareValue == '' ) {
						alert( 'Введите площадь помещения!!!' );
						return;
					}

					regExp = /^\D+(\.\D+)?/g
					if ( regExp.test( squareValue ) ) {
						alert( 'Поле "Площадь" должно быть числом ( положительным :)' );
						return;
					}
					calculationResultContainer.html( '' );

					var warmLosses = 75 *
						squareValue *
						coefficients.windowsTypeK.val() *
						coefficients.wallIsolationK.val() *
						coefficients.windowsToFloorSquareRatioK.val() *
						coefficients.outDoorsTemperatureK.val() *
						coefficients.wallsToStreetCountK.val() *
						coefficients.overHeadRoomTypeK.val() *
						coefficients.roomHeightK.val();

					calculationResultContainer.html( '<p class="mustfill"><strong>Предполагаемые теплопотери:&nbsp;&nbsp;' + ( warmLosses / 1000 ).toFixed( 1 ) + ' кВт</strong></p>' );
				}
			);
	}

})( jQuery )