var quizDiscountConsider = false;

function resetPrices(selectors){
	if($('#no_calc').attr('checked')==false){
		outputTotalPrice(selectors);
		$('select[name^=order]').each(function (){
			var matches = $(this).attr('name').match(/order\[items\]\[(\d)*\]\[quantity\]/);
			
			if(matches!=null){
				var index=matches[1];
				syncPrices($.extend({rowLocator: '#item-'+index},window.totalSelectors ));
			}
		});
		return;
	}
	var s = selectors;
	
	$( s.allBaseCost ).attr( "value", priceToString( 0 ) );
	$( s.allBaseCostCell ).text( priceToString( 0 ) );
	
	$( s.allTotalCost ).attr( "value", priceToString( 0 ) );
	$( s.allTotalCostCell ).text( priceToString( 0 ) );
	
	$( s.allBackPackagesCost ).attr( "value", priceToString( 0 ) );
	$( s.allBackPackagesCostCell ).text( priceToString( 0 ) );
	
	$( s.allBackPackagesCount ).attr( "value", 0 );
	$( s.discountCell ).text(0);
	
	
	var row = $( selectors.rowsCollectionLocator );
	
	row.find( selectors.costCell ).text( selectors.priceNoneSign );
	
	return;
}

function syncPrices( selectors )
{
	if($('#no_calc').attr('checked')==true){
		return;
	}
	var s = selectors;
	quizDiscountConsider = false;

        s.rowLocator = s.item1;
	syncRowPrices( s );

        s.rowLocator = s.item2;
	syncRowPrices( s );

        s.rowLocator = s.item3;
	syncRowPrices( s );
	quizDiscountConsider = false;
        syncQuantitySelects( s.rowLocator, s.quantity, s.backPackagesCount );
       
	outputTotalPrice( s );
}

