//----------------------------------------------------------------------------------------
//---------------
$(
	function()
	{
	    ORDER_OK_FLAG = false;
	    //Переход на стр. товара для ИЕ при клике по картинке
		if($.browser.msie){
		    $("ul.category-products li.item a.product-img").click(
			function()
			{
			    location.href = $('a.product-name', $(this).parents('li.item')).attr('href');
			}
		    );
		}

		$('body').click (
		    function(){
                        $('.product-filters').hide();
		    }
		);
		    
		$('#showSidebar, .hidemenu').click(
		    function(e){
			e.stopPropagation();
			$('.sidebar').slideToggle('slow', function() {
			    if( !$('.sidebar').is(':visible') )
			    {
				$.cookie( 'sidebar-display', 'none', {expires: 14, path: '/'});
			    }
			    else
			    {
				$.cookie( 'sidebar-display', 'block', {expires: 14, path: '/'});
			    }
			});
		    }
		);
/*
		$('.sidebar').click (
		    function(e){
			e.stopPropagation();;
		    }
		);
                */
                $('#showFilters span').click(
		    function(e){
			e.stopPropagation();
			$('.product-filters').slideToggle('fast', function() {});
		    }
		);
                    
                $('.product-filters').click (
		    function(e){
			e.stopPropagation();;
		    }
		);

		    $('div.sidebar li.main-category').click(
		    function(){
			var currElem = $(this);
			if( !currElem.hasClass('main-categoryactive') )
			{
			    $('li.main-category-active', currElem.parent()).removeClass('main-category-active');
			    currElem.addClass('main-category-active');

			    $('div.sidebar div.categories-cont ul.bands-menu-active').removeClass('bands-menu-active');

			    var currIndex = $('div.sidebar li.main-category').index(currElem);
			    $('div.sidebar div.categories-cont ul.bands-menu:eq('+currIndex+')').addClass('bands-menu-active');

			}
		    }
		);
		
		$('#moscowDelivery').click(
		    function()
		    {
			$('.msk-only').show();
			$('.russia-only').hide();
			$('#' + metroId).click();
		    }
		 );
		$('#russiaDelivery').click(
		    function()
		    {
			$('.msk-only').hide();
			$('div.textarea-label label span.self-delivery-only').hide();
			$('.russia-only').show();
			$('#' + russiaId).click();
		    }
		);
		    
		if( ( typeof(metroId) != 'undefined') && ( typeof(addressId) != 'undefined') )
		{
		    $('#' + metroId).click();
		    $('#' + metroId).click(
			function()
			{
			    $('div.metro-stations').show();
			    $('div.textarea-label label span.msk-only').show();
			}
		    );

		    $('#' + addressId).click(
			function()
			{
			    $('div.metro-stations').hide();
			    $('div.textarea-label label span').hide();
			    $('div.textarea-label label span.msk-only').show();
			}
		    );
		}
		if( ( typeof(selfDeliveryId) != 'undefined'))
		{
		    $('#' + selfDeliveryId).click(
			function()
			{
			    $('div.metro-stations').hide();
			    $('div.textarea-label label span').hide();
			    $('div.textarea-label label span.self-delivery-only').show();	
			}
		    );
		}

		$("#orderForm").submit(
		    function ()
		    {	
			process_order_form();
			return ORDER_OK_FLAG;
		    }
		);
	       $("#orderForm button.submit").click(
		    function ()
		    {
			$("#orderForm").submit();
		    }
		);

		$( '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');
			}
		    }
		);
		
		$('a.buy-button').click(
		    function()
		    {
			var currButton = $(this).parent();
                        
                        if( currButton.hasClass('in-basket') )
                        {
                            location.href = '/order/';
                            return;
                        }

			if( $('div.product-page ul.product-sizes li.active').length )
			{
			    if( !currButton.hasClass('av-preorder') && !currButton.hasClass('av-no') && !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');
			    }
			}
			else {
			    alert('Пожалуйста, выберите размер!')
			}
		    }
		);
		
		$('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);
			}

		    }
		);

		$('div.product-filters a.in-stock').click(
		    function(){
			var parentCont = $(this).parent().parent();

			if( !parentCont.hasClass('active') )
			{
			    $.cookie( 'availability_filter', 'yes', {expires: 365, path: '/'} );
			    location.reload();
			}
			
		    }
		);
		$('div.product-filters a.all-products').click(
		    function(){
			var parentCont = $(this).parent().parent();

			if( !parentCont.hasClass('active') )
			{
			    $.cookie( 'availability_filter', null, {path: '/'} );
			    $.cookie( 'sizes_filter', null, {path: '/'} );
			    location.reload();
			}
		    }
		);
		$('div.product-filters div.size-filter a.size-filter').click(
		    function(){
			var parentCont	= $(this).parent().parent();
			var currSize	= $(this).attr('id');
			var activeSizes = $('div.product-filters div.size-filter li.active a');

			activeSizesFilter = '';
			for(var i=0; i < activeSizes.length; i++)
			{
			    activeSizesFilter += activeSizes.eq(i).attr('id');
			}

			if( parentCont.hasClass('active') )
			{
			    activeSizesFilter = activeSizesFilter.replace(currSize,'');
			}
			if( !parentCont.hasClass('active') )
			{
			    activeSizesFilter += currSize;
			}

			$.cookie( 'sizes_filter', activeSizesFilter, {path: '/'} );
			location.reload();
		    }
		);
                $("#SELECT").selectBox();
                $('ul.selectBox-options li').each(function(index){
                    $(this).addClass($("#SELECT option.eq("+index+")").attr('class'));
                });
                
                $( "#dialog-form" ).dialog({
			autoOpen: false,
			height: 255,
			width: 330,
			modal: true,
                        draggable: false,
                        resizable: false,
			buttons: {
				"Окей": function() {
	
                                        var nameStatus = checkName($('input.pre-name', this));
                                        var mailStatus = checkMail($('input.pre-email', this));
                                        
					if ( nameStatus && mailStatus ) 
                                        {
					    infoMsg('Секундочку..', false);
                                            $.post( '/basket/ajaxAddPreorder', {name: $('input.pre-name', this).val(), email: $('input.pre-email', this).val(), size: $('select.pre-size', this).val(), product: location.href},
                                                function ( data )
                                                {
						    if(data)
						    {
							infoMsg('Спасибо, мы свяжемся с Вами!', true);
						    }
						    else
						    {
							infoMsg('Мы помним про Вас!', true);
						    }
                                                },
                                                'json'
                                            );

					    
                                            $( this ).dialog( "close" );
					}
				},
				"Отмена": function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				
			}
		});

		$( "#needSize" )
			.click(function() {
				$( "#dialog-form" ).dialog( "open" );
			});
                
		VK.init({apiId: 2135409, onlyWidgets: 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 )
		{
                    infoMsg('Этот товар уже есть в корзине!', true);
		    prodAlreadyInCart = true;
		    break;
		}
	    }
	    else
	    {
		    result.push( products[i] );
	    }
	}
	if( !prodAlreadyInCart )
	{
            infoMsg('Секундочку..', false);
	    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');
                    infoMsg('Товар добавлен в корзину!', true);
		},
		'json'
	    );
	}
	
	return false;
}

