(function($){
	$.fn.placeholder = function() {
		return this.each(function() {
			if( $(this).data('_placeholder') ){
				return;
			}

			$(this).data('_placeholder', true).parents('form').submit(function(){
				$(this).find('.placeholder.off').each(function(){
					if( $(this).val() == $(this).data('_placeholder_temporary') )
						$(this).val('');
					else if( $(this).data('o') ) {
						$(this).hide();
						$($(this).data('o')).show();
					}
					else
						$(this).removeClass('off');
				});
			});

			if( $(this).attr('type') == 'password' ) {
				var input = $("<input class='placeholder off'>").attr('value', $(this).attr('value')).insertAfter(this).data('o',this);

				input.focus(function(){
					$(this).hide();
					$($(this).data('o')).show().focus();
				});

				$(this).hide().attr('value','').data('o',input).blur(function(){
					if( $(this).attr('value')=='' ){
						$(this).hide();
						$($(this).data('o')).show();
					}
				});

				if( $.browser.mozilla ){
					var
						passw = $(this),
						func = function(){
							if( passw.val() != '' ){
								input.hide();
								passw.show();
							}
							setTimeout(func, 100);
						};
					func();
				}
			} else {
				$(this).addClass('off').data('_placeholder_temporary', $(this).attr('value')).bind({
					focus: function(){
						if( $(this).is('.off') ){
							$(this).removeClass('off')
								.attr('value','');
						}
					},
					blur: function(){
						if( $(this).attr('value')=='' ){
							$(this).addClass('off')
								.attr('value', $(this).data('_placeholder_temporary'));
						}
					}
				});
				/*
				if( $.browser.mozilla )
					$(this).parents('form').click(function(){
						$(this).find('.placeholder.off').each(function(){
							var input = $($(this).data('o'));
							console.log(input.val());
							if( !input || input.val()=='' )
								return;
							input.show();
							$(this).hide();
						})
					});*/
			}
		});
	};
	$.fn.toggles = function(s) {
		var o = {
			assume: true,
			prefix: 'c_',
			getId: function(){ return $(this).attr('href').replace('/?id=','') },
			getUrl: function(){ return $(this).attr('href') },
			loaded: null
		};
		$.extend(o, s);

		return this.each(function() {
			$(this).children('a').click(function(){
				if( !$(this).hasClass('select') ) {
					var id, holder, toSelect;

					holder = $(this).parent().children('div');

					if( o.assume ) {
						toSelect = holder.children('*:eq('+$(this).prevAll().length+')');

						holder.children('.select').hide().removeClass('select');
						if( $.browser.msie && $.browser.version < 8 )
							toSelect.show().addClass('select');
						else
							toSelect.fadeIn(300).addClass('select');
					} else {
						id = o.getId.call(this);

						toSelect = holder.children('#'+o.prefix+id);
						holder.children('.select').hide().removeClass('select');

						if(toSelect.length==0) {
							$.ajax({
								url: o.getUrl.call(this),
								beforeSend: function(){
									holder.addClass('ajax-loading');
								},
								success: function(ans){
									holder.children('.select').hide().removeClass('select');
									$("<div id='"+o.prefix+id+"'>"+ans+"</div>").appendTo(holder).each(function(){
										$(this).css({width: $(this).children().length * 331 + 100, minWidth: '100%'});
										if( $.browser.msie && $.browser.version < 8 )
											$(this).show().addClass('select');
										else
											$(this).fadeIn(300).addClass('select');
									});
									holder.removeClass('ajax-loading');
								},
								error: function(){ alert(2); }
							});
						} else {
							holder.children('.select').hide().removeClass('select');
							toSelect.fadeIn(300).addClass('select');
						}
					}

					$(this).parent().children('a.select').removeClass('select');
					$(this).addClass('select');
				}
				return false;
			});
		});
	};
	$.fn.tree = function(s, recursion) {
		if( !recursion ){
			var o = { autocollapse: false, callback: null };
			$.extend(o, s);

			$(".tree a").click(function(){
				if( o.autocollapse && $(this).parent().children('a.expand').length>0 ) {
					$(this).parents('li').nextAll().children('a.collapse').trigger('click');
					$(this).parents('li').prevAll().children('a.collapse').trigger('click');
				}

				if( !$(this).hasClass('icon') && $(this).parent().children('a.collapse').length>0 ) {
					return false;
				}

				$(this).parent().children('.icon').toggleClass("expand").toggleClass("collapse")
					.parent().children('ul').toggle(300, function(){
						$(this).css('overflow','visible');
					});

				return false;
			});
		}
		else{
			var o = s;
		}


		return this.each(function() {
			$(this).children('li').each(function(){
				var t = $(this),
					c = t.children('ul');

				if( o.callback ) {
					t.children('a').click(o.callback);
				}

				if( c.length != 0 ){
					if( o.autocollapse )
						c.filter(':not(.expand)').hide();

					t.children('.icon').show()
					c.tree(o, true);
				}
			})
			.children('ul').parent().children('a').css('cursor','hand')
		});
	};
	$.fn.tooltip = function() {
		return this.live({
			mouseenter: function(e) {
				var text = this.getAttribute('tooltip') ? this.getAttribute('tooltip') : $(this).text(),
                    bb = $("<div class='tooltip-box'></div>").text(text).appendTo($('body'))
					.css({ left: e.pageX+10, top: e.pageY+10}).hide();
				setTimeout(function(){ bb.show(); }, 500);
			},
			mouseleave: function() {
				$("body>.tooltip-box").fadeOut(300, function(){ $(this).remove() });
			}
		});
	};
	$.fn.splash = function(s){
		var o = { closeLabel: 'Закрыть' };
		$.extend(o, s);
		return this.each(function(){
			$("#splash").remove();
			var
				splash = $("<div id='splash'><div><div><div></div></div></div>").appendTo($('body')).hide(),
				content = splash.children().children().children().append(this),
				close = $('<div class="splash-actions"><a href="." class="close-splash">'+o.closeLabel+'</a></div>').appendTo(content);

			close.children('a').click(function(){
				if( $.browser.msie && $.browser.version < 8 )
					splash.remove();
				else
					splash.fadeOut(300, function(){ $(this).remove() });
				return false;
			});
			if( $.browser.msie && $.browser.version < 8 )
				splash.show();
			else
				splash.fadeIn(300);
		});
	}
})(jQuery);

