function add_product( product_id, count, auto_increment )
{
	if ( count == null ) count = 1;
	if ( auto_increment == null ) auto_increment = true;
	
	var products = [];
	var result = [];

	var cookie = $.cookie( 'products' );
	
	if ( cookie != null ) 
		products = cookie.split(',');

	var found = false;
	
	for ( var i = 0; i < products.length; i++ )
	{
		product = products[i].split('x');

		var current_product_id = product[0];
		var product_count = 1;
		
		if ( product[1] )
			product_count = Number( product[1] );
			
		if ( product[0] && product[0] == product_id )
		{
			if ( auto_increment )
				product_count = product_count + count;
			else
				product_count = count;
			
			found = true;
		}

		if ( product_count > 1 )
			result.push( current_product_id + 'x' + product_count );
		else if ( product_count == 1 )
			result.push( current_product_id );
	}
	
	if ( ! found )
	{
		if ( count > 1 )
			result.push( product_id + 'x' + count );
		else if ( count == 1 )
			result.push( product_id );
	}
	
	$.cookie( 'products', result.join( ',' ), { expires: 14, path: '/' } ); 

   	show_confirm_message( 'Товар добавлен в корзину' );

	$.post( '/basket/ajax_get_basket', {}, 
		function ( data )
		{
			set_basket_info( data );
		},
		'json'
	);
	
	return false;
}

function change_product_count( product_id, el )
{
	var count = parseInt( $( el ).val() );
	add_product( product_id, count, false );
}

function remove_product_from_basket( product_id, el )
{
	if ( ! confirm( 'Вы действительно хотите убрать товар из корзины?' ) ) return;
	
	add_product( product_id, 0, false ); 
	var row = $( el ).parent().parent();

	row.slideUp( 300, 
		function() 
		{
			row.remove();
		}
	);
}

function set_basket_info( info )
{
	$( 'span.products span.count' ).html( info.products_total_count + ' ' + morphology( info.products_total_count, 'товар', 'товара', 'товаров' ) );
	$( 'span.products span.price' ).html( info.total_price.toString() );

	if ( info.products_total_count > 0 )
	{
		$( 'span.products.ordering' ).removeClass( 'hidden' );
		$( 'p.helper.ordering' ).removeClass( 'hidden' );

		$( 'span.products.empty' ).addClass( 'hidden' );
		$( 'p.helper.empty' ).addClass( 'hidden' );
	}
	else
	{
		$( 'span.products.ordering' ).addClass( 'hidden' );
		$( 'p.helper.ordering' ).addClass( 'hidden' );
		
		$( 'span.products.empty' ).removeClass( 'hidden' );
		$( 'p.helper.empty' ).removeClass( 'hidden' );
	}
}

function search_by_price()
{
	var from = $( 'input#search_price_from' ).val();
	var to = $( 'input#search_price_to' ).val();
	
	window.location = '/search/product/pricefrom/' + from + '/priceto/' + to + '/';
}

function search_by_text()
{
	var text = $( 'input#search_text' ).val();
	
	window.location = '/search/product/name/' + text + '/';
}

function category_products_by_price()
{
	var to = $( 'input#category_price_to' ).val();
	
	window.location = $category_url + 'priceto/' + to + '/';
}

function check_order_form()
{
	if ( $( '#order_name' ).val() == '' )
	{
		alert( 'Необходимо указать имя' );
		$( '#order_name' ).focus();

		return false;
	}

	if ( $( '#order_phone' ).val() == '' )
	{
		alert( 'Необходимо указать контактный телефон' );
		$( '#order_phone' ).focus();

		return false;
	}

    if ( $( '#order_email' ).val() == '' )
    {
        alert( 'Необходимо указать электронную почту' );
        $( '#order_email' ).focus();

        return false;
    }

	if ( $( '#order_address' ).val() == '' )
	{
		alert( 'Необходимо указать адрес доставки' );
		$( '#order_address' ).focus();

		return false;
	}

	return true;
}

function show_confirm_message( message )
{
    if ( $( '#order_confirm_message' ).length > 0 )
    {
		$( '#order_confirm_message .message' ).text( message );
	    $( '#order_confirm_message' ).modal({
	        opacity: 60,
		    overlayCss: { backgroundColor: "#fff" }
	    });
    }
}

function morphology( $digital, $for_1, $for_2, $for_5 )
{
	$digital = $digital % 100;

	if ( $digital > 19 )
		$digital = $digital % 10;

	if ( $digital == 0 ) return $for_5;
	if ( $digital == 1 ) return $for_1;

	if ( ( $digital >= 2 ) && ( $digital <= 4 ) ) return $for_2;
	if ( ( $digital >= 5 ) && ( $digital <= 19 ) ) return $for_5;

	return $for_1;
}

$(
	function()
	{
		$( 'img.thumbnail' ).click(
			function()
			{
				$( 'div#image span img' ).attr( 'src', $( this ).attr( 'altsrc' ) );
			}
		)

		$( '#search_form input' ).keypress(
			function ( e )
			{
			  if ( e.which == 13 )
				$( '#search_form button' ).click();
			}
		);

		$( '#search_form button' ).click(
			function()
			{
				var text = $( '#search' ).val();
				if ( text != '' )
					window.location.href = 'search/product/name/' + text + '/';

				return false;
			}
		)

		$( '#search_form .example a' ).click(
			function()
			{
				var text = $( this ).text();
				$( '#search' ).val( text );

				return false;
			}
		)

		$( 'button.action.filter.category' ).click(
			function()
			{
				var $tag_id = $( '#filter_tags' ).val();
				var $category_id = $( '#filter_subcategories' ).val();
				var $producer_id = $( '#filter_producers' ).val();
				
				var $url = '';
				
				if ( $tag_id && $tag_id > 0 )
					$url = $url + 'tag/' + $tag_id + '/';
				
				if ( $producer_id && $producer_id > 0 )
					$url = $url + 'producer/' + $producer_id + '/';

				if ( $category_id != 0 && typeof( $category_id ) != 'undefined' )
					$url = '/category/' + $category_id + '/' + $url;
				else
					$url = '/category/' + $selected_category_id + '/' + $url;
				
				document.location.href = $url;
			}
		)

		$( 'button.action.filter.special' ).click(
			function()
			{
				var $producer_id = $( '#filter_producers' ).val();

				var $url = '/special/offer/';

				if ( $producer_id != 0 && $producer_id != 'undefined' )
					$url = $url + 'producer/' + $producer_id + '/';

				document.location.href = $url;
			}
		)

		$( 'button.action.filter.popular' ).click(
			function()
			{
				var $producer_id = $( '#filter_producers' ).val();

				var $url = '/popular/products/';

				if ( $producer_id != 0 && $producer_id != 'undefined' )
					$url = $url + 'producer/' + $producer_id + '/';

				document.location.href = $url;
			}
		)

		//Превью изображений на странице товара
		$('div.thumbnails ul li').click(
			function()
			{
				var currLi = $(this);
				if( !currLi.hasClass('active') )
				{
					$('li.active', currLi.parent()).removeClass('active');
					currLi.addClass('active');
					$('div.big-image span img').attr('src', $('input', currLi).val());
					$('div.big-image span img').attr('big', $('input', currLi).attr('big'));
				}
			}
		);
	}
);
