if (!rx) var rx = {};

rx = $.extend(rx, {
shopInit: function () {
	$('#shopBasket form:not(form[target])').each(function () {
		this.action = rx.shopPathToModule + 'shopController.php' + (this.action.indexOf('?')!=-1 ? this.action.substr(this.action.lastIndexOf('?')) : '');
	}).ajaxForm({
		//url: rx.shopPathToModule+'shop.php',
		beforeSubmit: function (formData, jqForm, options) {
			if ($(jqForm).validate) {
				if ($(jqForm).valid())
					return true;
				else return false;
			}
			else return true;
		},
		success: function(response) {
			$('#shopBasket').html(response);
			$('#shopBasketMini').load((rx.shopPathToModule?rx.shopPathToModule:'')+'shop_mini.php');
		}
	});
	$("#shopBasket #confirmBasket").validate({
		rules: {
			name: "required",
			surname: "required",
			//personalCode: "required",
			address: "required",
			phone: "required",
			email: {
				required: true,
				email: true
			}
		},
		messages: {
			name: "Please enter your name",
			surname: "Please enter your surname",
			//personalCode: "Please enter your personal code",
			address: "Please enter your address",
			phone: "Please enter your phone number",
			email: "Please enter a valid email address"
		}
	});
	//$('#shopBasket').addClass('inited');
},

shopGetNextProductId : function() {
	$.get((rx.shopPathToModule?rx.shopPathToModule:'')+'shopController.php?action=shopGetNextProductId', null, function(productId) { $('#article_product_id').val(productId);});
},

shopCheckProductId: function (elemId) {
	if(!elemId) var elemId = 'article_product_id';
	$.get((rx.shopPathToModule?rx.shopPathToModule:'')+'shopController.php?action=shopCheckProductId', { id: $('#'+elemId).val() }, function(checked_id) { $('#'+elemId).css({ border: 'solid 2px ' + (checked_id==1 ? 'green' : 'red')}).attr('isValid', checked_id); })
},

shopBuyProduct: function (product_id, units) {
	// Selected delivery type (Riga, Latvia, Daugavpils, ...) value
	var selectedPostalDestination = $("#delivery_destination_select").val();
	$.post((rx.shopPathToModule?rx.shopPathToModule:'')+'shopController.php?action=addProductToBasket', {  prod_id: product_id, prod_ammount: (parseInt(units,10) ? parseInt(units,10) : 1), selectedPostalDestination: selectedPostalDestination }, function() { 
		// if user changed delivery postal destination
		if(product_id=='-1' && units=='-2' ){
			$.jGrowl(rx.translate('delivery_post_chged'));
		}
		// if user added a delivery to the basket
		else if(product_id=='-1'){
			$.jGrowl(rx.translate('delivery_added'));
		}
		// if user added a product to the basket
		else {
			$.jGrowl(rx.translate('product_added_to_basket'));
		}		
		rx.shopBasketReload();
	})
},

shopConfirmBasket___: function () {
	$('#confirmBasket').attr('action', 'modules/rxShop/shop.php').submit();
},

shopConfirmBasket: function () {
	document.getElementById('basket_email_invoice_0').value = 1;
	if ($('#registerTable').is(':hidden')) $('#registerTable').slideDown();
	else {
		$.getJSON((rx.shopPathToModule?rx.shopPathToModule:'')+'shopController.php?action=checkBasketProductsInStock', function (data) {
			if(!data.error) {
				$('#confirmBasket').submit();
				$('tr[id^=basket_product_]').each(function() {
					var sold = parseInt($('input', this).val());
					var stock = parseInt($('td[id=product_'+($(this).attr('id')).substr(15)+'] > span').text(), 10);
					if(!(stock - sold)) $('td[id=product_'+($(this).attr('id')).substr(15)+'] > input').hide();
					$('td[id=product_'+($(this).attr('id')).substr(15)+'] > input:text').val(1);
					$('td[id=product_'+($(this).attr('id')).substr(15)+'] > span').text(stock - sold);
				});
			} else {
				rx.alert(data.error);
				rx.shopBasketReload();
			}
		});
	}
},

shopGetProductInfo: function (productID, thisTD) {
	if (!$('#product_'+productID+'_info').size()) {
		$.getJSON((rx.shopPathToModule?rx.shopPathToModule:'')+'shopController.php?action=getProductInfo', { productID: productID }, function (data) {
			$(thisTD).parents('tr:first').after('<tr id="product_'+productID+'_info"><td colspan="4">'+data.productInfo+'</td></tr>');
		});
	}
	else if ($('#product_'+productID+'_info').is(':visible')) {
			$('#product_'+productID+'_info').hide();
		}
		else $('#product_'+productID+'_info').show();
},

shopChangeAmount: function (product_id, new_amount, old_amount) {
	if (new_amount <= 0 || parseInt(new_amount,10) != new_amount) {
		new_amount = old_amount;
		document.getElementById('basket_ammount_of_' + product_id).value = new_amount;
	} else {
		$.post((rx.shopPathToModule?rx.shopPathToModule:'')+'shopController.php?action=changeAmount', { product_id: product_id, new_amount: new_amount }, function() {
			rx.shopBasketReload();
		});
	}
},

shopCheckAllCheckboxesInForm: function () {
	$('#shopBasket input:checkbox').attr('checked', true);
},

shopDeleteProductFromBasket: function () {
	if (!$('#shopBasket input:checkbox:checked').size()) {
		rx.confirm(rx.translate('empty_basket_confirm'),function() {
			rx.shopCheckAllCheckboxesInForm();
			$('#delete_marked_products').submit();
		});
	}
	else {
		rx.confirm(rx.translate('delete_product_confirm'),function() {
			$('#delete_marked_products').submit();
		});
	}
},

shopBasketReload: function () {
	$('#shopBasket').load((rx.shopPathToModule?rx.shopPathToModule:'')+'shop.php');
	setTimeout("$('#shopBasketMini').load((rx.shopPathToModule?rx.shopPathToModule:'')+'shop_mini.php');",1000);
}

});

