$(document).ready(function() {
	
	$('.btn-order').click(function() {
		$(this).toggleClass('btn-order-active');
		
		setCaption($(this));
	});
	
	$('.btn-order').each(function() {
		setCaption($(this));
	});
	
});

function setCaption(obj) {
	if ( obj.hasClass('btn-order-active') ) {
		obj.html('Отменить');
	} else {
		obj.html('В корзину');
	}
}

function toggleProduct2Basket(id, update) {
	if ( ! id ) return;
	
	var data = 'id=' + id;
	
	var result = $.ajax({
        type: 		"POST",
        url: 		"/order/set",
		dataType: 	'html',
        data: 		data,
		
        success: function(response) {
			$('#basketCell').html(response);
			
			if ( update == true ) {
				updateOrder();
			}
        }
	});
}

function getBasket() {
	var result = $.ajax({
        type: 		"POST",
        url: 		"/order/get",
		dataType: 	'html',
        data: 		'',
		
        success: function(response) {
			$('#basketCell').html(response);
        }
	});
}

function deleteOrderPosition(id) {
	if ( id == null ) return;
	
	if ( ! confirm('Вы уверены, что хотите удалить выбранную позицию?') ) return;
	
	$('#position' + id).detach();
	toggleProduct2Basket(id, true);
}

function clearBasket() {
	if ( ! confirm('Вы уверены, что хотите очистить корзину?') ) return;
	
	var result = $.ajax({
        type: 		"POST",
        url: 		"/order/clear",
		dataType: 	'html',
        data: 		'',
		
        success: function(response) {
			$('#orderCell').html('Корзина пуста.');
			getBasket();
        }
	});
}

function updateOrder(control) {
	if ( control != null && ! control.value.match(/[\d]+/) ) return;
	
	var data = $('#frmOrder').serialize();
	
	var result = $.ajax({
        type: 		"POST",
        url: 		"/order/update_order",
		dataType: 	'json',
        data: 		data,
		
        success: function(response) {
			if ( response.error == null ) {
				$('#totalCost').html(response.total);
				$('#totalCount').html(response.count);
				
				if ( response.count == 0 ) {
					$('#sendTable input:button').attr('disabled', true);
				} else {
					$('#sendTable input:button').attr('disabled', false);
				}
			} else {
				$('#orderCell').html('<h3>Ваша корзина пуста.</h3>');
				getBasket();
			}
        }
	});
}

function sendOrder() {
	var data = $('#frmOrder').serialize();
	
	var result = $.ajax({
        type: 		"POST",
        url: 		"/order/send",
		dataType: 	'json',
        data: 		data,
		
        success: function(response) {
        	updateCaptcha('captchaCell', 'order');
        	
			if ( response.errors == null ) {
				showOrderTemplate('success', 'successTpl', response);
			} else {
				showOrderTemplate('errors', 'errorsTpl', response.errors);
			}
        }
	});
}

function showOrderTemplate(type, tplName, tplData) {

	var result = $.ajax({
        type: 		"POST",
        url: 		"/order/template",
		dataType: 	'html',
        data: 		"name=" + tplName,
		
        success: function(response) {
			$.template('tpl', response);
			
			switch (type) {
				
				case 'errors':
					$( '#orderMessages' ).html($.tmpl( 'tpl', tplData ).html());
					$( 'div.form_errors' ).fadeIn();
					break;
					
				case 'success':
					$( '#orderMessages' ).html($.tmpl( 'tpl', tplData ).html());
					$( '#orderMessages #successMsg' ).fadeIn();
					clearControls(['txtName', 'txtEmail', 'txtPhone', 'txtMessage', 'txtCaptcha']);
						break;
				}
	        }
	});
}

