var ShopApplication = function(){

	this.FORM_APPLICATION = 'shop';
	
	this.FORM_APPLICATION_BASKET = 'basket';
	this.FORM_ACTION_BASKET_ADD = 'addProduct';
	this.FORM_ACTION_BASKET_NEW = 'add';
	this.FORM_ACTION_BASKET_SAVE = 'save';
	this.FORM_ACTION_BASKET_VIEW = 'view';
	this.FORM_ACTION_BASKET_VIEWLIST = 'viewList';
	this.FORM_ACTION_BASKET_UPDATE = 'update'; //
	this.FORM_ACTION_BASKET_RESET = 'reset';
	this.FORM_ACTION_BASKET_DELETE = 'delete';
	this.FORM_ACTION_BASKET_SET_DEFAULT = 'setDefault';
	this.FORM_ACTION_BASKET_GET_INFO = 'get';
	this.FORM_ACTION_BASKET_GET_SHIPPING_INFO = 'getShippingCost';
	this.FORM_ACTION_BASKET_CHECKOUT = 'checkout';
	this.FORM_ACTION_BASKET_CHECK_AVAILABLE = 'isAvailable';
	this.FORM_ACTION_BASKET_REMOVE_PRODUCT = 'removeProduct';
	
	this.FORM_APPLICATION_PRODUCT = 'shop'; 
	this.FORM_ACTION_PRODUCT_GETBOUGTH = 'boughtProducts';
	this.FORM_ACTION_PRODUCT_GETRELATED = 'relaitedProducts';
	
	
	this.FORM_APPLICATION_USER = 'user';
	this.FORM_ACTION_USER_INFO = 'getContact';
	
	this.BASKET_INFO_CONTAINER = '#basket-sub-menu-item';
	this.BASKET_AMOUNT_CONTAINER = '.basketAmount';
	this.BASKET_SUMM_CONTAINER = '.basketSumm';
	this.BASKET_NAME_CONTAINER = '.basketName';
	
	this.BASKET_AMOUNT_TPL = '%';
	this.BASKET_SUMM_TPL = '%';
	this.BASKET_NAME_TPL = '%';
	
	this.ORDER_INFO_CONTAINER = '#basket-checkout-form';
	this.ORDER_SHIPPING_CONTAINER = '#order-total-shipping';
	
	
	this.addToCompare = function(product_id) {
		var current_compare = cmsCookieManager.get("compare_products");
		
		if(typeof(current_compare) != 'undefined' && current_compare != '') {
			
			current_compare = current_compare.split(',');			
			if(current_compare.indexOf(product_id) >= 0) return;
		}
		
		var compare_count = cmsCookieManager.get("compare_count");
		
		if(typeof(compare_count) == 'undefined' || isNaN(compare_count) || compare_count < 1) compare_count = 0;
		
		compare_count++;
		
		cmsCookieManager.set("compare_count", compare_count);
		
		if(typeof(current_compare) != 'undefined' && current_compare.length > 0 && current_compare != '') current_compare = current_compare + "," + product_id;
		else current_compare = product_id;
		
		cmsCookieManager.set("compare_products", current_compare);
		
		$(".ico-difference-box-count").html( compare_count );
	}
	
	this.removeFromCompare = function(product_id) {
		var current_compare = cmsCookieManager.get("compare_products");
	
		if(typeof(current_compare) != 'undefined') {
			current_compare = current_compare.split(',');

			if(current_compare.indexOf(product_id) >= 0) {
				current_compare.splice((current_compare.indexOf(product_id)), 1);
				cmsCookieManager.set("compare_products", current_compare.join(','));
			
				var compare_count = current_compare.length;
				cmsCookieManager.set("compare_count", compare_count);
				
				var dialog_id = $(".product-compare-" + product_id).parents(".ui-dialog-content").attr('id');
				cmsAdministration.loadForm('shop', 'compare', '#'+dialog_id);
				
				$(".ico-difference-box-count").html( compare_count );
			}
		}
	}
	
	this.viewCompare = function() {
		cmsClient.showAjaxForm('shop', 'compare', '', {}, {width: 1220, height: 720, draggable: true})
	}
	
	this.increaseQuantity = function(el_id) {
		var current_value = cmsMath.parseCommaFormatted( jQuery("input[name='product[" + el_id + "][amount]']").val() );
		var new_value = ( current_value + 1 );
		jQuery("input[name='product[" + el_id + "][amount]']").val( new_value );
		
		this.updateProductSumm(el_id);
	}
	
	this.decreaseQuantity = function(el_id, el_count, custom_function) {
		var current_value = cmsMath.parseCommaFormatted( jQuery("input[name='product[" + el_id + "][amount]']").val() );
		var new_value = ( current_value - 1 );
		if(new_value < 0) new_value = 0;
		jQuery("input[name='product[" + el_id + "][amount]']").val( new_value );
		
		if(typeof(custom_function) != 'undefined') custom_function(el_id, el_count, current_value, new_value);
		
		
		this.updateProductSumm(el_id);
	}
	
	this.updateProductSumm = function(el_id) {
		var product_price = cmsMath.parseCommaFormatted( jQuery("#product_" + el_id + "_price").html() );
		var product_amount = cmsMath.parseCommaFormatted( jQuery("input[name='product[" + el_id + "][amount]']").val() );
		var new_summ = cmsMath.roundNumber( (product_price * product_amount), 2);
		new_summ = new_summ.toFixed(2);
			
		jQuery("#product_" + el_id + "_summ").html( cmsMath.formatAmount(new_summ) );
		
		this.updateTotal();
	}
	
	this.updateTotal = function() {
		var products_list = jQuery("input[name='products[]']");
		var total_summ = 0;
		var final_summ = 0;
				
		for(var i=0; i<products_list.length; i++) {
			var el_id = jQuery(products_list[i]).val();
			var product_price = cmsMath.parseCommaFormatted( jQuery("#product_" + el_id + "_price").html() );
			var product_amount = cmsMath.parseCommaFormatted( jQuery("input[name='product[" + el_id + "][amount]']").val() );
			
			total_summ = cmsMath.roundNumber( (total_summ + (product_price * product_amount)), 2);
		}
		total_summ = total_summ.toFixed(2);
		
		jQuery('#basket-total-summ').html( cmsMath.formatAmount(total_summ) );
	}
	
	this.updateUsedBonus = function() {
		var max_bonus = cmsMath.parseCommaFormatted( jQuery('#user_has_bonus').html() );
		var use_bonus = cmsMath.parseCommaFormatted( jQuery('#order_use_bonus').val() );
		var basket_summ = cmsMath.parseCommaFormatted( jQuery('#order-total-summ').html() );
		var shipping_price = cmsMath.parseCommaFormatted( jQuery('#order-total-shipping').html() );

		var tax_summ = cmsMath.parseCommaFormatted( jQuery('#order-tax-price').html() );
		var total_summ = (basket_summ + shipping_price + tax_summ);
		
		if(!new RegExp("^[0-9]{1,}$", "g").test(use_bonus)) return;
		
		if(use_bonus > max_bonus) use_bonus = max_bonus;
		if(use_bonus > total_summ) use_bonus = total_summ;
		
		use_bonus = cmsMath.roundNumber(use_bonus, 2);
		
		jQuery('#order_use_bonus').val( use_bonus );
		jQuery('#order-bonus-spend').html( use_bonus );
		this.updateFinal();
	}
	
	this.updateFinal = function() {
		var final_summ = 0;
		var tax_summ = 0;
		var tax = cmsMath.parseCommaFormatted( jQuery('#order-tax').html() );
		var basket_summ = cmsMath.parseCommaFormatted( jQuery('#order-total-summ').html() );
		var shipping_price = cmsMath.parseCommaFormatted( jQuery('#order-total-shipping').html() );
		var total_summ = (basket_summ + shipping_price);
		var use_bonus = cmsMath.parseCommaFormatted( jQuery('#order_use_bonus').val() );
		
		tax_summ = cmsMath.roundNumber( ( (total_summ * tax ) / 100), 2);
		total_summ = total_summ + tax_summ;
		final_summ = cmsMath.roundNumber( (total_summ - use_bonus), 2);
		
		jQuery('#order-tax-price').html( cmsMath.formatAmount(tax_summ) );
		jQuery('#order-final-summ').html( cmsMath.formatAmount(final_summ) );
	}
	
	this.addToBasket = function(basket, product, product_amount, product_info){
		if($('#product_' + product + '_basket').find('option:selected').length > 0 && $('#product_' + product + '_basket').find('option:selected').val().length > 0) {
			var new_basket = $('#product_' + product + '_basket').find('option:selected').val();
			if(basket != new_basket) {
				// change the selectbox values
				$('.basketSelectBox').find('option:selected').removeAttr('selected');
				$('.basketSelectBox').find('option[value=' + new_basket + ']').attr('selected', 'selected');
				// re-init the selectbox
				$('.basketSelectBox').parents('.jquery-selectbox').unselectbox();
				$('.basketSelectBox').selectbox();
			}
			basket = new_basket;
		}
		
		var dialog_params = {
			open: function(event, ui) { 
				var title = $('.form-title', $(this)).html();
				if(title != null && typeof(title) != 'undefined' && title.length > 0) {
					$('.ui-dialog-title', $(this).parent()).html( title );
					$('.form-title', $(this)).hide();
				}
				
				if(typeof(cmsAdministration) != 'undefined') cmsAdministration.init();
				cmsShop.updateBasketInfo(basket);
			}
		};
		
		var dialog_buttons = {};
		dialog_buttons[$t('button.ok', '', false)] = function() {
			$(this).dialog("close");
		};
		
		if(typeof(product_info) == 'undefined') product_info = '';
		
		var submit_params = {id_basket: basket, id_product: product, amount: product_amount, info: product_info};
		cmsClient.showAjaxForm(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_ADD, submit_params, dialog_buttons, dialog_params);
	}
	
	
	this.addNewBasket = function(body){
		var dialog_buttons = {};
		dialog_buttons[$t('button.add_cart', '', false)] = function() {
	
			cmsClient.postForm(cmsShop.FORM_APPLICATION_BASKET, cmsShop.FORM_ACTION_BASKET_NEW, $('form', $(this)).attr('id'), $.extend({operation: 'save'}, {layout: 'ajax'}), function() {
				cmsClient.loadForm(cmsShop.FORM_APPLICATION_BASKET, cmsShop.FORM_ACTION_BASKET_VIEWLIST, body);
			});
			$(this).dialog("close");
		};
		
		dialog_buttons[$t('button.cancel', '', false)] = function() {
			$(this).dialog("close");
		};
		
		if(typeof(body) == 'undefined') body = 'reload';
		
		cmsClient.showAjaxForm(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_NEW, {layout: 'ajax'}, dialog_buttons);
	}
	
	this.saveBasket = function(basket, body, defaultBasket){
		if(typeof(body) == 'undefined') body = 'reload';
		
		cmsClient.showAjaxEdit(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_SAVE, {id_basket: basket}, function() { 
			cmsClient.loadForm(cmsShop.FORM_APPLICATION_BASKET, cmsShop.FORM_ACTION_BASKET_VIEWLIST, body);
			if(typeof(defaultBasket) != 'undefined') cmsShop.updateBasketInfo(defaultBasket);
		});
		
	}
	
	this.viewBasketList = function(body){
	 	cmsClient.loadForm(cmsShop.FORM_APPLICATION_BASKET, cmsShop.FORM_ACTION_BASKET_VIEWLIST, body);
	}

	this.viewBasket = function(basket, body){
		if(typeof(body) == 'undefined') body = 'reload';
		cmsClient.loadForm(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_VIEW, body, {id: basket});
	}
	
	
	//basket - basket ID, form - form ID, body - ID element for layout
	this.updateBasket = function(form, body, defaultBasket){
		if(typeof(body) == 'undefined') body = 'reload';
		cmsClient.postForm(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_UPDATE, form, {show_responce: '#basket-profile-list'}, function () {
			if(typeof(defaultBasket) != 'undefined') cmsShop.updateBasketInfo(defaultBasket);
			
		});
	}
	
	this.removeProductFromBasket = function (basket, product, body){
		if(typeof(body) == 'undefined') body = 'reload';
		cmsClient.loadForm(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_REMOVE_PRODUCT, body, {id_basket: basket, id_product: product});
	}
	
	
	this.resetBasket = function(basket, body){
		var dialog_buttons = {};
		if(typeof(body) == 'undefined') body = 'reload';
		dialog_buttons[$t('button.empty', '', false)] = function() {
			cmsClient.postForm(cmsShop.FORM_APPLICATION_BASKET, cmsShop.FORM_ACTION_BASKET_RESET, $('form', $(this)).attr('id'), {id_basket: basket, operation: 'reset'}, function() {
				cmsClient.loadForm(cmsShop.FORM_APPLICATION_BASKET, cmsShop.FORM_ACTION_BASKET_VIEWLIST, body);
			});
			$(this).dialog("close");
		};
		dialog_buttons[$t('button.cancel', '', false)] = function() {
			$(this).dialog("close");
		};
		
		cmsClient.showAjaxForm(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_RESET, {id_basket: basket}, dialog_buttons);
		return false;
	}
	
	this.deleteBasket = function(basket, body) {
		var dialog_buttons = {};
		if(typeof(body) == 'undefined') body = 'reload';
		dialog_buttons[$t('button.delete', '', false)] = function() {
			cmsClient.postForm(cmsShop.FORM_APPLICATION_BASKET, cmsShop.FORM_ACTION_BASKET_DELETE, $('form', $(this)).attr('id'), {id_basket: basket, operation: 'delete'}, function() {
				cmsClient.loadForm(cmsShop.FORM_APPLICATION_BASKET, cmsShop.FORM_ACTION_BASKET_VIEWLIST, body);
			});
			$(this).dialog("close");
		};
		dialog_buttons[$t('button.cancel', '', false)] = function() {
			$(this).dialog("close");
		};
		
		cmsClient.showAjaxForm(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_DELETE, {id_basket: basket}, dialog_buttons);
	}
	
	this.basketCheckout = function(form_selector) {
		var validation_rules = {
			0:['length','order[shipping][firstname]','#i_email_err','', true, form_selector]
		 	,1:['length','order[shipping][lastname]','#i_date_err','', true, form_selector]
		};
		cmsClient.submitForm(validation_rules, this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_CHECKOUT, form_selector, {}, this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_CHECKOUT, 'window', {})
	}
	
	/*
	 * basket - id basket
	 * reload_item - action for responce after set basket active 
	 * 		'reload'    - reload page
	 * 		'set_only'  - set basket, not reload  
	 * 		reload_item - insert result in some element in DOM
	 * 		 
	 * 
	 */
	
	this.setDefaultBasket = function(basket, reload_item){
		if(typeof(reload_item) == 'undefined')reload_item = 'reload';

		if(reload_item == 'reload'){
			cmsClient.loadForm(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_SET_DEFAULT, 'reload', {id_basket: basket});
		}else{
			cmsClient.postForm(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_SET_DEFAULT, '', {id_basket: basket, show_loading: false, show_responce: false}, function (){
				if(reload_item != 'set_only'){
					cmsClient.loadForm(cmsShop.FORM_APPLICATION_BASKET, cmsShop.FORM_ACTION_BASKET_VIEWLIST, reload_item, {}, function () {
						cmsShop.updateBasketInfo(basket);
					}); 
				}
			});
			
		}
		
	}
	
	this.updateBasketInfo = function(basket, amount_tpl, summ_tpl, name_tpl){
		if(typeof(amount_tpl) != 'undefined' && amount_tpl != '') cmsShop.BASKET_AMOUNT_TPL = amount_tpl;
		if(typeof(summ_tpl) != 'undefined' && summ_tpl != '') cmsShop.BASKET_SUMM_TPL = summ_tpl;
		if(typeof(name_tpl) != 'undefined' && name_tpl != '') cmsShop.BASKET_NAME_TPL = name_tpl;
		
		cmsClient.ajaxGetData(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_GET_INFO, {id_basket: basket, show_loading: false, show_errors: false}, function(response){
			var response_data = cmsClient.pareseXMLResponse(response);
			response_data = $(response_data).find('data').text();
			response_data = $.evalJSON(response_data);
			
			if(typeof(response_data.amount) != 'undefined'){
				$(cmsShop.BASKET_AMOUNT_CONTAINER, cmsShop.BASKET_INFO_CONTAINER).html( cmsShop.BASKET_AMOUNT_TPL.replace('%', response_data.amount) );
			}
			
			var basketSumm = response_data.summ;

			if(typeof(response_data.summ) != 'undefined'){
				$(cmsShop.BASKET_SUMM_CONTAINER, cmsShop.BASKET_INFO_CONTAINER).html( cmsShop.BASKET_SUMM_TPL.replace('%',  cmsMath.number_format(response_data.summ, 2, '.', ' ') ) );
			}
			if(typeof(response_data.summ) != 'undefined'){
				$(cmsShop.BASKET_NAME_CONTAINER, cmsShop.BASKET_INFO_CONTAINER).html( cmsShop.BASKET_NAME_TPL.replace('%', response_data.name) );
			}
		});
	}
	
	this.fillShippingInfo = function(element_selector, info_type) {
		if(typeof(info_type) == 'undefined') info_type = 'shipping';
		
		if($(element_selector).is(':checked')){
			// Get The info from db and fill the fields
			cmsClient.ajaxGetData(this.FORM_APPLICATION_USER, this.FORM_ACTION_USER_INFO, {type: info_type}, function(response){
				var response_data = cmsClient.pareseXMLResponse(response);
				response_data = $(response_data).find('data').text();
				response_data = $.evalJSON(response_data);
				
				for(key in response_data) {
					if(key == "key_country"){
						$('select[name="order[shipping][country]"]').val(response_data[key]);
						$('.shipping-country .jquery-selectbox-currentItem:first').html(response_data['country_name']);
						//$('select[name="order[shipping][country]"]').parents('.sauna-select-box-set:first').fing('.jquery-selectbox-currentItem: first').html(response_data[key]); //select box container
						//$(conteiner + ' .jquery-selectbox-currentItem ').html(response_data['country_name']);
					} else {
						if($('input[name="order[shipping][' + key + ']"]').attr("readonly") != true) $('input[name="order[shipping][' + key + ']"]').val( response_data[key] );
					}
				}		
				
				submitForm('#basket-checkout-form', false);
			});
		} else {
			// Empty the fields
			$('input[name^="order[shipping]"]').val('');
			$('select[name="order[shipping][country]"]').find('option:selected').removeAttr('selected');
			$('.shipping-country .jquery-selectbox-currentItem:first').html($t('select.country'));
		}
	}
	
	this.updateShippingCost = function(form_selector, success_handler) {
		if(!submitForm('#basket-checkout-form', false)) return;
		
		$('#button_update_shipping').removeClass('validation_error');
		
		cmsClient.ajaxGetData(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_GET_SHIPPING_INFO, {form_id: form_selector}, function(response){
			// Have we got an error?
			if(response.length > 0 && $(response).find('#error-list').length > 0)
			{
				cmsClient.showError($(response).find('#error-list').html());
			} else {
				var response_data = cmsClient.pareseXMLResponse(response);
				response_data = $(response_data).find('data').text();
				response_data = $.evalJSON(response_data);
				
				if(typeof(response_data.error) != 'undefined'){
					alert(response_data.error);
					//$(cmsShop.BASKET_AMOUNT_CONTAINER, cmsShop.BASKET_INFO_CONTAINER).html(response_data.amount);
				}
				if(typeof(response_data.price) != 'undefined'){
					var shipping_price = response_data.price;
					
					$(cmsShop.ORDER_SHIPPING_CONTAINER, cmsShop.ORDER_INFO_CONTAINER).html(cmsMath.number_format(cmsMath.parseCommaFormatted(shipping_price), 2, '.', ' '));
					
					cmsShop.updateFinal();
					
					if(typeof(success_handler) != 'undefined') success_handler(form_selector, response_data);
				}
			}
		});
	}
	
	this.unsetVariantSelection = function(group_id, propertie_id) {
		jQuery('#properties_' + group_id + '_' + propertie_id).val(''); 
	}
	
	this.setVariantSelection = function(product_id, group_id, propertie_id, value, menu_id) {
		if(typeof(menu_id) == 'undefined') menu_id = '';
		this.clearVariantSelection(value);
		jQuery('#properties_' + group_id + '_' + propertie_id).val(value); 
		cmsClient.postForm('shop', 'sameProducts', 'product-variants-form', {show_loading: false, show_responce: '#product-variants-container', id: product_id, menu_id: menu_id});
	}
	
	this.clearVariantSelection = function(new_value) {
		jQuery('input[name^=properties]').each(function(i, val) {
			var has_new = false;
			var old_val = $(this).val();
			if(old_val.length == 0) return;
			
			old_val = old_val.split(',');
			
			for(var i = 0; i<old_val.length; i++) {
				if(new_value.indexOf(old_val[i]) != -1) has_new = true;
			}
			
			if(!has_new) {
				$(this).val('');
			}
		});
	}
	
	this.updateVariantPrice = function() {
		
	}
	
	this.isAvailable = function(form_id, success_handler, error_handler) {
		cmsClient.postForm(this.FORM_APPLICATION_BASKET, this.FORM_ACTION_BASKET_CHECK_AVAILABLE, form_id, {show_loading: false}, function(response){
			// Have we got an error?
			if(response.length > 0 && $(response).find('#error-list').length > 0)
			{
				if(typeof(error_handler) == 'function') {
					error_handler(response, '#' + form_id);
					if(typeof(cmsAdministration) != 'undefined') cmsAdministration.init();
				} else {
					cmsClient.showError($(response).find('#error-list').html());
					jQuery('#' + form_id).find('.submitButton').hide();
				}
			} else {
				if(typeof(success_handler) == 'function') {
					success_handler(response, '#' + form_id);
					if(typeof(cmsAdministration) != 'undefined') cmsAdministration.init();
				} else {
					jQuery('#' + form_id).find('.submitButton').show();
				}
			}
		}, false);
	}
	
	this.selectPaymentMethod = function(field_selector, code, rule_field_selector, form_selector) {
		if(typeof(rule_field_selector) != 'undefined' && rule_field_selector != false) {
			if(!jQuery(rule_field_selector).is(':checked')){
				cmsClient.showError($t('err_payment.terms'));
				return;
			}
		}
		
		if(typeof(field_selector) != 'undefined' && field_selector != false) {
			jQuery(field_selector).val(code);
		}
		
		if(typeof(form_selector) != 'undefined') {
			cmsClient.showLoading( $t('msg_payment.processing') );
			jQuery(form_selector).submit();
		}		
	}
	
	this.loadBoughtProducts = function(page, product, body){
		if( product == false)return false;
		if(typeof(body) == 'undefined') body = 'reload';
		cmsClient.loadForm(cmsShop.FORM_APPLICATION_PRODUCT, cmsShop.FORM_ACTION_PRODUCT_GETBOUGTH, body,{inPage: page, id: product});
	} 
	
	this.loadRelatedProducts = function(page, product, body){
		if( product == false)return false;
		if(typeof(body) == 'undefined') body = 'reload';
		cmsClient.loadForm(cmsShop.FORM_APPLICATION_PRODUCT, cmsShop.FORM_ACTION_PRODUCT_GETRELATED, body,{inPage: page, id: product});
	}	
}

var cmsShop = new ShopApplication();