// **************************
// PRICE WITH VAT CALCULATION
// **************************

// this will calculate price with VAT in Shop settings page if only one VAT is available in the system
$('.rx-shop-price-and-one-vat').live('keyup',function() {
	var price = parseFloat($(this).val());
	var priceWithVatInpt = $(this).nextAll('input');
	var vat = parseFloat(rx.defaultVat);
	// if price field is empty then display price with VAT as empty field
	if (!$(this).val()){
 		$(this).nextAll('input').val('');
 	} 
 	// if price is entered calculate price with vat in the next input
 	else{
 		var priceWithVat = price+price*vat/(parseFloat('100.00'));
 		priceWithVatInpt.val(priceWithVat.toFixed(2));
	}
});

// this will calculate product price with VAT in product tab
$('.rx-shop-price-and-vat').live('keyup',function() {
	var price =  parseFloat($(this).val());
	var priceWithVatInpt =  $(this).nextAll('input');
	var vat =  parseFloat($('#vat_category_select option:selected').attr('percent'));
	// if price field is empty then display price with VAT as empty field
	if (!$(this).val()){
 		$(this).nextAll('input').val('');
 	} 
 	// if price is entered calculate price with vat in the next input
 	else{
 		var priceWithVat = price+price*vat/(parseFloat('100.00'));
 		priceWithVatInpt.val(priceWithVat.toFixed(2));
	}
});

// this will calculate price with VAT for existing deliveries in product tab
$('.rx-shop-delivery-price-and-vat').live('keyup',function() {
	// if price field is empty then change opacity to 0.5
	if (!$(this).val()){
 		$(this).nextAll('input').val('').parents('.article-delivery-row').css('opacity',0.5);
 	} 
 	// if price is entered calculate price with vat in the next input
 	else{
 		// get percent from the next div where VAT is displayed like - 23%
		var vatHtml = $(this).nextAll('div').html();
		// split text by % sign
		var vatSplited = vatHtml.split('%');
		// get VAT percent number it will always be in array by index 0, because we just have splitted text from div by % sign
		var vat = vatSplited[0];
		// if we have no VAT for this delivery then use 0 VAT percent
		if (!vat){vat=0;}
		var price = parseFloat($(this).val());
		var priceWithVat = price+price*parseFloat(vat)/parseFloat('100.00');
		$(this).nextAll('input').val(priceWithVat.toFixed(2)).parents('.article-delivery-row').css('opacity',1);
	}
});