function syncRowPrices( selectors )
{
	var s = selectors;
	var considerOnlineDiscountForOneBottleWhenQuizDiscount = s.considerOnlineDiscountForOneBottleWhenQuizDiscount;
	var row = $( s.rowLocator );
	var quantityToBuy = parseInt( row.find( s.quantity ).attr( "value" ) );
	var allQuantityToBuy = 0;
	var quantity = 0;
	$( s.rowsCollectionLocator ).each( function()
	{
		quantity = parsePrice(
			$( this )
			.find( s.quantity )
			.attr( "value" ) );
		allQuantityToBuy += quantity;
	} );
	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;
	

	var hasQuizDisount = false;
	var discountValue = 0;
	$( s.discountSelector ).each( function()
	{
		if ( $( this ).attr( "checked" ) )
		{
			discountValue += parsePrice( $( "#" + $( this ).attr( "ref" ) ).text() );
			hasQuizDisount = true;
		}
	} );
	if($( s.discountSelector2 ).length){
		$( s.discountSelector2 ).each( function()
		{
			if ( $( this ).attr( "checked" ) )
			{
				discountValue += parsePrice( $( "#" + $( this ).attr( "ref" ) ).text() );
				hasQuizDisount = true;
			}
		} );
	}

	if ( !considerOnlineDiscountForOneBottleWhenQuizDiscount
		&& hasQuizDisount
		&& allQuantityToBuy >= discountBottles
		&& !quizDiscountConsider
		&& cost > 0 )
		{
		cost += 10;
		quizDiscountConsider = true;
	}
	
	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;
	var discountValue = 0;
	var freeBottles = 0;
	var allQuantityToBuy = 0;
	var discountBottles = 2;
	$( s.rowsCollectionLocator ).each( function()
	{
		cost += parsePrice( 
			$( this )
				.find( s.costInput )
				.attr( "value" ) );							
	});
	
	var packingCostInfo = calculatePackagesCost( selectors );
	
	var assocGoodsCost = parsePrice( $( s.allAssocGoodsCost ).attr( "value" ) );
	
	$( s.rowsCollectionLocator ).each( function()
	{
		allQuantityToBuy += parsePrice(
			$( this )
				.find( s.quantity )
				.attr( "value" ) );
	});
	var row = $( s.rowLocator );
	
	$( s.discountSelector ).each( function()
	{
		if ( $( this ).attr( "checked" ) )
		{
			if ( $( this ).hasClass( s.freeBottles ) )
			{
				freeBottles += parsePrice( $( "#" + $( this ).attr( "ref" ) ).text() );
			}
			else
			{
				discountValue += parsePrice( $( "#" + $( this ).attr( "ref" ) ).text() );
			}
		}
	} );
	if($( s.discountSelector2 ).length){
		$( s.discountSelector2 ).each( function()
		{
			if ( $( this ).attr( "checked" ) )
			{
				if ( $( this ).hasClass( s.freeBottles ) )
				{
					freeBottles += parsePrice( $( "#" + $( this ).attr( "ref" ) ).text() );
				}
				else
				{
					discountValue += parsePrice( $( "#" + $( this ).attr( "ref" ) ).text() );
				}
			}
		} );
	}

	if($(s.onlineDiscount).val()>0 && $(s.fromAccount).val() == 0){
		discountValue += parseInt($(s.onlineDiscount).val());
	}

	
	if ( 0 && ( discountValue != 0 ) && ( allQuantityToBuy >= discountBottles ) )
	{
		var onlineDeliveryDiscount = 10;
		discountValue -= onlineDeliveryDiscount;
	}
	if($(s.discountInvitePrice).val()>0){
		discountInvite = Math.round((cost + packingCostInfo.cost + assocGoodsCost - discountValue)/2);
		discountValue += discountInvite;
	}
	if($(s.birthDay).val()==1){
		discountBirthday = Math.round((cost + packingCostInfo.cost + assocGoodsCost - discountValue)/4);
		$( s.discountBirthday ).text( priceToString( discountBirthday ) );
		discountValue += discountBirthday;
	}
	var discountOutput = discountValue;
	var totalCost = 0;
	if($(s.birthDay).val()==1){
		discountOutput -= discountBirthday;
	}
	totalCost = cost + packingCostInfo.cost + assocGoodsCost - discountValue;
	
	if ( totalCost < 0 )
	{
		totalCost = 0;
		$( s.discountCell ).text( priceToString( 0 ) );
	}
	else
	{
		$( s.discountCell ).text( priceToString( discountOutput ) );
	}
	
	$( 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 )
{
	return false;
	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()
{
	return false;
	$( ".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 bindResetPrices( selectors )
{
	$().ready( function()
	{
		setTimeout(function(){
			resetPrices( selectors )	
		},1000);
	});
}

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 )
function validateSubmit( formLocator, termsAgreedLocator, orderSelectsLocator )
{
	var selected = false;
	$(orderSelectsLocator).each(function(){
		if($(this).val() > 0) selected = true;
	});
	
	if (!selected)
	{
		window.alert( "Пожалуйста выберите продукцию, которую необходимо доставить" );
		return;
	}
	
	if ( !$( termsAgreedLocator ).attr( "checked" ) )
	{
		window.alert( "Пожалуйста прочтите условия доставки воды" );
		return;
	}
	

	
	$( formLocator ).submit();
}

function validateContactSubmit( formLocator, radiosLocator, eMsg )
{
	if ( !$( formLocator ).validate().form() )
	{
		return;
	}
	
	if ( !atLeastOneChecked( radiosLocator ) )
	{
		alert( eMsg );
		return;
	}
	
	$( formLocator ).submit();
	$("#loader").removeClass("hidden");
	$(".blue-button").addClass("unactive-btn").attr("onClick", "");
}

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 );
}

var banner_no=0;

function bindRotateBanners(source_banners_loc,destination_loc,delay){
	$().ready(function()
	{
		source = $(source_banners_loc);
		destination = $(destination_loc);
		delay = delay*1000;
		banners_count = source.length
		rotateBanners( source,destination,banners_count);
		setInterval(function(){
			rotateBanners( source,destination,banners_count);
		},delay);
	});
}


function rotateBanners( source,destination,banners_count){
	
	if(banner_no<banners_count){
		destination.html(source.eq(banner_no).html());
		banner_no++;
	}else{
		banner_no=0
	}
	return;
}
