function syncPrices( selectors )
{
	var s = selectors;

        s.rowLocator = s.item1;
	syncRowPrices( s );

        s.rowLocator = s.item2;
	syncRowPrices( s );

        s.rowLocator = s.item3;
	syncRowPrices( s );

        syncQuantitySelects( s.rowLocator, s.quantity, s.backPackagesCount );
	
	outputTotalPrice( s );
}

function syncRowPrices( selectors )
{
	var s = selectors;
	var row = $( s.rowLocator );
	var quantityToBuy = parseInt( row.find( s.quantity ).attr( "value" ) );
        var allQuantityToBuy = 0;
        $( s.rowsCollectionLocator ).each( function()
	{
		allQuantityToBuy += parsePrice(
			$( this )
				.find( s.quantity )
				.attr( "value" ) );
	});
	var discountBottles = parseInt( row.find( s.discountBottles ).attr( "value" ) );	
	
	var price = parsePrice( row.find( s.firstPrice ).attr( "value" ) );
	if ( allQuantityToBuy >= discountBottles )
	{		
		price = parsePrice( row.find( s.deliveryDiscountPrice ).attr( "value" ) );
	}	
	var cost = price * quantityToBuy;	
	
	outputRowPrice( row, s, cost );
}

function outputRowPrice( row, selectors, cost )
{
	var s = selectors;
	row.find( s.costInput ).attr( "value", priceToString( cost ) );
	row.find( s.costCell ).text( cost > 0 ? priceToString( cost ) : s.priceNoneSign );
}

function outputTotalPrice( selectors )
{
	var s = selectors;
	var cost = 0;
	var packingsToBuy = 0;	
	$( s.rowsCollectionLocator ).each( function()
	{
		cost += parsePrice( 
			$( this )
				.find( s.costInput )
				.attr( "value" ) );							
	});		
	var packingCostInfo = calculatePackagesCost( selectors );
	
	var assocGoodsCost = parsePrice( $( s.allAssocGoodsCost ).attr( "value" ) );
	
	var totalCost = cost + packingCostInfo.cost + assocGoodsCost;
	
	$( s.allBaseCost ).attr( "value", priceToString( cost ) );
	$( s.allBaseCostCell ).text( priceToString( cost ) );
	
	$( s.allTotalCost ).attr( "value", priceToString( totalCost ) );
	$( s.allTotalCostCell ).text( priceToString( totalCost ) );
	
	$( s.allBackPackagesCost ).attr( "value", priceToString( packingCostInfo.cost ) );
	$( s.allBackPackagesCostCell ).text( priceToString( packingCostInfo.cost ) );
	
	$( s.allBackPackagesCount ).attr( "value", packingCostInfo.backPackagesCount );
	
	var metric = packingsMetric( packingCostInfo.count );
	metric = $( s.allBackPackagesCountMetricPrefix + metric ).attr( "value" );	
	$( s.allBackPackagesCountCell ).text( priceToString( packingCostInfo.count ) + metric );
	
}

function calculatePackagesCost( selectors )
{
	var s = selectors;
	var packagesCost = 0;
	var countPackages = 0;
	var backCountPackages = parseInt($( s.backPackagesCount ).attr( "value" ));
        
	$( s.backPackagesRowsCollectionLocator ).each( function()
	{
		countPackages += parseInt( 
			$( this )
				.find( s.quantity )
				.attr( "value" ) );
	});
	var countBuy = countPackages - backCountPackages;
	var packingPrice = parsePrice( $( s.allPackingPrice ).attr( "value" ) );
	
	var ret = 
	{
		count: countBuy,
		cost: countBuy * packingPrice,
		backPackagesCount: backCountPackages
	};
	
	return ret;
}

function itemValue( context, locator, mode, value )
{
	var item = $( locator );
	if ( context )
	{
		item = context.find( locator );	
	}
	
	var isGet = value ? false : true;
	if ( mode == "TEXT" && value )
	{
		item.text( value );
	}
	else if ( mode == "TEXT" )
	{
		value = item.text();
	}
	else if ( mode == "INPUT" && value )
	{
		item.attr( "value", value );
	}
	else
	{
		value = item.attr( "value" );
	}
	
	return isGet ? value : item;
}

$().ready( function()
{
	$( ".city-select select" ).change( function()
	{
		window.location.href = this.value;
	});
	
});

