var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmCreateDiscount = $("#frmCreateDiscount"),
			$frmUpdateDiscount = $("#frmUpdateDiscount"),
			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 ($frmCreateDiscount.length > 0 || $frmUpdateDiscount.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 ($frmCreateDiscount.length > 0) {
							
			$frmCreateDiscount.validate({
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'date_from' || element.attr('name') == 'date_to' || element.attr('name') == 'min_persons' || element.attr('name') == 'max_persons' || element.attr('name') == 'min_duration' || element.attr('name') == 'max_duration')
					{
						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: ""
			});
			
			updateOptions();
		}
		if ($frmUpdateDiscount.length > 0) {
			$frmUpdateDiscount.validate({
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'date_from' || element.attr('name') == 'date_to' || element.attr('name') == 'min_persons' || element.attr('name') == 'max_persons' || element.attr('name') == 'min_duration' || element.attr('name') == 'max_duration')
					{
						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: ""
			});
			updateOptions();
		}
		
		if ($("#grid").length > 0 && datagrid) {
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminDiscounts&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminDiscounts&action=pjActionDeleteDiscount&id={:id}"}
				          ],
				columns: [{text: myLabel.name, 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=pjAdminDiscounts&action=pjActionGetDiscount",
				dataType: "json",
				fields: ['name', 'discount', 'valid'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminDiscounts&action=pjActionDeleteDiscountBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminDiscounts&action=pjActionExportDiscount", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminDiscounts&action=pjActionSaveDiscount&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=pjAdminDiscounts&action=pjActionGetDiscount", "name", "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');
			}
		}).on("click", "#options", function (e) {
			updateOptions();
		}).on("keydown", ".abOptions", function (e) {
			if (e.shiftKey == true) {
                e.preventDefault();
            }
			if ((e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105) || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 37 || e.keyCode == 39 || e.keyCode == 46) {
				
            } else {
            	e.preventDefault();
            } 
		});
		
		function updateOptions()
		{
			var opt = $('#options').val();
			$('.optionsBox').hide();
			$('.'+opt+'Box').show();
			
			$('.abOptions').removeClass('required').removeClass('number');
			
			if(opt == 'early')
			{
				$('#early_days').addClass('required').addClass('number');
			}else if(opt == 'persons'){
				$('#min_persons').addClass('required').addClass('number');
				$('#max_persons').addClass('required').addClass('number');
			}else if(opt == 'duration'){
				$('#min_duration').addClass('required').addClass('number');
				$('#max_duration').addClass('required').addClass('number');
			}else{
				
			}
		}
	});
})(jQuery_1_8_2);