jQuery(function($){
    $("a.editor_file_link").click(function(){
        if( $(this).attr('rel') )
            window.location = "/upload/editor/" + $(this).attr('rel');
        else
            alert('файл не найден');
    });

	var product_placeholder_function = function(){
		if( $(this).parents('table.products').length ) {
			if( $(this).val() != 0 )
				$(this).removeClass('off').data('_placeholder_temporary','0');

			$(this).css({
				width: Math.max($(this).val().length,1)*6+14
			});
		}
	}

	$(window.document).ajaxComplete(function(){
		$(".placeholder").placeholder().each(product_placeholder_function);
	});

	$(".placeholder").placeholder().each(product_placeholder_function);
	$(".toggles:not(.metabanner)").toggles();
	$(".toggles.metabanner").toggles({assume: false});
	$(".tooltip").tooltip();
    
    $('.marquee').marquee('marquee').css({width: 'auto'});
    
	$(".tree").tree({
		autocollapse: true,
		callback: function(){
			if( !$('#aside').hasClass('ajaxed') ) {
				if( $.browser.msie && $.browser.version < 8 )
					return true;
				window.location = $(this).attr('href');
				return false;
			}

			if( !$(this).hasClass('select') ){
				$(this).parents('.tree').find('a.select').removeClass('select');
				$(this).addClass('select');

				if( $(this).attr('href').length > 1 )
					location.hash = $(this).attr('href');
			}
			return false;
		}
	});

	$("a.excursus").click(function(){
		$("<div class='message'><div><img src='"+$(this).attr('href')+"'/></div></div>").splash()
			.find('img').css({
				maxWidth: Math.round($(window).width()-100),
				maxHeight: Math.round($(window).height()-100),
			});
		return false;
	});

	if( $("#content table.products, #content table.orders").length ){
		$("table.products tbody td a:not(.delete)").live({
			click: function(e){
				var name = $(this).parents('tr').children('td:eq(2)').text(),
					box = $('<div class="toggles product"><a class="select"><span>'+name+'</span></a><div><table class="products makeup" cellspacing="0"><tbody></tbody></table></div></div>').splash();

				box.find('table')
					.append($(this).parents('table.products').children('thead').clone())
					.append($(this).parents('table.products').children('tfoot').clone())
				.find('tbody')
					.append($(this).parents('tr:eq(0)').clone())
					.find('a:not(.delete)').each(function(){ $(this).parent().html($(this).html()) });

				box.find('.pager').remove();
				box.find('.tooltip').tooltip();

				if( $.browser.msie && $.browser.version < 9 )
					box.find('tbody td').css('background','white');

				if( box.find('tfoot button.to-cart').length == 0 ) {
					box.find('.products .actions').hide();
					box.find('.products thead td:last-child').remove();
					box.find('.products thead td:last-child').remove();
					box.find('.products tbody td:last-child').remove();
					box.find('.products tbody td:last-child').remove();
				}

				$("<div class='product-info'>")
					.css({ maxHeight: Math.round($(window).height()/2), height: 'auto' })
					.prependTo(box.children('div'))
					.html('<div class="ajax-loading" style="height: 300px"></div>').show()
					.load($(this).attr('href'), function(){
						var img = $(this).find('img');
						img.css({ maxHeight: Math.round($(window).height()/2)-10 });
						if( img.attr('src') != '/img/default.png' )
							img.css('cursor','hand').click(function(){
								window.open(this.getAttribute('src'), '_blank');
							});
					});

				return false;
			}
		});

		$("#content table.products tbody td a.delete").live({
			click: function(e){
				var tr = $(this).parents('tr');

				$("<div class='message'><div><p>Удалить из корзины «"+$(this).parents('tr').find('a:not(.delete)').text()+"»?</p></div></div>").splash()
					.parent().parent().find('.close-splash').each(function(){
						$(this).text('Отмена');
						$("<button>Удалить</button>").insertAfter(this)
							.click(function(){
								$(this).attr('disabled','disabled');
								var id = tr.find('input').attr('name').replace(/[^\d]/g,'');
								$.ajax({
									url: '/cart/order/remove/' + id,
									context: this,
									success: function(){
										if( tr.parent().children().length == 1 )
											window.location.reload();

										tr.children().each(function(){
											$(this).html('<div>' + $(this).html() + '</div>');
										}).children().slideUp(300, function(){ $(this).parents('tr').remove() });

										$("#splash .close-splash").trigger('click');
									},
									error: function(){
										$(this).attr('disabled', '');
										$("<div class='message error'><div><h3>Произошла ошибка</h3><p>Проверьте Ваше соединение с интернетом.</p></div></div>").splash();
									}
								});
							});
					});
				return false;
			}
		});

		$("#content table.products .pager a").live({
			click: function(){
				if( $.browser.msie && $.browser.version < 8 )
					return true;
				location.hash = $(this).attr('href');
				return false;
			}
		});

		$("table.products>tfoot button.to-cart").live({
			click: function(){
				var ids = {};

				$(this).parents('table').find('input').each(function(){
					if( $(this).val() != '0' )
						ids[$(this).attr('name')] = $(this).val();
				});

				var b = $(this).attr('disabled', true);

				$.ajax({
					url: '/cart/add',
					type: 'post',
					context: this,
					data: ids,
					success: function(ans, status, xhr){
						var o = $.parseJSON(xhr.getResponseHeader('actionmessage'));
						$(this).attr('disabled', '');
						$("<div class='message'><div><h3>"+o.message+"</h3><p><a href='/cart/'>Перейти в корзину</a></p></div></div>").splash();
					},
					error: function(){
						$(this).attr('disabled', '');
						$("<div class='message error'><div><h3>Произошла ошибка</h3><p>Проверьте Ваше соединение с интернетом.</p></div></div>").splash();
					}
				});

				return false;
			}
		});

		$("table.products>tfoot button.create-order").live({
			click: function(){
				$("<div class='toggles create-order-from'><a class='select'><span>Оформить заказ</span></a><div><div class='table'></div></div></div>").splash()
					.children('div')
						.append($("<h4>Ваш коментарий:</h4><textarea></textarea>\
							<h4>Итого:</h4><table class='makeup altogether' cellspacing='0'><thead><tr>\
								<td>Позиций</td><td>Единиц</td><td>Цена, <span class='icon USD'></span></td><td>Цена, <span class='icon UAH'></span></td>\
								</tr></thead>\
								<tfoot><tr><td colspan='4'><span>&nbsp;</span></td></tr></tfoot>\
								<tdody><tr></tr></tbody></table>"))
						.find('.table')
                            .append($(this).parents('table').clone())
                            .css({maxHeight: Math.round($(window).height()-400), overflowY: 'auto', display: 'block'})
                        .parent()
					.each(function(){
						$("#splash").find('.splash-actions').append($("<button value='hold'>Сохранить</button> <button value='order'>Отправить заказ</button>"));
						$(this)
						.find('table.products tbody td:last-child').remove().end()
						.find('table.products thead td:last-child').remove().end()
						.find('table.products tbody tr').each(function(){
							if( $(this).find('.icon-12.presence').length == 0 )
								$(this).addClass('highlight');
						}).find('a').each(function(){ $(this).parent().html($(this).html()) });

						$(this).find('table.products tfoot td>*').remove();
						$(this).find('textarea').placeholder();
						$(this).find('table.altogether tbody').each(function(){
							var products = $('#splash').find('table.products'),
								count = products.find('tbody>tr').length,
								total = 0, sum = 0, sum_grn = '';

							products.find('input').each(function(){
								var v = parseInt($(this).val());
								$(this).attr('disabled','disabled');
								if( isNaN(v) )
									return;
								total += v;
								sum += v * parseFloat($(this).parent().siblings('.cost').text().replace(/[^\d\.]/g,''));
							});

							var rate = $("#exchange-rate .USD-UAH+p>span:eq(1)").text();
							if( !isNaN(parseFloat(rate)) )
								sum_grn = sum * parseFloat(rate);

							$(this).html('<tr><td>'+count+'</td><td>'+total+'</td><td>'+sum.toFixed(2)+'</td><td>'+sum_grn.toFixed(2)+'</td></tr>');
						});
						$(this).parent().next().find('button').click(function(){
							var ids = {};

							$('#splash table.products input').each(function(){
								if( $(this).val() != '0' )
									ids[$(this).attr('name')] = $(this).val();
							});
							ids['m'] = { comment: $('#splash textarea').val() };

							$(this).parent().children('button').attr('disabled', true);

							var label = $(this).text(),
								url = '/cart/' + $(this).text('').attr('value');
							$(this).text(label);

							$.ajax({
								url: url,
								type: 'post',
								context: this,
								data: ids,
								success: function(ans, status, xhr){
									var o = $.parseJSON(xhr.getResponseHeader('actionmessage'));
									$(this).parent().children('button').attr('disabled', '');
									if( o.type == 'error')
										$("<div class='message error'><div><h3>"+o.message+"</h3></div></div>").splash();
									else
										$("<div class='message'><div><h3>"+o.message+"</h3></div></div>").splash()
											.parent().parent().find('.close-splash').unbind('click');
								},
								error: function(){
									$(this).parent().children('button').attr('disabled', '');
									$("<div class='message error'><div><h3>Произошла ошибка</h3><p>Проверьте Ваше соединение с интернетом.</p></div></div>").splash();
								}
							});

							return false;
						});
					})
					.find('tfoot span').hide();
				return false;
			}
		});

		$("#content table.products input").live({
			keyup: function(e) {
				$(this).css({
					width: Math.max($(this).val().length,1)*6+14
				});
			},
			change: function(){
				if( isNaN(parseInt($(this).val())) )
					$(this).val('');
				else
					$(this).val(parseInt($(this).val()).toFixed(0));
				$(this).css({
					width: Math.max($(this).val().length,1)*6+14
				});
			}
		});

		if( $.browser.msie && $.browser.version < 9 ) {
			$(".makeup tbody>tr:nth-child(odd) td").css({backgroundColor: '#f7fcff'});
			$(".orders>tbody>tr:nth-child(4n+1)>td").css({backgroundColor: '#f7fcff', borderBottom: 'none'});
			$(".orders>tbody>tr:nth-child(4n+2)>td").css({backgroundColor: '#f7fcff', borderTop: 'none'});
			$(".orders>tbody>tr:nth-child(4n+3)>td").css({backgroundColor: 'transparent', borderBottom: 'none'});
			$(".orders>tbody>tr:nth-child(4n)>td").css({backgroundColor: 'transparent', borderTop: 'none'});
		}

		if( $.fn.hashchange ) {
			var history = [];
			function updateState(hash){
				var href = hash.replace(/^#/,'');
				if( !href.match(/^\/catalog\//) )
					return;

				if( history[href] )
					$("#content").html(history[href]);
				else
					$("#content").html('<div class="ajax-loading" style="height: '+$(this).height()+'"></div>')
						.load(href + ' #content>*', function(){
							if( $.browser.msie && $.browser.version < 9 ) {
								$(".makeup tbody>tr:nth-child(odd) td").css({backgroundColor: '#f7fcff'});
							}
							history[href] = $("#content").html();
						});
				var sel = $(".tree a[href]").filter(function(){ return $(this).attr('href') == href });

				if( !sel.hasClass('select') ){
					sel.parents('.tree').find('a.select').removeClass('select');
					sel.parents('li').children('a.icon.expand').trigger('click');
					sel.addClass('select');

					var tab = sel.parents('div:eq(0)');
					if( !tab.hasClass('select') )
						tab.parent().parent()
							.children('a:eq(' + tab.prevAll('div').length + ')').trigger('click');
				}
			}
			$(window).hashchange(function() { updateState(location.hash) });
			updateState(location.hash);
		}
	};

	if( $.browser.msie && $.browser.version < 8 )
		$("table.orders>tbody>tr>td>div").each(function(){ $("<span>&nbsp;</span>").appendTo(this.parentNode).hide(); });

	$("table.orders>tbody>tr>td>a").live({
		click: function(){
			if( $(this).hasClass('off') ) {
				$(this).removeClass('off').html('Показать содержимое')
					.parents('tr').next().children().children('div').slideUp(300);
			} else {
				$(this).addClass('off').html('Спрятать содержимое')
					.parents('tr').next().removeClass('hidden').children().children('div').each(function(){
						if( $(this).children().length > 0 ) {
							$(this).hide().slideDown(300);
							return;
						}

						$(this).hide().addClass('ajax-loading').slideDown(300);

						var id = $(this).parents('tr').prev().attr('id').replace(/^o_/,'');
						$(this).load('/catalog/order/' + id, function() {
							$(this).removeClass('ajax-loading')
							.find('input').attr('disabled','disabled').end()
							.find('button').click(function(){
								$(this).attr('disabled', true);

								var label = $(this).text(),
									url = '/cart/' + $(this).text('').attr('value') + '/' + id;
								$(this).text(label);

								$.ajax({
									url: url,
									context: this,
									success: function(ans, status, xhr){
										var o = $.parseJSON(xhr.getResponseHeader('actionmessage'));

										$("<div class='message'><div><h3>"+o.message+"</h3></div></div>").splash().parent().parent()
											.find('.close-splash').unbind('click');
									},
									error: function(){
										$(this).attr('disabled', '');
										$("<div class='message error'><div><h3>Произошла ошибка</h3><p>Проверьте Ваше соединение с интернетом.</p></div></div>").splash();
									}
								});

								return false;
							});


							if( $.browser.msie && $.browser.version < 9 ) {
								$(this).find("tbody tr:nth-child(odd) td").css({backgroundColor: '#e2f2ff'});
							}
						});
					});
			}
		}
	});

	$("#register").each(function(){
		$(this).find('a').click(function(){
			$("<div class='register toggles ajax-loading'><a class='select'><span>Регистрация</span></a><div></div></div>").splash()
				.find('.close-splash').text('Отмена').end()
				.children('div').load($(this).attr('href') + ' #content>*', function(ans){
					$(this).parents('.ajax-loading').removeClass('ajax-loading');

					if( ans.match(/^<h2>.*<\/h2>/) ) {
						$("<div class='message error'><div><h3>Произошла ошибка</h3><p>"+ans.replace(/<\/{0,1}h2>/,'')+"</p></div></div>").splash()
							.parent().find('.close-splash').unbind('click');
					} else {
						$(this).find('h3').remove();
						$(this).find('button').parent().each(function(){
							$('#splash .close-splash').prependTo(this);
							$('#splash .splash-actions').remove();
							$(this).addClass('splash-actions');
						})
					}
				});

			return false;
		});

		$(this).submit(function(){
			$(this).find('button').attr('disabled', 'disabled');
            $(this).find('input[type=hidden]').remove();

			$.ajax({
				url: $(this).attr('action'),
				type: 'post',
				context: $(this).find('button'),
				data: $(this).serialize(),
				success: function(answ, status, xhr){
					$(this).attr('disabled', '');

					var o = $.parseJSON(xhr.getResponseHeader('actionmessage')),
						r = xhr.getResponseHeader('redirectDirect');

                    if( !o )
                        $("<div class='message error'><div><h3>Неизвестная ошибка!</h3></div><p>Попробуйте позже.<br/><small style='color: #eee'>А в конце будет Торт!</small></p></div>").splash();

					if( o.type == 'success' ){
                        $("<div class='message'><div><h3>Здравствуйте!</h3><p style='margin-bottom:10px'>"+o.message+"</p></div></div>").splash()
                            .parent().children('div.splash-actions').remove();
                        window.location = r;
                    } else if( xhr.getResponseHeader('errorcode') == 1 ) {
                        var login_code_form = function(){
                            $("<div class='message error'><div><h3>"+o.message+"</h3><p>Для входа в систему введите его: <input type='text'/></p></div></div>").splash().parent().find('div.splash-actions').append('<button>Подтвердить</button>')
                                .find('button').click(function(){
                                    $(this).attr('disabled','disabled');

                                    var form = $("#register");
                                    $('<input type="hidden" name="m[code]"/>').val($("#splash input").val()).appendTo(form);

                                    $.ajax({
                                        url: form.attr('action'),
                                        type: 'post',
                                        context: this,
                                        data: form.serialize(),
                                        success: function(answ, status, xhr){
                                            var o = $.parseJSON(xhr.getResponseHeader('actionmessage')),
                                                r = xhr.getResponseHeader('redirectDirect');

                                            if( !o )
                                                $("<div class='message error'><div><h3>Неизвестная ошибка!</h3></div><p>Попробуйте позже.<br/><small style='color: #eee'>А в конце будет Торт!</small></p></div>").splash();

                                            if( o.type == 'success' ){
                                                $("<div class='message'><div><h3>Здравствуйте!</h3><p style='margin-bottom:10px'>"+o.message+"</p></div></div>").splash()
                                                    .parent().children('div.splash-actions').remove();
                                                window.location = r;
                                            } else {
                                                $("<div class='message error'><div><h3>Произошла ошибка</h3><p>"+o.message+"</p></div></div>").splash()
                                                    .parent().children('div.splash-actions').each(function(){
                                                        $(this).children('a').html('Отмена');

                                                        if( xhr.getResponseHeader('errorcode') != 4 )
                                                            $("<button>Ввести ещё раз</button>").appendTo(this).click(login_code_form);

                                                        $("<button>Сгенерировать новый</button>").appendTo(this).click(function(){
                                                            $(this).parent().children('a').trigger('click');
                                                            $("#register").trigger('submit');
                                                        });
                                                    })
                                            }
                                        },
                                        error: function(){
                                            $("<div class='message error'><div><h3>Произошла ошибка</h3><p>Проверьте Ваше соединение с интернетом.</p></div></div>").splash();
                                        }
                                    })
                                    return false;
                                });
                        };

                        login_code_form();
                    }
                    else
						$("<div class='message error'><div><h3>Произошла ошибка</h3><p>"+o.message+"</p></div></div>").splash();
				},
				error: function(){
					$(this).attr('disabled', '');
					$("<div class='message error'><div><h3>Произошла ошибка</h3><p>Проверьте Ваше соединение с интернетом.</p></div></div>").splash();
				}
			})
			return false;
		});
	});

	$(".ajax_show_map").click(function(){
		$("<div class='toggles map'><a class='select'><span>Карта проезда</span></a><div><div class='select' id='YMapsID-3811'></div></div></div>").splash();

		var map = new YMaps.Map($("#YMapsID-3811")[0]);
		map.setCenter(new YMaps.GeoPoint(30.435929,50.448295), 15, YMaps.MapType.MAP);
		map.addControl(new YMaps.Zoom());
		map.addControl(new YMaps.ToolBar());
		YMaps.MapType.PMAP.getName = function () { return "Народная"; };
		map.addControl(new YMaps.TypeControl([
			YMaps.MapType.MAP,
			YMaps.MapType.SATELLITE,
			YMaps.MapType.HYBRID,
			YMaps.MapType.PMAP
		], [0, 1, 2, 3]));

		YMaps.Styles.add("constructor#pmlbmPlacemark", {
			iconStyle : {
				href : "http://api-maps.yandex.ru/i/0.3/placemarks/pmlbm.png",
				size : new YMaps.Point(28,29),
				offset: new YMaps.Point(-8,-27)
			}
		});

		map.addOverlay(createObject("Placemark", new YMaps.GeoPoint(30.435371,50.447281), "constructor#pmlbmPlacemark", "Mirtex LTD —  Официальный дистрибьютор<br/><br/>Static Control Components в Украине<br/><br/><br/><br/>г. Киев, ул.Машиностроительная 27"));

		function createObject (type, point, style, description) {
			var allowObjects = ["Placemark", "Polyline", "Polygon"],
				index = $.inArray( type, allowObjects),
				constructor = allowObjects[(index == -1) ? 0 : index];
				description = description || "";

			var object = new YMaps[constructor](point, {style: style, hasBalloon : !!description});
			object.description = description;

			return object;
		}

		return false;
	});

	$("form.register-form").live({
		submit: function(){
			$(this).find('button').attr('disabled','disabled').end()
				.find('.error-box').slideUp(300, function(){ $(this).remove() }).end();

			$.ajax({
				url: $(this).attr('action'),
				type: 'post',
				context: $(this).find('button'),
				data: $(this).serialize(),
				success: function(ans, st, xhr){
					$(this).attr('disabled','');

					var o = $.parseJSON(xhr.getResponseHeader('actionmessage')),
						errors = $.parseJSON(xhr.getResponseHeader('X-JSON'));

					if( !o ){
						$("<div class='message error'><div><h3>Неизвестная ошибка!</h3></div><p>Попробуйте зарегестрироваться позже.<br/><small style='color: #eee'>А в конце будет Торт!</small></p></div>").splash();
					} else if( o.type == 'error' ){
						$(this).attr('disabled', '');

						for( var i in errors ){
							$('<div class="error-box">'+errors[i]+'</div>')
								.appendTo($(this).parents('form').children('p.'+i)).hide().slideDown(300);
						}
					} else {
						$("<div class='message'><div><h3>Спасибо за регистрацию!</h3></div><p>Наши менеджеры обработают Вашу заявку и активируют Вашу учётную запись.</p></div>").splash();
					}
				},
				error: function(){
					$(this).attr('disabled', '');
						$("<div class='error-box'>"+o.message+"</div>").insertBefore($(this).parent());
				}
			});
			return false;
		}
	});

	$(".payment-form").click(function(){
		$("<div class='toggles payment'><a href='#' class='select'><span>Пополнить баланс</span></a><div class='select'><form><label>Пополнить баланс на сумму: <input type='text' name='m[requested_sum]'/></label></form></div></div>").splash()
			.each(function(){
				var b = parseFloat($('#user-ballance').text().replace(/[^-\d\.]/g,''));
				if( isNaN(b) )
					b = 0;
				$(this).find('input').val( Math.max( 0, -b ).toFixed(2) );
				$("<button>Создать платёжку</button>").insertAfter( $(this).parent().find('.close-splash').text('Отмена') )
					.click(function(){
						$(this).attr('disabled','disabled');

						$.ajax({
							url: '/cart/ballance',
							type: 'post',
							data: $('#splash form').serialize(),
							context: this,
							success: function(ans, s, xhr){
								$(this).attr('disabled','');

								var o = $.parseJSON(xhr.getResponseHeader('actionmessage'));

                                if( !o ){
                                    $("<div class='message error'><div><h3>Неизвестная ошибка!</h3></div><p>Попробуйте зарегестрироваться позже.<br/><small style='color: #eee'>А в конце будет Торт!</small></p></div>").splash();
                                }

								$("<div class='message'><div><h3>"+o.message+"</h3></div></div>").splash().parent().parent()
									.find('.close-splash').unbind('click');
							},
							error: function(){
								$(this).attr('disabled', '');
								$("<div class='message error'><div><h3>Произошла ошибка</h3><p>Проверьте Ваше соединение с интернетом.</p></div></div>").splash();
							}
						})
					});
			});
		return false;
	});

	$("table.ballance .delete").click(function(e){
		var tr = $(this).parents('tr'),
			id = tr.attr('id').replace(/^b_/,'');

		$("<div class='message'><div><p>Удалить платёж на сумму "+$(this).parents('tr').find('.cost').html()+"?</p></div></div>").splash()
			.parent().parent().find('.close-splash').each(function(){
				$(this).text('Отмена');
				$("<button>Удалить</button>").insertAfter(this).click(function(){
						$(this).attr('disabled','disabled');

						$.ajax({
							url: '/cart/ballance/remove/' + id,
							context: this,
							success: function(){
								if( tr.parent().children().length == 1 )
									window.location.reload();

								tr.children().each(function(){
									$(this).html('<div>' + $(this).html() + '</div>');
								}).children().slideUp(300, function(){ $(this).parents('tr').remove() });

								$("#splash .close-splash").trigger('click');
							},
							error: function() {
								$(this).attr('disabled', '');
								$("<div class='message error'><div><h3>Произошла ошибка</h3><p>Проверьте Ваше соединение с интернетом.</p></div></div>").splash();
							}
						});
					});
			});
		return false;
	});

	$("form.register-form .private input").live({
		change: function(){
			$(this).parent().prevAll().toggle().find('input').each(function(){
				if( !$(this).attr('disabled') )
					$(this).attr('disabled','disabled');
				else
					$(this).attr('disabled','');
			});
		}
	});

	$("#search").submit(function(){
		if( $("body>div").hasClass("private") )
			return true;
		$("<div class='message error'><div><h3>Поиск не доступен</h3><p>Зарегестрируйтесь и войдите в систему, чтобы воспользоваться поиском</p></div></div>").splash();
		return false;
	});


        $(".generaly-the-news:not(.hidden)").css('display', 'block');
        $("#menu .toggle-generaly-news").click(function(){
            $(".generaly-the-news").slideToggle(200);
            if( $(".generaly-the-news").toggleClass('hidden').is('.hidden') ) {
                $(this).text("↓ Показать новости");
                $.cookie('hidegeneralynews', this.getAttribute('timestamp'), { expires: 7, path: '/' });
            } else {
                $(this).text("× Спрятать новости");
                $.cookie('hidegeneralynews', 0, { expires: 7, path: '/' });
            }
        });
})
