//----------------------------------------------------------------------------------------
//---------------
$(
	function()
	{
		$('#moscowDelivery').click();
		
		$('#moscowDelivery').click(
				function()
				{
					$('.msk-only').show();
					$('.russia-only').hide();
					$('#' + metroId).click();
				}
			);
			$('#russiaDelivery').click(
				function()
				{
					$('.msk-only').hide();
					$('.russia-only').show();
					$('#' + russiaId).click();
				}
			);
		if( ( typeof(metroId) != 'undefined') && ( typeof(addressId) != 'undefined') )
		{
			$('#' + metroId).click();
			$('#' + metroId).click(
				function()
				{
					$('div.metro-stations').show();
				}
			);

			$('#' + addressId).click(
				function()
				{
					$('div.metro-stations').hide();
				}
			);
		}
		$('#orderForm button.submit').click(process_order_form);

		$( 'img.additional-image' ).click( 
			function()
			{
				$( 'img#main' ).attr( 'src', $( this ).attr( 'altsrc' ) );
			}
		);
		
		$('div.category a.buy-button').click(
			function()
			{
				var currButton = $(this);
				
				if( !currButton.hasClass('in-basket') )
				{
					var currProductId = currButton.attr('id').replace('buy_', '');
					currButton.addClass('in-basket');
					addProductToCart( currProductId, 'NULL' );
				}
			}
		);
		
		$('#clearCart').click(
			function()
			{
				clearCart();
			}
		);
		
		/** Сраница товара **/
		
		$('div.product-page #thumbsImg li').click(
			function()
			{
				var currThumb = $(this);
				
				if( !currThumb.hasClass('current') )
				{
					var thumbsC			= currThumb.parent();
					var bigImgsC		= $('#bigImg ul');
					var currThumbIndex	= $('li', thumbsC).index(currThumb);
					$('li.current', thumbsC).removeClass('current');
					currThumb.addClass('current');
					
					$('li.current', bigImgsC).removeClass('current');
					$('li:eq(' + currThumbIndex + ')', bigImgsC).addClass('current');
				}
			}
		);
		
		$('div.product-page a.buy-button').click(
			function()
			{
				var currButton = $(this).parent();
				
				if( !currButton.hasClass('av-preorder') && !currButton.hasClass('in-basket') )
				{
					var currProductId = $('a.buy-button', currButton).attr('id').replace('buy_', '');
					var currProductSizeC = $('ul.product-sizes li.active');
					var currProdSizeName = ( currProductSizeC.length ) ? currProductSizeC.attr('id').replace('size_', '') : 'NULL';
					
					addProductToCart( currProductId, currProdSizeName );
					currButton.addClass('in-basket');
					
					$('li', currProductSizeC.parent()).removeClass('in-cart');
					currProductSizeC.addClass('in-cart');
				}
			}
		);
		
		$('div.product-page ul.product-sizes li').click(
			function()
			{
				var currSize	 = $(this);
				if( !currSize.hasClass('active') )
				{
					$('li', currSize.parent()).removeClass('active');
					currSize.addClass('active');
					if( !currSize.hasClass('in-cart') )
					{
						$('div.product-page a.buy-button').parent().removeClass('in-basket');
					}
					else
					{
						$('div.product-page a.buy-button').parent().addClass('in-basket');
					}
				}
				
			}
		);
		
		$('td.amount select').change(
			function()
			{
				calcCart();
			}
		);
		
		//Пересчитываем корзину
		calcCart();
		
		$('div.cart .remove-product a').click(
			function()
			{
				var currProductC	= $(this).parents('tr');
				var currProductId	= currProductC.attr('id').replace('product_', '');
				
				//Удаляем продукт из кук
				var products		= [];
				var cookie			= $.cookie( 'products' );
	
				if( cookie != null )
				{
					products = cookie.split(',');
				}
				
				for( var i=0; i<products.length; i++)
				{
					if( products[i].indexOf(currProductId + '_') != -1 )
					{
						products.splice(i, 1);
					}
				}
				/* */
				
				currProductC.hide('300', 
					function()
					{ 
						currProductC.remove();
						
						//Пересчитываем итог
						calcCart();
						
						$.cookie( 'products', products.join( ',' ), { expires: 14, path: '/' } );
						$.post( '/basket/ajax_get_basket', {}, 
							function ( data )
							{
								setBasketInfo( data );
								$('.basket-cont').removeClass('no-products');
								
							},
							'json'
						); 
				
					} 
				);
				
				if( !products.length )
				{
					clearCart(true);
				}
				
			}
		);

}
	
);

