
function $(el) {return document.getElementById(el)}

function toggleQ(id) {
	if ($('question'+id).style.display == "none")
		$('question'+id).style.display = "block"
	else if ($('question'+id).style.display == "block")
		$('question'+id).style.display = "none"
}

function toggleContact(id) {
	if ($('contact'+id).style.display == "none")
		$('contact'+id).style.display = "block"
	else if ($('contact'+id).style.display == "block")
		$('contact'+id).style.display = "none"
}
	
function toggleAsk() {
	if ($('formDiv').style.display == "none")
		$('formDiv').style.display = "block"
	else if ($('formDiv').style.display == "block")
		$('formDiv').style.display = "none"
}

function isTxt(str) {
	var Txt1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	var Txt2 = new RegExp("^[^0-9]{3,25}$");
	return (!Txt1.test(str) & Txt2.test(str));
}
	
function validate(form) {
	if (!isTxt(form.name.value)) {
		alert("Не указано Ваше Ф.И.О.");
		form.name.focus();
		form.name.select();
		return false;
	}
	if (!isTxt(form.email.value)) {
		alert("Не указан Ваш E-mail");
		form.email.focus();
		form.email.select();
		return false;
	}
	if (!form.text.value ) {
		alert("Не указан ваш вопрос");
		form.text.focus();
		form.text.select();
		return false;
	}
	if (!form.FormValidate_number.value ) {
		alert("Не указан код с картинки");
		form.FormValidate_number.focus();
		form.FormValidate_number.select();
		return false;
	}
	return true
}

function changeBg(num, name) {
	$('cars'+num).style.background = "url(/imgs/cars/" + name + ".jpg) right no-repeat"
}
function changeBg2(num, name) {
	$('cars'+num).style.background = "url(/imgs/cars/" + name + ".jpg) left no-repeat"
}

function changeWeight(obj) {
	if (obj.style.fontWeight == "normal" || obj.style.fontWeight == "" || obj.style.fontWeight == 400)
		obj.style.fontWeight = "bold"
	else if (obj.style.fontWeight == "bold" || obj.style.fontWeight == 700)
		obj.style.fontWeight = "normal"
}

function showMap(num) {
	if(document.getElementById('pmp' + num)) {
		document.getElementById('pmp' + num).src = dlr_a[num];
	}
	var map = $('map'+num)
	if (!map) return
	//map.style.visibility = "visible"
	if ($('highlight')) {
		$('highlight').innerHTML = $('area'+num).title
		$('highlight').style.visibility = "visible"
	}
}

function hideMap(num) {
	if(document.getElementById('pmp' + num)) {
		document.getElementById('pmp' + num).src = dlr[num];
	}
	var map = $('map'+num)
	if (!map) return
	//map.style.visibility = "hidden"
	if ($('highlight')) $('highlight').style.visibility = "hidden"
}

function openRegion(name) {
	location.href=name
}


/**
 * @author Vyacheslav Lotsmanov, October 2010
 * @purpose Работа с магазином
 */
