function open_phone_app(){
	if (!window.phone || (window.phone && window.phone.closed) || (window.phone && window.phone.closed == undefined)) {
		window.phone = window.open('http://www.tipmeet.com/_/phone/?uid=mwater','phone','height=550,width=480,left=100,top=100,resizable=no,scrollbars=yes,toolbar=no,status=no');
	} else{
		window.phone.focus();
	}
}
var init_common = function($) {
	$('a.call').click(function(){
		open_phone_app();
	});
	$(".header .menu a").mouseenter(function() {
		$(this).closest(".menu").find("a.highlight").removeClass("highlight")
				.addClass("highlight-disabled");
	})
	$(".header .menu a").mouseleave(function() {
		$(this).closest(".menu").find("a.highlight-disabled").removeClass("highlight-disabled")
				.addClass("highlight");
	})
	$('#best_offers .carousel').jcarousel({
		scroll: 1
	});
	$('#diploma .carousel').jcarousel({
		vertical: true,
		scroll: 1,
		start: 999
	}).find('a').fancybox();
	$('#offers-right .carousel').jcarousel({
		vertical: true,
		scroll: 1,
		start: 999
	});
	$('#certificates-on-nagrady').find('a').fancybox();
	$('.left-menu > li').each(function(){
		var obj = $(this);
		var subMenu = obj.find('> ul');
		if (subMenu.length)
		{
			$('> a', obj).attr('href', 'javascript:void(0);').click(function()
			{
				if (subMenu.is(':hidden'))
				{
					$('.left-menu > li > ul').slideUp();
					subMenu.slideDown();
				}
				else
					subMenu.slideUp();
				return false;
			});
		}
	});

	function cartClass()
	{
		var obSelf = this;
		this.addToCart = function(obj, hidePopup)
		{
			var product_id = parseInt(obj.attr('id').replace('product-', ''));
			var number = obj.siblings('input[name=number]').length ? parseInt(obj.siblings('input[name=number]').val()) : 1;
			obSelf.addToCartLowLever(product_id, number, hidePopup ? null : obj);
		}
		this.addToCartLowLever = function(product_id, number, obj)
		{
			$.post(
					flotheme.ajax_load_url,
					{
						'action':	'flotheme_add_to_cart',
						'item':		product_id,
						'number':	number
					},
					function(data)
					{
						if (data.state)
						{
							obSelf.updatePriceInfo(data);
							if (obj)
								obSelf.showPopup(obj);
						}
					},
					'json'
			);
		}
		this.showPopup = function(obj)
		{
			var popup = $('<div id="popup">Товар добавлен в корзину</div>');
			$('body').append(popup);
			popup.css(obj.offset());
			setTimeout(function(){
				popup.remove();
			}, 4000)
		}
		this.removeFromCart = function(obj)
		{
			var product_id = parseInt(obj.attr('id').replace('product-', ''));
			$.post(
					flotheme.ajax_load_url,
					{
						'action':	'flotheme_remove_from_cart',
						'item':		product_id
					},
					function(data)
					{
						if (data.state)
						{
							obSelf.updatePriceInfo(data);
							obj.parents('tr').remove();
						}
					},
					'json'
			);
		}
		this.recalcCart = function(obj)
		{
			var product_id = parseInt(obj.attr('id').replace('product-field-', ''));
			var number = parseInt(obj.val());
			$.post(
					flotheme.ajax_load_url,
					{
						'action':	'flotheme_recount_cart_gallery',
						'item':		product_id,
						'number':	number
					},
					function(data)
					{
						if (data.state)
						{
							obSelf.updatePriceInfo(data);
							$('span','#product-summ-'+product_id).text(parseInt(obj.parents('tr').find('.item-price').text())*number);
						}
					},
					'json'
			);
		};
		this.updatePriceInfo = function(data)
		{
			if (data.count < 1)
				window.location.replace('/');
			$('#top-cart-text').html(data.basket_title);
			$('span', '#all-summ').text(data.summ);
		};
		this.init = function()
		{
			$('a.order-link').click(function(){
				obSelf.addToCart($(this));
			});
			$('a.delete-from-cart').click(function(){
				obSelf.removeFromCart($(this));
			});
			$('input.recalc-field').blur(function(){
				obSelf.recalcCart($(this))
			});
			obSelf.calculatorInit();
			obSelf.initSpecials();
		};
		this.initSpecials = function()
		{
			$('.special-propositions').fancybox({
				'autoDimensions': false,
				'width': 584,
				'height': 250,
				'onComplete': function()
				{
					$('#fancybox-content').find('a.order-link').click(function(){
						obSelf.addToCart($(this), true);
						$.fancybox.close();
					});
				}
			});
		};
		this.calculatorInit = function()
		{
			var productId = 30;//Важно! Если изменится ID основного продукта, калькулятор перестанет работать.
			var calc = function() {
				$.each(['#days', '#adults', '#glasses'], function(i, f) {
					var v = parseFloat($(f).val());
					if ((v == 0) || (isNaN(v))) { $(f).addClass('error'); } else { $(f).removeClass('error'); }
				});

				var days = parseFloat($('#days').val());
				var adults = parseFloat($('#adults').val());
				var kids = parseFloat($('#kids').val());
				var glasses = parseFloat($('#glasses').val());

				if (isNaN(kids)) { kids = 0; }

				var persons = kids + adults;

				var cleared = persons * 0.05;
				var cleared_another = persons * 0.05;

				var liters = ((glasses * 0.2) * persons);

				if ($('#cleared_yes').attr('checked')) { liters = liters + cleared; }
				if ($('#cleared_another_yes').attr('checked')) { liters = liters + cleared_another; }
				if ($('#animals_yes').attr('checked')) { liters = liters + 0.05; }

				liters = liters * days;

				if (isNaN(liters)) liters = 0;
				var bottles = Math.ceil(liters / 19.8);

				$('#liters').val(liters.toFixed(1));
				$('#bottles').val(bottles.toFixed());
			};

			var clear = function() {
				$('#days').val('7');
				$('#adults, #kids').val('2');
				$('#glasses').val('3');
				$('#cleared_no, #cleared_another_no, #animals_no').attr('checked', 'checked');
				$('#liters, #bottles').val('0');
			};

			$('#calc_button').click(calc);
			$('#clear_button').click(clear);

			$('#order_button').click(function(e) {
				var bottles = parseInt($('#bottles').val());
				if (!isNaN(bottles)) {
					obSelf.addToCartLowLever(productId, bottles);
				}
				$('#water').overlay({api: true}).close();
			});

			$('a[href=#water_calc]').click(function(e) {
				e.preventDefault();
				clear();
				$('#water').overlay({api: true}).load();
			});
	}
	this.init();
}
new cartClass();

$.fn.initForm = function()
{
	$(this).each(function(){
		var fn = $(this);
		var form = fn.find('form');
		var messages = fn.find('div.messages');
		form.find('input[type=text], textarea').labelify();
		form.validate({
			submitHandler: function(_form) {
				$.post(flotheme.ajax_load_url, form.serialize() + '&action=flotheme_submit_contact', function(data){
					if (data.error) {
						alert(data.msg);
						return;
					}
					$('#order-form .contact').remove();
					$('#order-form h2').text(data.msg);
					setTimeout(function(){
						window.location.replace(flotheme.site_url);
					}, 10000);
				}, 'json');
			},
			ignoreTitle: true,
			onkeyup: false,
			onfocusout: false,
			showErrors:function(errorMap, errorList){
				$.each(errorList, function(key, elm){
					$(elm.element)
							.animate( {opacity: 0.2}, 175 )
							.animate( {opacity: 1}, 150 );
				});
			},
			invalidHandler: function(form, validator) {
				$(this).find('input[type=text], textarea').blur();
			}
		});
	});
};
$('#order-form').initForm();
}

jQuery(document).ready(function($) {
	init_common($);
});

