var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmCreateVoucher = $("#frmCreateVoucher"),
			$frmUpdateVoucher = $("#frmUpdateVoucher"),
			spinner = ($.fn.spinner !== undefined),
			multiselect = ($.fn.multiselect !== undefined),
			datepicker = ($.fn.datepicker !== undefined),
			datagrid = ($.fn.datagrid !== undefined);
		
		if (multiselect) {
			$("#calendar_id").multiselect({
				noneSelectedText: myLabel.choose,
				close: function(event, ui){
					$("#calendar_id").valid();
			    }
			});
		}
		if (spinner) {
			$(".field-int").spinner({
				min: 1
			});
		}
		if ($frmCreateVoucher.length > 0 || $frmUpdateVoucher.length > 0) {
			jQuery.validator.addMethod("pjNumber", function(value, element) {
				
				var currency_format = parseInt($(element).attr('data-currency_format'), 10);
				var regex = /^((\d+)|(\d{1,3})(\,\d{3}|)*)(\.\d{1,2}|)$/;
				if(currency_format == 1)
				{
					regex = /^((\d+)|(\d{1,3})(\,\d{3}|)*)(\.\d{1,2}|)$/;
				}else if(currency_format == 2){
					regex = /^((\d+)|(\d{1,3})(\ \d{3}|)*)(\.\d{1,2}|)$/;
				}else if(currency_format == 3){
					regex = /^((\d+)|(\d{1,3})(\.\d{3}|)*)(\,\d{1,2}|)$/;
				}else if(currency_format == 4){
					regex = /^((\d+)|(\d{1,3})(\ \d{3}|)*)(\,\d{1,2}|)$/;
				}
				if(regex.test(value))
				{
					return true;
				}else{
					if(currency_format == 3 || currency_format == 4)
					{
						regex = /^((\d+)|(\d{1,3})(\\d{3}|)*)(\.\d{1,2}|)$/;
						if(regex.test(value))
						{
							return true;
						}else{
							return false;
						}
					}else{
						return false;
					}
				}
			});
		}
		if ($frmCreateVoucher.length > 0) {
							
			$frmCreateVoucher.validate({
				rules: {
					"code": {
						required: true,
						remote: "index.php?controller=pjAdminVouchers&action=pjActionCheckCode"
					}
				},
				messages: {
					"code": {
						remote: myLabel.code_exist
					}
				},
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'date_from' || element.attr('name') == 'date_to' || element.attr('name') == 'used_count')
					{
						error.insertAfter(element.parent().parent());
					}else if( element.attr('name') == 'discount'){
						error.insertAfter(element.parent().parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		}
		if ($frmUpdateVoucher.length > 0) {
			$frmUpdateVoucher.validate({
				rules: {
					"code": {
						required: true,
						remote: "index.php?controller=pjAdminVouchers&action=pjActionCheckCode&id=" + $frmUpdateVoucher.find("input[name='id']").val()
					}
				},
				messages: {
					"code": {
						remote: myLabel.code_exist
					}
				},
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'date_from' || element.attr('name') == 'date_to' || element.attr('name') == 'used_count')
					{
						error.insertAfter(element.parent().parent());
					}else if( element.attr('name') == 'discount'){
						error.insertAfter(element.parent().parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		}
		
		function formatDefault (str, obj) {
			if (obj.role_id == 3) {
				return '<a href="#" class="pj-status-icon pj-status-' + (str == 'F' ? '0' : '1') + '" style="cursor: ' +  (str == 'F' ? 'pointer' : 'default') + '"></a>';
			} else {
				return '<a href="#" class="pj-status-icon pj-status-1" style="cursor: default"></a>';
			}
		}
		function formatRole (str) {
			return ['<span class="label-status voucher-role-', str, '">', str, '</span>'].join("");
		}
		
		if ($("#grid").length > 0 && datagrid) {
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminVouchers&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminVouchers&action=pjActionDeleteVoucher&id={:id}"}
				          ],
				columns: [{text: myLabel.code, type: "text", sortable: true, editable: true, width: 200},
				          {text: myLabel.discount, type: "text", sortable: false, editable: false, width: 100},
				          {text: myLabel.valid, type: "text", sortable: false, editable: false}],
				dataUrl: "index.php?controller=pjAdminVouchers&action=pjActionGetVoucher",
				dataType: "json",
				fields: ['code', 'discount', 'valid'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminVouchers&action=pjActionDeleteVoucherBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminVouchers&action=pjActionExportVoucher", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminVouchers&action=pjActionSaveVoucher&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		$(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=pjAdminVouchers&action=pjActionGetVoucher", "code", "ASC", content.page, content.rowCount);
			return false;
		}).on("focusin", ".datepick", function (e) {
			if (datepicker) {
				var minDate, maxDate,
					$this = $(this),
					custom = {},
					o = {
						firstDay: $this.attr("rel"),
						dateFormat: $this.attr("rev"),
						dayNames: ($this.data("day")).split(","),
					    monthNames: ($this.data("months")).split(","),
					    monthNamesShort: ($this.data("shortmonths")).split(","),
					    dayNamesMin: ($this.data("daymin")).split(","),
						onClose: function (dateTimeText){
							$this.valid();
						}
				};
				switch ($this.attr("name")) {
				case "date_from":
					if($(".datepick[name='date_to']").val() != '')
					{
						maxDate = $(".datepick[name='date_to']").datepicker({
							firstDay: $this.attr("rel"),
							dateFormat: $this.attr("rev")
						}).datepicker("getDate");
						$(".datepick[name='date_to']").datepicker("destroy").removeAttr("id");
						if (maxDate !== null) {
							custom.maxDate = maxDate;
						}
					}
					break;
				case "date_to":
					if($(".datepick[name='date_from']").val() != '')
					{
						minDate = $(".datepick[name='date_from']").datepicker({
							firstDay: $this.attr("rel"),
							dateFormat: $this.attr("rev")
						}).datepicker("getDate");
						$(".datepick[name='date_from']").datepicker("destroy").removeAttr("id");
						if (minDate !== null) {
							custom.minDate = minDate;
						}
					}
					break;
				}
				$(this).datepicker($.extend(o, custom));
			}
		}).on("click", ".pj-form-field-icon-date", function (e) {
			var $dp = $(this).parent().siblings("input[type='text']");
			if ($dp.hasClass("hasDatepicker")) {
				$dp.datepicker("show");
			} else {
				$dp.trigger("focusin").datepicker("show");
			}
		}).on("click", "#valid", function (e) {
			var val = $(this).val(),
				valid_box = $('#valid_' + val);
			$('.valid-box').css('display', 'none');
			valid_box.css('display', 'block');
		}).on("click", "#type", function (e) {
			var sign = $('option:selected', this).attr('data-sign');
			$('#icon_type').html(sign);
			if($(this).val() == 'amount')
			{
				$('#discount').removeClass('number').addClass('pjNumber');
			}else{
				$('#discount').removeClass('pjNumber').addClass('number');
			}
		});
	});
})(jQuery_1_8_2);