function bindSyncRowPrices( selectors )
{
	$().ready( function()
	{
		syncRowPrices( selectors );
	});	
}

function bindSyncTotalPrices( selectors )
{
	$().ready( function()
	{
		outputTotalPrice( selectors );
	});
}

function syncQuantitySelects( rowLocator, fromSelect, toSelect )
{
	fromSelect1 = $( "#item-1" ).find( fromSelect );
        fromSelect2 = $( "#item-2" ).find( fromSelect );
        fromSelect3 = $( "#item-3" ).find( fromSelect );
	toSelect = $( "#item-1" ).find( toSelect );
	var prevValue = toSelect.attr( "value" );
	toSelect.empty();
	var fromSelectValue = parseInt( fromSelect1.attr( "value" ) ) + 
                              parseInt( fromSelect2.attr( "value" ) ) +
                              parseInt( fromSelect3.attr( "value" ) );
	fromSelect1.find( "option" ).each( function()
	{
		if ( parseInt( this.value ) > parseInt( fromSelectValue ) )
		{
			return;
		}
		
		var newOpt = $( this ).clone();		
		toSelect.append( newOpt );
	});
        if (fromSelectValue == 0)
        {
            $( ".backPackagesCount" ).attr("disabled", "true");
        }
        else
        {
            $( ".backPackagesCount" ).attr("disabled", "");
        }
	toSelect.attr( "value", prevValue );
	if ( !toSelect.attr( "value" ) )
	{
		toSelect.attr( "value", toSelect.find("option:first").attr( "value" ) );
	}
}

function priceToString( price )
{
	price = ( Math.round( price * 100 ) / 100 ).toString();
	return price.replace( parsePrice.DEF_FLT_DELIM, parsePrice.FLT_DELIM );
}

function parsePrice( textPrice )
{
	var parts = textPrice.split( parsePrice.FLT_DELIM );
	return parseFloat( parts.join( parsePrice.DEF_FLT_DELIM ) );
}

parsePrice.DEF_FLT_DELIM = ".";
parsePrice.FLT_DELIM = parsePrice.DEF_FLT_DELIM;

function validateSubmit( formLocator, termsAgreedLocator, totalPriceLocator )
{
	if ( !$( termsAgreedLocator ).attr( "checked" ) )
	{
		window.alert( "Пожалуйста прочтите условия доставки воды" );
		return;
	}
	
	if ( parsePrice( $( totalPriceLocator ).attr( "value" ) ) == 0 )
	{
		window.alert( "Пожалуйста выберите продукцию, которую необходимо доставить" );
		return;
	}
	
	$( formLocator ).submit();
}

function validateContactSubmit( formLocator, radiosLocator, eMsg )
{
	if ( !$( formLocator ).validate().form() )
	{
		return;
	}
	
	if ( !atLeastOneChecked( radiosLocator ) )
	{
		alert( eMsg );
		return;
	}
	
	$( formLocator ).submit();
}

function atLeastOneChecked( radiosLocator )
{
	var checked = false;
	$( radiosLocator ).each( function()
	{
		checked = checked || this.checked;
	});
	return checked;
}

function bindPersonTypeChange( inputsLocator, organizationBlock, inputDisable )
{	
	$().ready( function()
	{
		$( inputsLocator ).change( function()
		{
			synchronizeOrganizationShow( inputsLocator, organizationBlock, inputDisable );
		});
		
		synchronizeOrganizationShow( inputsLocator, organizationBlock, inputDisable );
	});
}

function synchronizeOrganizationShow( inputsLocator, organizationBlock, inputDisable )
{
	var isShow = false;
	$( inputsLocator ).each( function()
	{
		if ( this.value == "1" && this.checked )
		{
			isShow = true;
		}
	});
	
	$( organizationBlock ).css( "display", isShow ? "" : "none" );
	$( inputDisable ).attr( "disabled", !isShow );
}


function packingsMetric( count )
{
	var decPart = count % 10;
	var tenPart = Math.floor( count / 10 ) % 10;
	
	var metric;
	if ( tenPart == 1 )
	{
		return "many-from";
	}
	else if ( decPart == 1 )
	{
		return "one";
	}
	else if ( decPart >= 2 && decPart <= 4 )
	{
		return "many";
	}
	return "many-from";
}