// this will calculate price without VAT for delivery depending on price with VAT
$('.rx-shop-delivery-price-with-vat').live('keyup',function() {
	var priceWithVat = parseFloat($(this).val());
	if(!priceWithVat){
		$(this).prevAll('input').val('');
	}
	else{
		var percent = parseFloat('100.00');
		var vatHtml = $(this).prevAll('div').html();
		// split text by % sign
		var vatSplited = vatHtml.split('%');
		// get VAT percent number it will always be in array by index 0, because we just have splitted text from div by % sign
		var vat = parseFloat(vatSplited[0]);
		// if we have no VAT for this delivery then use 0 VAT percent
		if (!vat){vat=0;}
		var newPrice = priceWithVat/(percent+vat)*percent;
		$(this).prevAll('input').val(newPrice.toFixed(2));
	}
});

// this will calculate price without VAT for the N E W delivery depending on price with VAT
$('.rx-shop-new-delivery-price-with-vat').live('keyup',function() {
	var priceWithVat = parseFloat($(this).val());
	if(!priceWithVat){
		$(this).prevAll('.rx-shop-new-delivery-price-and-vat').val('');
	}	
	else{
		var percent = parseFloat('100.00');
		var vat = parseFloat($(this).prevAll('select').find(':selected').attr('percent'));
		var newPrice = priceWithVat/(percent+vat)*percent;
		$(this).prevAll('.rx-shop-new-delivery-price-and-vat').val(newPrice.toFixed(2));
	}
});

// this will recalculate price with VAT if VAT category selection dropdownbox value is changed (product edit tab)
$('.rx-shop-change-vat').live('change',function() {
	var price = parseFloat($('.rx-shop-price-with-vat').prevAll('input').val());
	if(!price){
		$('.rx-shop-price-with-vat').val('');
	}
	else{
		var vat = parseFloat($(this).find(':selected').attr('percent'));
		var priceWithVat = price+price*vat/parseFloat('100.00');
		$('.rx-shop-price-with-vat').val(priceWithVat.toFixed(2));
	}
});

// If price with vat field in product edit tab changed change also price without vat field
$('.rx-shop-price-with-vat').live('keyup',function() {
	var priceWithVat = parseFloat($(this).val());
	if(!priceWithVat){
		$(this).prevAll('input').val('');
	}
	else{
		var percent = parseFloat('100.00');
		var vat = parseFloat($(this).parent().nextAll().find('select').find(':selected').attr('percent'));
		var newPrice = priceWithVat/(percent+vat)*percent; 
		$(this).prevAll('input').val(newPrice.toFixed(2));
	}
});

// this will calculate price with VAT for the new deliveries entered in the product edit mode
$('.rx-shop-new-delivery-price-and-vat').live('keyup',function() {
	// if price field is empty then change opacity to 0.5
	var price = parseFloat($(this).val());
	var priceWithVatInpt = $(this).nextAll('input');
	var vat = parseFloat($(this).nextAll('select').find(':selected').attr('percent'));
	if (!$(this).val()){
 		$(this).nextAll('input').val('').parents('.article-delivery-row').css('opacity',0.5);
 	} 
 	// if price is entered calculate price with vat in the next input
 	else{
 		var priceWithVat = price+price*vat/parseFloat('100.00');
		priceWithVatInpt.val(priceWithVat.toFixed(2)).parents('.article-delivery-row').css('opacity',1);
	}
});

// this will recalculate price with VAT if VAT category selection dropdown box value for the new delivery is changed
$('.rx-shop-new-delivery-vat-change').live('change',function() {
	var price = parseFloat($(this).prevAll('input').val());
	var priceWithVatInpt = $(this).nextAll('input');
	if(!price){
		priceWithVatInpt.val('');
	}
	else{
		var vat = parseFloat($(this).find(':selected').attr('percent'));
		var priceWithVat = price+price*vat/parseFloat('100.00');
		priceWithVatInpt.val(priceWithVat.toFixed(2)).parents('.article-delivery-row').css('opacity',1);
	}
});

// *********************************
// END OF PRICE WITH VAT CALCULATION
// *********************************

// functions to add and remove new delivery destination and price
$('.rx-shop-delivery-type-addOptionButton').live('focus',function() {
 	if ($(this).parent().is(':last-child')) {
  		$(this).parent().after($(this).parent().clone().css('opacity',0.5).find('input').val('').end()).css('opacity',1);
  		
  	}
});
$('.rx-shop-delivery-type-removeOptionButton').live('click',function() {
	 if ($('button',$(this).parent().parent()).size()>1)
	 	$(this).parent().remove();
});	
// functions to add and remove new delivery destination and price


$(function() {
rx.shopInit();
});

$.ajaxSetup({
complete: function() {
	rx.shopInit();
}
});

// Live events

rx.shopPathToModule = rx.getScriptPath('rxShop.js');