var jQuery = jQuery || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmCreate = $("#frmCreate"),
			validate = ($.fn.validate !== undefined),
			multilang = ($.fn.multilang !== undefined),
			datagrid = ($.fn.datagrid !== undefined);
		
		if (multilang && myLabel.isFlagReady == 1) {
			$(".multilang").multilang({
				langs: pjLocale.langs,
				flagPath: pjLocale.flagPath,
				tooltip: "",
				select: function (event, ui) {
					$("input[name='locale_id']").val(ui.index);					
				}
			});
		}
		
		if($(".touchspin3").length > 0)
		{
			$(".touchspin3").TouchSpin({
				verticalbuttons: true,
	            buttondown_class: 'btn btn-white',
	            buttonup_class: 'btn btn-white',
	            max: 4294967295
	        });
		}
		
		if ($frmCreate.length > 0 && validate) {
			$frmCreate.validate({
				onkeyup: false,
				submitHandler: function (form) {
					var price = parseFloat($('input[name="price"]').val());
					if(price <= 99999999999999.99)
					{
						var l = Ladda.create( $(form).find(":submit").get(0) );
						l.start();
						$.post("index.php?controller=pjAdminExtras&action=pjActionAddExtra", $(form).serialize()).done(function (data) {
							var content = $grid.datagrid("option", "content");
							$grid.datagrid("load", "index.php?controller=pjAdminExtras&action=pjActionGetExtras", content.column, content.direction, content.page, content.rowCount);
							$(form)[0].reset();
							$('.cpLimitedCount').show();
							l.stop();
							$(form).find(':input:enabled:visible:first').focus();
						}).always(function () {
							l.stop();
						});
					}else{
						swal({
			    			title: "",
							text: myLabel.prices_invalid_input,
							type: "warning",
							confirmButtonColor: "#DD6B55",
							confirmButtonText: "OK",
							closeOnConfirm: false,
							showLoaderOnConfirm: false
						}, function () {
							swal.close();
						});
					}
					return false;
				}
			});
		}
        
        function formatPrice (str, obj) {
			return obj.price_formated;
		}
		
		function formatPrice (str, obj) {
			return obj.price_formated;
		}
		
		if ($("#grid").length > 0 && datagrid) {
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminExtras&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminExtras&action=pjActionDelete&id={:id}"}
				          ],
		          columns: [{text: myLabel.name, type: "text", sortable: true, editable: pjGrid.hasAccessUpdate},
				          {text: myLabel.price, type: "text", sortable: true, editable: false, renderer: formatPrice},
				          {text: myLabel.count, type: "text", sortable: true, editable: false}
				          ],
				dataUrl: "index.php?controller=pjAdminExtras&action=pjActionGetExtras",
				dataType: "json",
				fields: ['name', 'price', 'cnt'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminExtras&action=pjActionDeleteBulk", render: true, confirmation: myLabel.delete_confirmation},
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminExtras&action=pjActionSaveExtra&id={:id}",
				select: {
					field: "id",
					name: "record[]",
					cellClass: 'cell-width-2'
				}
			});
		}
		
		
		$(document).on("submit", ".frm-filter", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this),
				content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache");
			$.extend(cache, {
				q: $this.find("input[name='q']").val()
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminExtras&action=pjActionGetExtras", content.column, content.direction, content.page, content.rowCount);
			return false;
		}).on("click", ".pj-table-icon-edit", function (e) {
			var $url = $(this).attr("href");
			$.get($url).done(function (data) {
				$(".boxFormExtra").html(data);
				if($(".touchspin3").length > 0)
				{
					$(".touchspin3").TouchSpin({
						verticalbuttons: true,
			            buttondown_class: 'btn btn-white',
			            buttonup_class: 'btn btn-white',
			            max: 4294967295
			        });
				}
				$("#frmUpdate").validate({
    				onkeyup: false,
    				submitHandler: function (form) {
    					var price = parseFloat($('input[name="price"]').val());
    					if(price <= 9999999.99)
    					{
	    					var l = Ladda.create( $(form).find(":submit").get(0) );
	    					l.start();
	    					$.post("index.php?controller=pjAdminExtras&action=pjActionUpdate", $(form).serialize()).done(function (data) {
	    						var content = $grid.datagrid("option", "content");
	    						$grid.datagrid("load", "index.php?controller=pjAdminExtras&action=pjActionGetExtras", content.column, content.direction, content.page, content.rowCount);
	    						if(pjGrid.hasAccessCreate == true)
	    						{
	    							$(".pjBtnCancelUpdateExtra").trigger("click");
	    						}else{
	    							$(".boxFormExtra").html("");
	    						}
	    						l.stop();
	    					}).always(function () {
	    						l.stop();
	    					});
    					}else{
    						swal({
				    			title: "",
								text: myLabel.prices_invalid_input,
								type: "warning",
								confirmButtonColor: "#DD6B55",
								confirmButtonText: "OK",
								closeOnConfirm: false,
								showLoaderOnConfirm: false
							}, function () {
								swal.close();
							});
    					}
    					return false;
    				}
    			});
			});
			return false;
		}).on("click", ".pjBtnCancelUpdateExtra", function (e) {
			if(pjGrid.hasAccessCreate == true)
			{
				var $url = 'index.php?controller=pjAdminExtras&action=pjActionCreate';
				$.get($url).done(function (data) {
					$(".boxFormExtra").html(data);
					if($(".touchspin3").length > 0)
					{
						$(".touchspin3").TouchSpin({
							verticalbuttons: true,
				            buttondown_class: 'btn btn-white',
				            buttonup_class: 'btn btn-white',
				            max: 4294967295
				        });
					}
					$("#frmCreate").validate({
						onkeyup: false,
						submitHandler: function (form) {
							var l = Ladda.create( $(form).find(":submit").get(0) );
							l.start();
							$.post("index.php?controller=pjAdminExtras&action=pjActionAddExtra", $(form).serialize()).done(function (data) {
								var content = $grid.datagrid("option", "content");
								$grid.datagrid("load", "index.php?controller=pjAdminExtras&action=pjActionGetExtras", content.column, content.direction, content.page, content.rowCount);
								$(form)[0].reset();
								$('.cpLimitedCount').show();
								l.stop();
							}).always(function () {
	    						l.stop();
	    					});
							return false;
						}
					});
				});
			}else{
				$(".boxFormExtra").html("");
			}
			return false;
		}).on("change", "select[name='type']", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var type = $(this).val();
			if(type == 'unlimited')
			{
				$('.cpLimitedCount').hide();
			}else{
				$('.cpLimitedCount').show();
			}
			return false;
		}).on("change", ".number", function (e) {
			var val = parseFloat(this.value);
		    if (!isNaN(val)) {
		    	this.value = val.toFixed(2);
		    	if (parseFloat(this.value) >= 99999999999999.99) {
			    	this.value = '99999999999999.99';
			    }
		    }
		});
	});
})(jQuery);