//----------------------------------------------------------------------------------------
//Добавление товара в корзину
function addProductToCart( productId, sizeName )
{
	var products			= [];
	var result				= [];
	var cookie				= $.cookie( 'products' );
	var prodAlreadyInCart	= false;
	
	if( cookie != null )
	{
		products = cookie.split(',');
	}
	
	for ( var i = 0; i < products.length; i++ )
	{
		var currProdInfo		= products[i].split('_');
		var currProdId			= currProdInfo[0];
		var currProdSizeName	= currProdInfo[1];
		
		if( productId == currProdId )
		{
			if( currProdSizeName == sizeName )
			{	
				alert('Товар уже в корзине');
				prodAlreadyInCart = true;
				break;
			}
		}
		else
		{
			result.push( products[i] );
		}
	}
	if( !prodAlreadyInCart )
	{
		result.push( productId + '_' + sizeName );
				
		$.cookie( 'products', result.join( ',' ), { expires: 14, path: '/' } ); 

		$.post( '/basket/ajax_get_basket', {}, 
			function ( data )
			{
				setBasketInfo( data );
				$('.basket-cont').removeClass('no-products');
			},
			'json'
		);
	}
	
	return false;
}

//----------------------------------------------------------------------------------------
//Очистка корзины
function clearCart(refresh)
{
	$('a.in-basket').removeClass('in-basket');
	$('.basket-cont').addClass('no-products');
	$.post( '/basket/ajax_clear_basket', function(){ if( refresh ) { location.href = ''; } } );
}

//----------------------------------------------------------------------------------------
//Пересчет корзины
function calcCart()
{
	var productsC = $('table.cart-products tr.product');
	var currPrice, currAmount, totSum = 0;
	var currProductC = '';
	
	for( var i=0; i<productsC.length; i++ )
	{
		currProductC	= productsC.eq(i);
		currPrice		= $('td.price span', currProductC).text();
		currAmount		= $('td.amount select', currProductC).val();
		totSum	   	   += currPrice*currAmount;
	}
	
	$('.total-sum').text(totSum);
}
//----------------------------------------------------------------------------------------
//---------------
function change_product_count( product_id, el )
{
	var count = parseInt( $( el ).val() );
	add_product( product_id, count, false );
}

//----------------------------------------------------------------------------------------
//Пишет состояние корзины в хедер
function setBasketInfo( info )
{
	var num			= info.products_count.toString();
	var	count		= num;
	var	strLength	= count.length;
		
	if( strLength >=2 )
	{
		count = count.substring(strLength-2, strLength);
		if( ( count >= 10 ) && ( count < 20 ) )
		{
			word = 'футболок';
		}
		else
		{
			count = count.substring(count.length-1, count.length);
			
			if( count == 1 )
			{
				word = 'футболка';
			}
			if( ( count >= 2 ) && ( count <= 4 ) )
			{
				word = 'футболки';
			}
			if(  ( ( count >= 5 ) && ( count <= 9 ) ) || ( count == 0 ) )
			{
				word = 'футболок';
			}
		}
	}
	else
	{
			count = count.substring(count.length-1, count.length);
			if( count == 1 )
			{
				word = 'футболка';
			}
			if( ( count >= 2 ) && ( count <= 4 ) )
			{
				word = 'футболки';
			}
			if( ( count >= 5 ) && ( count < 9 ) || ( count == 0 ) )
			{
				word = 'футболок';
			}
	}
	
	$( '#baskProdCount' ).html( num );
	$( '#baskTotalPrice' ).html( info.total_price.toString() + '&nbsp;Р' );
	$( '#countWord' ).html( word );
}

