jQuery(function($) {
	/* DRAG AND DROP PRODUCT */
	+(function() {
		$('.loading').hide('fast');
		var proId = 0;
		$('.product-item').draggable({helper: 'clone', zIndex: 20,
			start: function(){
				proId = $(this).data('id');
				$('.sale-content').css('overflow-y', 'visible');
			},
			stop: function(){
				$('.sale-content').css('overflow-y', 'auto');
			}
		});
		$('.cart-item-container').droppable({
			drop: function(e, ui){
				orderProduct(proId,"");
			}
		});
		$('.product-list .product-item').on('click',function(e) {
			e.preventDefault();
			orderProduct($(this).data('id'),"");
		});

		/**
		 * Add Product To Cart
		 * @param  {integer} productId
		 * @param  {integer} sku
		 * @return {void}
		 */
		function orderProduct(productId,sku,amount,discount,price) {
			/* If Product ID is given */
			if(sku == ""){
				formData = "productId="+productId;
			}
			/* If SKU is submitted */
			else{
				formData = "sku="+sku;
			}
			if(!amount == ""){
				price = parseFloat(price);
				formData = formData.concat("&amount="+amount+"&discount="+discount+"&price="+price);
			}
			if($('#price_type').prop('checked')) {
				formData = formData.concat("&wholesale=true");
			}
			var storeProductUrl = $('.cart-item-container').data('store-product-url');
				$.ajax({
					type: "POST",
					url : storeProductUrl,
					data : formData,
					success : function(data){
							$('.loading').hide('fast');
							var returnData = data; //jQuery.parseJSON(data);
							toastr.options = {
								"progressBar": false,
								"positionClass": "toast-bottom-left",
								"hideMethod": "fadeOut"
							}
							if(returnData.error)
								toastr.error(returnData.message);
							else {
								var order = returnData.order;
								priceDollar = parseFloat(returnData.grand_total).toFixed(2);
								$('.price').html("$ "+parseFloat(returnData.grand_total).toFixed(2));
								$('.amount-price').html("$ "+parseFloat(returnData.total).toFixed(2));
								if(returnData.tax)
									$('.tax').html(parseInt(returnData.tax)+"%");
								else
									$('.tax').html("%");
								$('.price-riel').html("&#6107 "+parseFloat(returnData.total_riel).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
								$('.usd-price').val(parseFloat(returnData.grand_total).toFixed(2));
								$('.riel-price').val(parseFloat(returnData.total_riel).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());

								/* Update item to cart list container if inserted item is in the cart */
								if(returnData.update_item == true) {
									productItem = $('.cart-item-container ul').find('li[data-item-id="item'+order.product_id+'"]');
									$(".cart-item-container").animate({ scrollTop: productItem.position().top}, 1000);
									productItem.find('.badge').removeClass('hidden').html(order.amount);
									productItem.find('.price-val').html(parseFloat(order.price).toFixed(2));
									productItem.find('.discount-val').val(order.discount);
									if(order.discount != 0) {
										productItem.find('.discounted').addClass('badge bg-red').html("-"+order.discount+"%");
									}
									else {
										productItem.find('.discounted').html("");
									}

								}
								/* Add new item to cart list container if inserted item is not yet in the cart */
								else {
									var newItem = '\
									<li class="clearfix" data-toggle="modal" data-target=".item-list-modal" data-item-id="item'+order.product_id +'" data-order-id="'+order.id +'" data-product-id="'+order.product_id +'">\
										<div class="product-img">\
											<img src="'+order.thumbnail+'" class="img-circle">\
										</div>\
								   	<div class="product-text clearfix">\
											<div class="product-name">\
												<p>\
					   							<span class="title">\
					   								'+order.name +'\
					   							</span> \
					   							<span class="badge hidden bg-blue">'+order.amount  +'</span>\
					   						</p>\
												<p class="details">\
													'+order.name_kh +'\
												</p>\
											</div>\
											<div class="product-price">\
												$ <span class="price-val">'+parseFloat(order.price).toFixed(2)+'</span>';
												if(order.discount != null) {
													newItem += '<span class="discounted badge bg-red">'+"-"+order.discount+"%"+'</span>';
												}
												else {
													newItem += '<span class="discounted badge bg-red"></span>';
												}
												newItem +='\
												<input type="hidden" class="discount-val" value="'+order.discount +'">\
											</div>\
										</div>\
							   	</li>';
				   				$('.cart-item-container ul').append(newItem);
				   				$(".cart-item-container").animate({ scrollTop: $(".cart-item-container")[0].scrollHeight}, 1000);
			   				}
								toastr.success(returnData.message);

							}
					}
				},"json");
		}
		function removeItem(id) {
			/* If Product ID is given */
			productUrl = $('.cart-item-container').data('store-product-url');
			destroyProductUrl = productUrl+"/"+id;
				$.ajax({
					type: "DELETE",
					url : destroyProductUrl,
					success : function(data){
							$('.loading').hide('fast');
							var returnData = data //jQuery.parseJSON(data);
							toastr.options = {
								"progressBar": false,
								"positionClass": "toast-bottom-left",
								"hideMethod": "fadeOut"
							}
							if(returnData.error)
								toastr.error(returnData.message);
							else {
								var order = returnData.order;
								priceDollar = parseFloat(returnData.grand_total).toFixed(2);
								$('.price').html("$ "+parseFloat(returnData.grand_total).toFixed(2));
								$('.amount-price').html("$ "+parseFloat(returnData.total).toFixed(2));
								$('.tax').html(parseInt(returnData.tax)+"%");
								$('.price-riel').html("&#6107 "+parseFloat(returnData.total_riel).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
								$('.usd-price').val(parseFloat(returnData.grand_total).toFixed(2));
								$('.riel-price').val(parseFloat(returnData.total_riel).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
								$('.cart-item-container').find('li[data-order-id="'+id+'"]').slideUp('fast').remove();
								/* Add new item to cart list container if inserted item is not yet in the cart */
								toastr.success(returnData.message);
							}
					}
				},"json");
		}

		$('.submit_sku').on('submit',function(e) {
			e.preventDefault();
			sku = $(this).find('input[type=text]').val();
			orderProduct("",sku);
			$('.product_sku').val('');
		});
		$('.save-item').on('click',function(e){
			e.preventDefault();
			amount 		= 	$('.item-number input').val();
			price 		=		$('#item-price').val();
			discount 	=		$('#item-discount').val();
			productId =		$('#product-id').val();
			orderProduct(productId,"",amount,discount,price);
			$('.item-list-modal').modal('hide');
		});
		$('.edit-sidebar-item-form').on('submit',function(e){
			e.preventDefault();
			amount 		= 	$('.item-number input').val();
			price 		=		$('#item-price').val();
			discount 	=		$('#item-discount').val();
			productId =		$('#product-id').val();
			orderProduct(productId,"",amount,discount,price);
			$('.item-list-modal').modal('hide');
		});
		$('.remove-item').on('click',function(e){
			e.preventDefault();
			orderId =		$('#order-id').val();
			removeItem(orderId);
			$('.item-list-modal').modal('hide');
		});
		$('.search-product').on('select2:select', function (evt) {
  		orderProduct($(this).val(),"");
  		$(this).find('option').remove();
  		$('#select2-search-product-container').html('');
		});
	})();

	/**
	 * Filter Products
	 * @return {void}
	 */
	+(function() {
		function formatProduct (product) {
			var tUrl = $('.search-product').data('product-thumbnail-url');
      var markup = "<div class='select2-result-product clearfix'>" +
        "<div class='select2-result-product-thumbnail'><img class='img-responsive' src='"+ product.thumbnail + "' /></div>" +
        "<div class='select2-result-product-meta'>" +
          "<div class='select2-result-product-title'>" + product.name +  "</div>";

      if (product.name_kh) {
        markup += "<div class='select2-result-product-description'>" + product.name_kh + "</div>";
      }
      "</div></div>";

      return markup;
    }

    function formatProductSelection (product) {
      return product.name || product.name_kh;
    }
    $('.search-product').select2({
      ajax: {
        url: $('.search-product').data('product-list-url'),
        dataType: 'json',
        delay: 250,
        type: "GET",

        data: function (params) {
          return {
            term: params.term, // search term
          };
        },
        processResults: function (data, params) {
          // parse the results into the format expected by Select2
          // since we are using custom formatting functions we do not need to
          // alter the remote JSON data, except to indicate that infinite
          // scrolling can be used

          return {
            results: data.customers
          };
        },
        cache: false
      },
      escapeMarkup: function (markup) { return markup; },
      minimumInputLength: 3,
      placeholder: 'Find Products',
      templateResult: formatProduct,
      templateSelection: formatProductSelection
    });

	})();
	/**
	 * Filter Customer
	 * @return {void}
	 */
	+(function() {
    $('.customer').select2({
    	allowClear: true,
      ajax: {
        url: $(".customer").data('customer-list-url'),
        dataType: 'json',
        delay: 250,
        type: "GET",

        data: function (params) {
          return {
            term: params.term, // search term
          };
        },
        processResults: function (data, page) {
        	data = data.customers;
          return {
            results: $.map(data, function (item) {
                return {
                    text: item.last_name+" "+item.first_name,
                    id: item.id
                }
            })
        	};
        },
        cache: false
      },
      initSelection: function(element, callback) {
      	if($('.product-list > .row').data('customer-id')) {
      		$('select#select-customer').append($('<option>', {value:$('.product-list > .row').data('customer-id'), text:$('.product-list > .row').data('customer-name')}));
		    	callback({ id: $('.product-list > .row').data('customer-id'), text: $('.product-list > .row').data('customer-name') });
      	}
			},
      minimumInputLength: 3,
      placeholder: 'ស្វែងរកអតិថិជន',
      formatResult: function (data, term) {
        return data;
	    },
	    formatSelection: function (data) {
	        return data;
	    },
	    escapeMarkup: function (m) {
	        return m;
	    }
    });
    $('.customer').on('select2:unselect', function (evt) {
		  $(this).trigger('change');
		});




	})();
	/**
	 * Keycode Activation
	 */
	+(function(){
		$(document).bind('keydown', function (e){
			console.log(e.keyCode);
			switch(e.keyCode){
			case 117: //F6
			$('.barcode-input input[type="text"]').focus();
			return false;
			break;
			case 118: //F7
			$('#search-product').select2('open');
			return false;
			break;
			case 119: //F8
			$('.currency-modal').modal('show');
			return false;
			break;
			case 114: //F3
			$('.save-invoice').trigger('click');
			return false;
			break;

			}
		});
		keyCodeConvert = {
			49:0,
			50:1,
			51:2,
			52:3,
			53:4,
			54:5,
			55:6,
			56:7,
			57:8,
			58:9,
		};
		$(document).bind('keydown', function (e){
			productItem = $('.cart-item-container ul li');
			code = e.keyCode;
			if (e.ctrlKey){
				productItem.eq(keyCodeConvert[code]).trigger('click');
			}
		});
		$(document).bind('keydown', function (e){
			code = e.keyCode;
			if (code == 39 && e.shiftKey){
				$('#order-tab').trigger('click');
			}
			if (code == 37 && e.shiftKey){
				$('#product-tab').trigger('click');
			}
		});
		$('#input-dollar').keydown(function(e) {
			switch(e.keyCode){
				case 9: //F6
				$('#input-riel').focus();
				return false;
				break;
			}
		});
	})();

})
