
$(function() {

/*
	Odnoklassniki auth
*/
ODKL.init();

$('#navigation div').hide();

$("a[rel^='prettyPhoto']").prettyPhoto({'theme': 'facebook'});

        if($.cookie('default_nav') == 'right') {
			$('#tab2').css('background','url(/img/tab2_black.png) no-repeat');
			$('#tab1').css('background','url(/img/tab1.png) no-repeat');
			$('#plitka_nav_2').show();
			$('#plitka_nav_1').hide();
        } else {
			$('#tab1').css('background','url(/img/tab1_black.png) no-repeat');
			$('#tab2').css('background','url(/img/tab2.png) no-repeat');
			$('#plitka_nav_1').show();
			$('#plitka_nav_2').hide();
        }

	$('#tab1').live(
		'click', function() {
			$('#tab1').css('background','url(/img/tab1_black.png) no-repeat');
			$('#tab2').css('background','url(/img/tab2.png) no-repeat');
			$('#plitka_nav_1').show();
			$('#plitka_nav_2').hide();
                        $.cookie("default_nav", "left", {
                            expires: 7,
                            path: "/"
                        });
	});

	$('#tab2').live(
		'click', function() {
			$('#tab2').css('background','url(/img/tab2_black.png) no-repeat');
			$('#tab1').css('background','url(/img/tab1.png) no-repeat');
			$('#plitka_nav_2').show();
			$('#plitka_nav_1').hide();
                        $.cookie("default_nav", "right", {
                            expires: 7,
                            path: "/"
                        });
	});
	
   $('#extra_collections').live('click', function() {
       $('#extra_collections_list').slideToggle('fast');
   });
   $('#extra_manufacturers').live('click', function() {
       $('#extra_manufacturers_list').slideToggle('fast');
   });
   $('#extra_manufacturers_list').hide();
   
   $('#seach_field').keypress(function(e) {
		if(e.keyCode == 13) {
			if($(this).val().length >= 3) {
				location.href = '/search/collection/' + $(this).val() + '/';
			} else {
				alert('Запрос должен быть длиной не менее 3 символов!');
			}
		}
   });
   
   $('#leningradka').click(function() {
		$.modal({
			msg: '<iframe frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="/map/index.html"></iframe>',
			label: 'Рынок "Ленинградка". Расположение на карте.',
			posX: 'left',
			posY: 'top',
			close: 1,
			width: $(window).width()-30,
			height: $(window).height()-30
		});
   });
   
	function array2json(arr) {
		var parts = [];
		var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');
		for(var key in arr) {
			var value = arr[key];
			if(typeof value == "object") {
				if(is_list) parts.push(array2json(value))
				else parts[key] = array2json(value);
			} else {
				var str = "";
				if(!is_list) str = '"' + key + '":';
				if(typeof value == "number") str += value;
				else if(value === false) str += 'false';
				else if(value === true) str += 'true';
				else str += '"' + value + '"';
				parts.push(str);
			}
		}
		var json = parts.join(",");
		if(is_list) return '[' + json + ']';
		return '{' + json + '}';
	}
  
	var anntimer = '';
	function announce(msg) {
		clearTimeout(anntimer);
		$('#announce').remove();
		$('body').append('<div id="announce">'+msg+'</div>');
		$('#announce').hide().css({
			'position': 'fixed',
			'background': '#FFF',
			'opacity': 0.95,
			'filter': 'alpha(opacity=95)',
			'width': '300px',
			'left': $(window).width() - 390,
			'top': '50px',
			'font-family': 'Verdana',
			'font-size': '20px',
			'font-weight': 'bold',
			'color': '#000',
			'padding': '20px',
			'border-radius': '15px',
			'-moz-border-radius': '15px',
			'z-index': '999'
		});
		$('#announce').fadeIn(750);
		anntimer = setTimeout(function(){$('#announce').fadeOut(500)},2250);
	}
  
   //cart
	update_cart_ajax()
	var cart = {} || eval('(' + $.cookie('cart') + ')' )
	
	$('.addtocart').click(function() {
		var product_id = $(this).attr('id').replace('addtocart_','');
		var product_count = $('#cartcount_' + product_id).val();
		if($('#cartcount_' + product_id).val()=='') return;
		if($.cookie('cart') == null) {
			var cart_loc = {};
		} else {
			var cart_loc = eval('(' + $.cookie('cart') + ')' );
		}
		if(cart_loc[product_id] != undefined) {
			cart_loc[product_id] = parseFloat(cart_loc[product_id]) + parseFloat(product_count);
		} else {
			cart_loc[product_id] = product_count;
		}
		announce('Товар добавлен в корзину');
		$('#cartcount_' + product_id).val('');
		$.cookie("cart", array2json(cart_loc), {
			expires: 7,
			path: "/"
		});
		update_cart_ajax();
	});
	
	//Б-б-б-б-ыыыыыыыыдлооо код тут! ;(
	$('#litochrom_add').live('click', function() {
		var type_kg		= $('#litochrom_count').val();
		var type_color	= $('#litochrom_color').val();
		var type_count	= $('#litochrom_input').val();
		
		//2977 - 2kg
		//3792 - 5kg
		var id = type_kg==2?2977:3792;

		if($.cookie('cart') == null) {
			var cart_loc = {};
		} else {
			var cart_loc = eval('(' + $.cookie('cart') + ')' );
		}
		
		if(cart_loc[id] != undefined) {
			cart_loc[id] = parseFloat(cart_loc[id]) + parseFloat(type_count);
		} else {
			cart_loc[id] = type_count;
		}
		
		if(type_kg == 2) {
			$.cookie("litochrom_color_2", type_color, {
				expires: 7,
				path: "/"
			});
		} else {
			$.cookie("litochrom_color_5", type_color, {
				expires: 7,
				path: "/"
			});
		}
		
		$.cookie("cart", array2json(cart_loc), {
			expires: 7,
			path: "/"
		});
		
		announce('Товар добавлен в корзину');
		update_cart_ajax();
	});
	
	$('#recount').click(function() {
		var cart_loc = eval('(' + $.cookie('cart') + ')' );
		for(var i = 0; i < $('#inner_content input').size(); i++) {
			var value = parseFloat($('#inner_content input').eq(i).val());
			if (isNaN(parseFloat(value))) {
				announce('Введено не правильное значение. Поле не может содержать буквы, а так же запятую.');
				$('#inner_content input').eq(i).css({'border': '2px solid red', background: '#FFADAD'});
				return;
			}
			var id = $('#inner_content input').eq(i).attr('id').replace('price_','');
			cart_loc[id] = value;
		}
		$.cookie("cart", array2json(cart_loc), {
			expires: 7,
			path: "/"
		});
		document.location.reload();
	});
	
	$('.cart_delete').click(function() {
		var cart = eval('(' + $.cookie('cart') + ')' );
		var id = $(this).attr('id').replace('cart_delete_','');
		delete cart[id];
		$.cookie("cart", array2json(cart), {
			expires: 7,
			path: "/"
		});
		$(this).parent().parent().prev('tr').remove();
		$(this).parent().parent().remove();
		retotal();
		update_cart_ajax();
	});
	
	$('.carttrselect').live('mouseover mouseout', function(event) {
		if(event.type == 'mouseover') {
			$(this).css({
				'background': '#FFF',
				'color': '#000'
			});
		} else {
			$(this).css({
				'background': 'transparent',
				'color': '#FFF'
			});
		}
	});
	
	function retotal() {
		var total = 0;
		$('.presum').each(function(index){
			total += parseFloat($(this).html().replace(' руб.',''));
		});
		$('.pretotal').html(total + ' руб.');
	}
	
	function update_cart_ajax() {
		if($.cookie('cart') != null && $.cookie('cart') != '{}' ) {
			var out = 
			'<br /><div class="wide_block">\
				<div class="wide_block_top"></div>\
				<div class="wide_block_middle">\
					<a href="/cart/">\
					<div class="wide_button button_plitka">Корзина</div>\
					</a>\
					<div id="cartinfo"></div>\
				</div>\
				<div class="wide_block_bottom"></div>\
			</div>';
			$('#cart').html(out).show();
			$('#cartinfo').css({
				'padding': '10px',
				'color': '#FFF',
				'font-size': '12px',
				'font-family': 'Verdana'
			});
			$('#cartinfo').html('<table width="100%"><tr><td align="center"><img src="/img/ajax.gif" /></td></tr></table>');
			var info = '<table width="100%" cellspacing="0" cellpadding="0">';
			var total = 0;
			$.getJSON('/cart/update/', function(data) {
				$.each(data, function(key, val) {
					if(key == 2977 || key == 3792) {
						var add = key == 2977 ? $.cookie('litochrom_color_2') : $.cookie('litochrom_color_5');
						info += '<tr><td align="center" width="70"><img onload="javascript:($(this).width()/$(this).height()>=1)?($(this).width(60)):($(this).width()/$(this).height()<1)?($(this).height(60)):null" class="cartinfoimg" src="/'+val['image']+'" /><br />'+val['name'] + ' ' + add + '</td><td> x '+val['count']+'</td><td>'+ parseFloat(val['count']) * parseFloat(val['price']) +' руб.</td></tr><tr><td colspan="3" height="5"></td></tr>';
					} else {
						info += '<tr><td align="center" width="70"><img onload="javascript:($(this).width()/$(this).height()>=1)?($(this).width(60)):($(this).width()/$(this).height()<1)?($(this).height(60)):null" class="cartinfoimg" src="/'+val['image']+'" /><br />'+val['name']+'</td><td> x '+val['count']+'</td><td>'+ parseFloat(val['count']) * parseFloat(val['price']) +' руб.</td></tr><tr><td colspan="3" height="5"></td></tr>';
					}
					total += parseFloat(val['count']) * parseFloat(val['price']);
				});
				info += '</table><div style="font-size:14px;font-weight:bold;">Итого: <span style="color:#FF6C05">'+ total +' руб.</span></div>';
				$('#cartinfo').html(info);
			});
		} else {
			$('#cart').hide();
		}
	}
	
	$('#centercolum input').live('keyup',function(e) {
		var value = $(this).val();
		value = value.replace(/,/, '.');
		$(this).val(value);
	});
	
	$('#offerorder').click(function() {
		var check_cart = eval( '(' + $.cookie('cart') + ')' );
		var newarr = {};
		for(var key in check_cart) {
			if (isNaN(parseFloat(check_cart[key]))) {
				announce('Введено не правильное значение. Поле не может содержать буквы, а так же запятую.');
				return false;
			}
			newarr[key] = parseFloat(check_cart[key]);
		}
		$.cookie("cart", array2json(newarr), {
			expires: 7,
			path: "/"
		});
	});
	
});