//----------------------------------------------------------------------------------------
//Информационные сообщения
function infoMsg(msgText, hide)
{
   var msg = $('#infoMsg'); 
   msg.text(msgText).show();
   if( hide )
   {
        setTimeout(function(){$('#infoMsg').hide()}, 2000); 
   }
}

//----------------------------------------------------------------------------------------
//Очистка корзины
function clearCart(refresh)
{
    infoMsg('Секундочку...', false);
    $('a.in-basket').removeClass('in-basket');
    $('.basket-cont').addClass('no-products');
    $.post( '/basket/ajax_clear_basket', 
        function(){
            infoMsg('Корзина очищена.', true);
            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()
{
    var russiaView = $('#order_surname').is(':visible') && $('#order_surname').is(':visible');
    var checkBlock = $('div.order-check');
    
    if( !checkName($('#order_name')) || !checkPhone($('#order_phone')) || !checkMail($('input.email')) )
    {
	    $('.error-message').show();
	    ORDER_OK_FLAG = false;
    }
    else
    {
	if( russiaView ) //RUSSIA_view
	{
	    if( checkName($('#order_surname')) && checkName($('#order_patronymic')) && checkPostIndex($('#order_post_index')))
	    {
		$('div.russia-check').show();
		$('div.moscow-check').hide();

		$('.error-message').hide();
		$('span.check-person-surn', checkBlock).text( $('#order_surname').val() );
		$('span.check-person', checkBlock).text( $('#order_name').val() );
		$('span.check-person-patronymic', checkBlock).text( $('#order_patronymic').val() );
		$('span.check-phone', checkBlock).text( $('#order_phone').val() );
		$('span.check-email', checkBlock).text( $('input.email').val() );
		$('span.check-post-index', checkBlock).text( $('#order_post_index').val() );

		$('div.address-check span.check', checkBlock).text( $('div.order-delivery-info textarea').val() );

		checkBlock.modal();
		$('a.check-ok').click(
		    function(){
			ORDER_OK_FLAG = true;
			$('#orderForm').submit();
		    }
		);
	    }
	}
	else //MOSCOW_view
	{
	    $('div.russia-check').hide();
	    $('div.moscow-check').show();

	    $('.error-message').hide();
	    $('span.check-person', checkBlock).text( $('#order_name').val() );
	    $('span.check-phone', checkBlock).text( $('#order_phone').val() );
	    $('span.check-email', checkBlock).text( $('input.email').val() );
	    $('span.metroStation', checkBlock).text( $('#selectdelivery_metro').text() );
	    $('div.address-check span.check', checkBlock).text( $('div.order-delivery-info textarea').val() );

	    checkBlock.modal();
	    $('a.check-ok').click(
		function(){
		    ORDER_OK_FLAG = true;
		    $('#orderForm').submit();
		}
	    );

	}
    }
    return false;
}
//-------------------------------------------------------
//телефон
function checkPhone( obj )
{
    var str = obj.val();
    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))
    {
	obj.css('border', '1px solid #ccc');
	return true;
    }
    else
    {
	obj.css('border', '1px solid red').focus();
	return false;
    }
};

//-------------------------------------------------------
//e-mail
function checkMail( obj )
{
    var str = obj.val();
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
    if (filter.test(str))
    {
	obj.css('border', '1px solid #ccc');
	return true;
    }
    else
    {
	obj.css('border', '1px solid red').focus();
	return false;
    }
}
//-------------------------------------------------------
//e-mail
function checkPostIndex( obj )
{
    var str = obj.val();
    var filter=/^(\d{6})$/i;
    if (filter.test(str))
    {
	obj.css('border', '1px solid #ccc');
	return true;
    }
    else
    {
	obj.css('border', '1px solid red').focus();
	return false;
    }
}
//-------------------------------------------------------
//e-mail
function checkName( obj )
{
    var str = obj.val();
    var filter=/^[А-Я]+$/i;
    if (filter.test(str))
    {
	obj.css('border', '1px solid #ccc');
	return true;
    }
    else
    {
	obj.css('border', '1px solid red').focus();
	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;