(function ($) {
	window.shop = new function () {
		// private
		var root = this;
		// Array Remove - By John Resig (MIT Licensed)
		var array_remove = function(array, from, to) {
			var rest = array.slice((to || from) + 1 || array.length);
			array.length = from < 0 ? array.length + from : from;
			return array.push.apply(array, rest);
		};
		
		// public
		this.cookie_name = 'shop';
		
		// public hands
		this.cookies;
		this.basket;
		this.order;
		
		// работа с куками
		this.cookies = new function () {
			// private
			var cookies_root = this;
			
			// public
			this.check;
			this.get;
			this.send;
			
			// проверить, забита ли вообще кука по теме, если нет - записывает
			this.check = function () {
				if ( $.cookie( root.cookie_name ) === null ) {
					this.send();
				} else {
					this.get();
				}
				
				root.basket.button_update();
			};
			
			// получить параметры из кук
			this.get = function () {
				var data = $.parseJSON( $.cookie( root.cookie_name ) );
				root.basket.params = $.extend(true, {}, root.basket.params, data);
				
				root.basket.button_update();
			};
			
			// записать параметры в куку
			this.send = function () {
				$.cookie( root.cookie_name, $.toJSON( root.basket.params ), {path:'/'} );
				this.get();
				
				root.basket.button_update();
			};
		};
		
		// корзина
		this.basket = new function () {
			// private
			var basket_root = this;
			
			// public
			this.params = {
				goods: []
			};
			this.handlers = {
			
				// срабатывает по изменении количества товара в редактировании корзины
				change_count: function () {
					var id = $(this).closest('tr').find('.hidden_id').text();
					var val = $(this).val();
					var save_val = function () {
						$.each(basket_root.params.goods, function () {
							if ( id == this.id ) {
								this.count = parseInt( val );
								root.cookies.send();
							}
						});
					};
					
					if ( !/^[0-9]+$/.test( val ) ) {
						val = val.replace(/[^0-9]+/g, '');
						if ( val == '' ) {
							val = 1;
						}
						$(this).val( parseInt( val ) );
					}
					if ( val < 1 ) {
						$(this).closest('tr').find('a.deleter').click();
					}
					save_val();
					
					basket_root.handlers.recalc_totals();
				},
				
				// кнопочки прибавляющие и убавляющие количество
				spinner: {
					up: function () {
						var $input = $(this).closest('td').find('input');
						$input.val( parseInt($input.val()) + 1 );
						$input.change();
					},
					down: function () {
						var $input = $(this).closest('td').find('input');
						$input.val( parseInt($input.val()) - 1 );
						$input.change();
					}
				},
				
				// добавление в корзину (кнопка в товаре)
				add_to_basket: function () {
					var $box = $(this).parent();
					var id = $box.find('span.id').html();
					var name = $box.find('span.name').html();
					var link = $box.find('span.link').html();
					var price = $box.find('span.price').html();
					var complete = $.makeArray($box.closest('tr').find('.complete_to_basket div, .complete_to_basket td').map(function(i, elem) {
						if ($(elem).is('div') && $(elem).css('font-weight') == 'bold') 
							return '<strong>' + $.trim($(elem).text()) + '</strong><br/>'
						else 
							if ($(elem).is('div')) 
								return $.trim($(elem).text()) + '<br/>'
							else 
								if ($(elem).index() == 2) 
									return $.trim($(elem).text()) + '<br/>'
								else 
									if ($(elem).index() == 1) 
										return '(' + $.trim($(elem).text()) + ') '
									else 
										return $.trim($(elem).text()) + ' '
					})).join('').replace(/<br\/>$/, '');
					
					basket_root.add_good({
						data: {
							id: parseInt(id),
							name: name,
							link: link,
							price: price,
							complete: complete
						}
					});
					
					basket_root.handlers.check_has_in_basket();
					
					return false;
				},
				
				// проверяет в доме наличие товаров в корзине и в случае наличия меняет кнопку
				check_has_in_basket: function () {
					$('div.to_basket').each(function () {
						var $box = $(this);
						var id = $(this).find('span.id').html();
						
						$box.removeClass('in_basket');
						$box.find('a').html('В корзину');
						
						$.each(basket_root.params.goods, function () {
							if ( id == this.id ) {
								$box.addClass('in_basket');
								$box.find('a').html('В корзине');
							}
						});
					});
				},
				
				// удалялка по ссылке в редактировании корзины
				deleter: function () {
					if ( confirm('Вы уверены, что хотите удалить этот товар из корзины?') ) {
						var id = $(this).closest('tr').find('.hidden_id').text(),
						table = $(this).closest('table');
						$.each(basket_root.params.goods, function () {
							if ( id == this.id ) {
								basket_root.remove_by_id( id );
							}
						});
						$(this).closest('tr').remove();
						table.find('.good_index').each(function(i,elem){$(elem).text(i+1)});
						// если удалили и нифига не осталось - заменяем контент на сообщение об этом грустном факте
						if ( basket_root.params.goods.length < 1 ) {
							$('#basket_editor').replaceWith('<div>Ваша корзина пуста.<br/>'
								+ 'В разделе &quot;<a href="/goods/">Продукция</a>&quot; '
								+ 'вы можете положить товары в корзину для дальнейшего оформления заказа.</div>');
							return false;
						} else {
							basket_root.handlers.recalc_totals();
						}
					}
					return false;
				},
				
				// пересчёт суммы в корзине
				recalc_totals: function () {
					var res = 0.0;
					var part;
					var get_part;
					
					$.each(basket_root.params.goods, function () {
						var val = this.price.replace(',', '.');
						val = parseFloat( val );
						res += val * this.count;
					});
					
					res = res.toString();
					if ( res.search(/\./g) === -1 ) {
						res += '.00';
					}
					
					get_part = function () {
						part = res.replace(/[0-9]*\.([0-9]*)$/, '$1');
					};
					get_part();
					
					while ( part.length < 2 ) {
						res += '0';
						get_part();
					}
					
					while ( part.length > 2 ) {
						res = res.slice( 0, res.length-1 );
						get_part();
					}
					
					res = res.replace('.', ',');
					$('#basket_totals').html( res );
				},
				
				// обработчик кнопки "оформить заказ"
				go_order: function () {
					location.href = '/goods/shop/order/';
					return false;
				}
				
			};
			
			// public hands
			this.button_update;
			this.detail_init;
			this.add_good;
			this.remove_by_id;
			this.has_by_id;
			
			// обновление индикации полноты корзины на кнопке
			this.button_update = function () {
				if ( this.params.goods.length > 0 ) {
					$('.basket_button .goods_count').html('Товаров<br/>в&nbsp;корзине: ' + this.params.goods.length);
				} else {
					$('.basket_button .goods_count').html('Корзина<br/>пуста');
				}
			};
			
			// Инициализация страницы работы с корзиной
			this.detail_init = function ( input_params ) {
				input_params = $.extend({
					good_tmpl_selector: '#basket_good_item_tmpl'
				}, input_params);
				
				if ( this.params.goods.length < 1 ) {
					$('#basket_editor').replaceWith('<div>Ваша корзина пуста.<br/>'
						+ 'В разделе &quot;<a href="/goods/">Продукция</a>&quot; '
						+ 'вы можете положить товары в корзину для дальнейшего оформления заказа.</div>');
					return false;
				}
				
				var tbody = '';
				
				$.each(this.params.goods, function (i) {
					var res = $( input_params.good_tmpl_selector ).html();
					for ( var key in this ) {
						var reg = new RegExp(('\\#' + key + '\\#'), 'gi');
						res = res.replace(reg, this[key]);
					}
					res = res.replace(/#i#/gi, i+1);
					tbody += res;
				})
				
				$('table.shop_basket_table tbody').html( tbody );
				
				$('table.shop_basket_table tr').each(function () {
					var $count = $(this).find('td.count');
					$count.find('input').bind('change keydown keyup click', basket_root.handlers.change_count);
					$count.find('span.spinner span.up').click( basket_root.handlers.spinner.up );
					$count.find('span.spinner span.down').click( basket_root.handlers.spinner.down );
					
					$(this).find('.deleter').click( basket_root.handlers.deleter );
				});
				
				$('.go_order').click( basket_root.handlers.go_order );
				
				this.handlers.recalc_totals();
			};
			
			// добавление товара в корзину
			this.add_good = function ( input_params ) {
				input_params = $.extend(true, {
					data: {
						id: 0,
						name: '', // наименование товара
						count: 1, // количество
						price: '', // стоимость
						link: '', // ссылка на товар
						complete: '' // комплект
					}
				}, input_params);
				
				if ( input_params.data.id == 0 || input_params.data.id == '' ) {
					return false;
				}
				
				var stop = false;
				
				$.each(this.params.goods, function (i) {
					if ( this.id == input_params.data.id && !stop ) {
						location.href = '/goods/shop/basket/';
						stop = true;
					}
				});
				
				if ( stop ) {
					return false;
				}
				
				this.params.goods.push( input_params.data );
				
				root.cookies.send();
				this.handlers.check_has_in_basket();
			};
			
			// удаляет товар из корзины по его id
			this.remove_by_id = function ( id ) {
				$.each(this.params.goods, function (i) {
					if ( this.id == id ) {
						array_remove(basket_root.params.goods, i);
					}
				});
				
				root.cookies.send();
				this.handlers.check_has_in_basket();
			};
			
			// очистка корзины
			this.empty = function () {
				this.params.goods = []
				root.cookies.send();
				this.handlers.check_has_in_basket();
			};

			// проверка на наличие в корзине по заданному id
			this.has_by_id = function ( id ) {
				var has = false;
				
				$.each(this.params.goods, function () {
					if ( this.id == id ) {
						has = true;
					}
				});
				
				return has;
			};
		};
		
		// оформление заказа
		this.order = new function () {
			// private
			var order_root = this;
			
			// public
			this.handlers = {
				
				// принималка соглашения
				agreement_agree: function () {
					window.scrollTo(0,0);
					$('#shop_agreement').hide();
					$('#shop_order').show();
					return false;
				},
				
				// обработка на сабмит
				submit_hook: function () {
					var $form = $(this);
					
					if($(this).find('input#shop_fio[value=]').size()) {
						$.fancybox({
							content: '<p><strong>Ошибка!</strong></p><p>Пожалуйста, укажите ваше имя.</p>',
							onClosed: function(){
								$('input#shop_fio').focus();
							}
						});
						return false;
					}
					if($(this).find('input#shop_contact_telephone[value=], input#shop_email[value=]').size() > 0) {
						$.fancybox({
							content: '<p><strong>Ошибка!</strong></p><p>Пожалуйста, укажите контактный телефон и адрес электронной почты.</p>',
							onClosed: function(){
								$('input#shop_contact_telephone[value=]').focus();
							}
						});
						return false;
					}
					
					var data = {};
					$form.find('input[type=text], textarea').each(function(i, elem) {
						data[jQuery(elem).attr('name')] = jQuery(elem).val()
					});
					data['ajax'] = 1;
					data['params'] = jQuery.toJSON(root.basket.params);
					$.ajax({
						url: '/goods/shop/send/',
						type: 'GET',
						cache: false,
						'data': data,
						dataType: 'html',
						success: function ( res ) {
							var res = $.parseJSON( res );
							if ( typeof res.status !== 'undefined' && res.status == 'success' ) {
								shop.basket.empty()
								$.fancybox({
									content: '<p><strong>Ваш заказ подтвержден!</strong></p><p>В ближайшее время с Вами свяжется менеджер для уточнения деталей Вашего заказа.</p>',
									onClosed: function(){
										location.href = '/goods/'
									}
								});
							} else {
								$.fancybox('<p><strong>Ошибка!</strong></p><p>Произошла ошибка при отправке заказа, свяжитесь с администратором.</p>');
							}
						},
						error: function () {
							$.fancybox('<p><strong>Ошибка!</strong></p><p>Произошла ошибка при отправке заказа, свяжитесь с администратором.</p>');
						}
					});
					
					return false;
				},
				
				// показ товаров
				show_goods: function () {
					var res = '';
					
					res += '<table class="shop_basket_table" style="width:600px;">'
								+ '<thead>'
									+ '<tr>'
										+ '<th>№</th>'
										+ '<th class="long">Наименование товара</th>'
										+ '<th>Цена товара</th>'
										+ '<th>Количество</th>'
									+ '</tr>'
								+ '</thead>'
								+ '<tbody>';
					
					$.each(root.basket.params.goods, function (i) {
						res += '<tr>'
									+ '<td class="short good_id"><div class="good_index">' + (i+1) + '</div><div class="hidden_id">'+this.id+'</div></td>'
									+ '<td class="name"><a href="' + this.link + '">' + this.name + '</a><p>' + this.complete + '</p></td>'
									+ '<td class="price">' + this.price + ' руб.</td>'
									+ '<td class="count">' + this.count + '</td>'
								+ '</tr>';
					});
					
					res += '</tbody>'
						+ '</table>'
						+ '<div class="basket_totals">Итого без стоимости доставки: <span id="basket_totals">0,00</span> руб.</div>'
						+ '<div style=" clear:both; height:15px; "></div>';
					
					return res;
				},
				
				// проверка на наличие товаров
				check_goods: function () {
					if ( root.basket.params.goods.length < 1 ) {
						location.href = '/goods/shop/basket/';
						return false;
					} else {
						return true;
					}
				}
				
			};
		};
	};
	
	shop.cookies.check();
	
	$(function () {
		$('div.to_basket').each(function () {
			$(this).find('a').click( shop.basket.handlers.add_to_basket );
		});
		shop.basket.handlers.check_has_in_basket();
	});
})(jQuery);