function openOrderConditionsPopup( url )
{
	window.open( url, 'photo_update', 
	[
		"height=560",
		"width=690",
		"top=50",
		"left=200",
        "location=1",
	]
	.join( "," ) );
}


function bindDatePlaceTime( dateControl, containerLocator, rangeLocatorPrefix )
{
	$().ready( function()
	{
		DateControl.onChange( dateControl, function( id, oldVal, newVal )
		{
			syncDeliveryTime( newVal, containerLocator, rangeLocatorPrefix );
		} );
		
		syncDeliveryTime( DateControl.getValue( dateControl ), containerLocator, rangeLocatorPrefix );
	});	
}

function syncDeliveryTime( val, containerLocator, rangeLocatorPrefix )
{
	var vals = val.split( "-" );
	var year = parseInt( vals[ 0 ] );
	var month = parseInt( vals[ 1 ], 10 ) - 1;
	var day = parseInt( vals[ 2 ], 10 );
	var date = new Date( year, month, day );
	
	var dayOfWeek = ( date.getDay() + 6 ) % 7;	
	
	var item = $( rangeLocatorPrefix + dayOfWeek );
	var cloned = item.clone();	
	$( containerLocator ).empty().append( cloned );
	
	cloned.find("input").each( function()
	{
		if ( $( this ).hasClass( "checked" ) )
		{
			this.checked = true;
		}
	});
}

function toggleAssocGoods( blockId, btnId, hideLnkId, onShowHandler, onHideHandler, params )
{
	var isShown = $( blockId ).attr( "isShown" );
	var blockDisplay = "block";
	var btnDisplay = "none";
	var hideLnkDisplay = "inline";
	var handler = onShowHandler; 
	if ( isShown )
	{
		blockDisplay = "none";
		btnDisplay = "inline";
		hideLnkDisplay = "none";
		handler = onHideHandler;
	}
	
	handler && handler( params );
	
	$( blockId ).css( "display", blockDisplay );
	$( btnId ).css( "display", btnDisplay );
	$( hideLnkId ).css( "display", hideLnkDisplay );
	
	$( blockId )[ 0 ].isShown = !isShown;	
}

function onShowAssocGoods( selectors )
{
	var origValue = $( selectors.allAssocGoodsCost ).attr( "origValue" );
	if ( typeof( origValue ) != "undefined" )
	{	
		$( selectors.allAssocGoodsCost ).attr( "value", origValue );
		outputTotalPrice( selectors );
	}
	
	$( selectors.allAssocGoodsCostContainer ).css( "display", "block" );
}

function onHideAssocGoods( selectors )
{
	var origValue = $( selectors.allAssocGoodsCost ).attr( "value" );
	$( selectors.allAssocGoodsCost ).attr( "origValue", origValue );
	$( selectors.allAssocGoodsCost ).attr( "value", 0 );
	outputTotalPrice( selectors );
	
	$( selectors.allAssocGoodsCost ).css( "display", "none" );
	$( selectors.allAssocGoodsCostContainer ).css( "display", "none" );	
}

function bindSyncAssocGoods( selectors )
{
	$().ready(function()
	{
		syncAssocGoods( selectors );				
	});
}

function syncAssocGoods( selectors )
{
	var row = $( selectors.rowLocator );
	var quantity = row.find( selectors.quantity ).attr( "value" );
	quantity = parseInt( quantity );
	var price = row.find( selectors.priceInput ).attr( "value" );
	price = parsePrice( price );
	var cost = price * quantity;
	var costStr = priceToString( cost );
	row.find( selectors.costInput ).attr( "value", costStr );		
	row.find( selectors.costCell ).text( cost > 0 ? costStr : selectors.priceNoneSign );
	
	outputTotalAssocGoods( selectors ); 
}

function outputTotalAssocGoods( selectors )
{
	var s = selectors;
	var totalCost = 0;
	$( s.assocGoodsRowsLocator ).each( function()
	{
		totalCost += parsePrice( $( this ).find( s.costInput ).attr( "value" ) );		
	});
	var costStr = priceToString( totalCost );	
	$( s.allAssocGoodsCost ).attr( "value", costStr );
	$( s.allAssocGoodsCostCell ).text( costStr );
	
	outputTotalPrice( selectors );
}