//----------------------------------------------------------------------------------------
//---------------
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 process_order_form()
{
	if( ( !checkPhone( $('#order_phone').val() ) ) || ( !checkMail( $('input.email').val() ) ) )
	{
		$('.error-message').show();	
		$('#order_phone').css('border', '1px solid red').focus();
		$('input.email').css('border', '1px solid red');
		return false;
	}
	else
	{
		$('.error-message').hide();
		$('#orderForm').submit();
	}
}
//-------------------------------------------------------
//телефон
function checkPhone( str )
{
	var filter=/^(\+?(\d{1})?( )?\(?\d{1} ?\d{2}(\d{1})?\)? ?\d{1}-? ?\d{1}-? ?\d{1}-? ?(\d{1})?-? ?(\d{1})?-? ?(\d{1})?-? ?(\d{1})?)$/;
	if (filter.test(str))
	{
		return true;
	}
	else { return false; }
};

//-------------------------------------------------------
//e-mail
function checkMail( str )
{
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if (filter.test(str))
	{
		return true;
	}
	else { return false; }
}
//-------------------------------------------------------
//e-mail
function checkPostIndex( str )
{
	var filter=/^(\d{1})$/i;
	if (filter.test(str))
	{
		return true;
	}
	else { return false; }
}


//----------------------------------------------------------------------------------------
// JavaScript Document
function shw_hd_sbmn(obj) 
{
	if (document.getElementById(obj).style.display == 'none') 
	{
		document.getElementById(obj).style.display = 'block';
	} 
	else 
	{
		document.getElementById(obj).style.display = 'none';
	}
}

//----------------------------------------------------------------------------------------	
function change_brand(cat_id) 
{
	for (i=1; i<5; i++) 
	{
		document.getElementById('brnd0'+i).className = '';
		document.getElementById('cat0'+i).style.display = 'none';
	}
	
	document.getElementById('brnd0'+cat_id).className = 'selected';
	document.getElementById('cat0'+cat_id).style.display = 'block';
}

//----------------------------------------------------------------------------------------
function show_desc(obj) 
{
	if ( document.getElementById(obj).style.display == 'none' ) 
	{
		document.getElementById(obj).style.display = 'block';
	} 
	else 
	{
		document.getElementById(obj).style.display = 'none';
	}
}


//Модные и красивые элементы форм (радиокнопки, выпадающие списки, чекбоксы)
var checkboxHeight = "25";
var radioHeight = "25";
var selectWidth = "5";

document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; opacity: 0; filter: alpha(opacity=0); z-index: 5; }</style>');

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
		var my_span = Array();
		for(a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
				span[a] = document.createElement("span");
				span[a].className = inputs[a].type;

				if(inputs[a].checked == true) {
					if(inputs[a].type == "checkbox") {
						position = "0 -" + (checkboxHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					} else {
						position = "0 -" + (radioHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					}
				}
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.clear;
				span[a].onmousedown = Custom.pushed;
				span[a].onmouseup = Custom.check;
				document.onmouseup = Custom.clear;
			}
		}
		inputs = document.getElementsByTagName("select");
		for(a = 0; a < inputs.length; a++) {
			if(inputs[a].className == "styled") {
				option = inputs[a].getElementsByTagName("option");
				active = option[0].childNodes[0].nodeValue;
				textnode = document.createTextNode(active);
				for(b = 0; b < option.length; b++) {
					if(option[b].selected == true) {
						textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
					}
				}
				span[a] = document.createElement("span");
				span[a].className = "select";
				span[a].id = "select" + inputs[a].name;
				span[a].appendChild(textnode);
				
				my_span[a] = document.createElement("span");
				my_span[a].className = "wr-span";
				my_span[a].appendChild(span[a]);
				
				inputs[a].parentNode.insertBefore(my_span[a], inputs[a]);
				$(inputs[a]).width($(my_span[a]).width()+8)
				inputs[a].onchange = Custom.choose;
			}
		}
	},
	pushed: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
		} else if(element.checked == true && element.type == "radio") {
			this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
		} else if(element.checked != true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
		} else {
			this.style.backgroundPosition = "0 -" + radioHeight + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			if(element.type == "checkbox") {
				this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else {
				this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
				group = this.nextSibling.name;
				inputs = document.getElementsByTagName("input");
				for(a = 0; a < inputs.length; a++) {
					if(inputs[a].name == group && inputs[a] != this.nextSibling) {
						inputs[a].previousSibling.style.backgroundPosition = "0 0";
					}
				}
			}
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
			if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			} else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
			} else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			}
		}
	},
	choose: function() {
		option = this.getElementsByTagName("option");
		for(d = 0; d < option.length; d++) {
			if(option[d].selected == true) {
				document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
			}
		}
	}
}
window.onload = Custom.init;