var jQuery = jQuery || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmUpdatePrice = $("#frmUpdatePrice"),
			$frmUpdateDiscount = $("#frmUpdateDiscount"),
			dialog = ($.fn.dialog !== undefined),
			validate = ($.fn.validate !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			$datepick = $(".datepick"),
			datepicker = ($.fn.datepicker !== undefined);

		if($(".touchspin3").length > 0)
		{
			$(".touchspin3").TouchSpin({
				verticalbuttons: true,
	            buttondown_class: 'btn btn-white',
	            buttonup_class: 'btn btn-white',
	            max: 4294967295
	        });
		}
		
		if ($('#datePickerOptions').length) {
        	$.fn.datepicker.dates['en'] = {
        		days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
    		    daysMin: $('#datePickerOptions').data('days').split("_"),
    		    daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
    		    months: $('#datePickerOptions').data('months').split("_"),
    		    monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
    		    format: $('#datePickerOptions').data('format'),
            	weekStart: parseInt($('#datePickerOptions').data('wstart'), 10),
    		};
        };
        
        function myDatepickInit() {
        	$datepick.datepicker({autoclose: true}).on('changeDate', function (selected) {
        		var idx = $(this).closest('tr').attr('data-id'),
        			element_id = $(this).attr('id');        		
        		if (parseInt(element_id.indexOf("date_from_"), 10) >= 0) {
	        		var $toElement = $("#date_to_" + idx);
        			if($toElement.length > 0)
        			{
        				var $minDate = new Date(selected.date.valueOf());
        				$toElement.datepicker('setStartDate', $minDate);
        				if ($toElement.val() != '') {
	        				var date_to_value = $toElement.datepicker("getUTCDate");
	        				if(date_to_value < selected.date)
	    					{
	        					$toElement.val($(this).val());
	    					}
        				} else {
        					$toElement.val($(this).val());
        				}
        			}
        		}

        		if (parseInt(element_id.indexOf("date_to_"), 10) >= 0) {
        			var $fromElement = $("#date_from_" + idx),
        				$toElement = $("#date_to_" + idx);
        			if($fromElement.length > 0 && $toElement.length > 0)
        			{
        				var $maxDate = new Date(selected.date.valueOf());
        				$fromElement.datepicker('setEndDate', $maxDate);
        				if ($fromElement.val() != '') {
	        				var date_from_value = $fromElement.datepicker("getUTCDate");
	        				if(date_from_value > selected.date)
	    					{
	        					$fromElement.val($toElement.val());
	    					}
        				}
        			}
        		}
            });
        }
		
		if ($frmUpdatePrice.length > 0 && validate) {
			$frmUpdatePrice.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				ignore: "",
				submitHandler: function(form){
					$.ajax({
	        	        type: "POST",
	        	        url: "index.php?controller=pjAdminPrices&action=pjActionCheckDates",
	        	        data: $(form).serialize(),
	        	        async:true,
	        	        success: function (data) {
	        	        	if(data.status == 'OK')
	        	        	{
	        	        		var l = Ladda.create( $(form).find(":submit").get(0) );
								l.start();
								form.submit();
	        	        	}else{
	        	        		swal({
	    			    			title: "",
	    							text: data.text,
	    							type: "warning",
	    							confirmButtonColor: "#DD6B55",
	    							confirmButtonText: "OK",
	    							closeOnConfirm: false,
	    							showLoaderOnConfirm: false
	    						}, function () {
	    							swal.close();
	    						});
	        	        	}
	        	        }
	        	    });
					return false;
				}
			});
		}
		
		if ($frmUpdateDiscount.length > 0 && validate) {
			$frmUpdateDiscount.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				ignore: "",
				submitHandler: function(form){
					var duplidated = false,
						$duplicated_tr = null,
						$duplicated_next_tr = null;
					$('#tblDiscounts > tbody > tr').each(function(index){
						var $tr = $(this),
							id = $tr.attr('data-id'),
							space_id = $('select[name="space_id['+id+']"]').val(),
							price_id = $('select[name="price_id['+id+']"]').val(),
							min_days = $('input[name="min_days['+id+']"]').val(),
							max_days = $('input[name="max_days['+id+']"]').val();
						$('#tblDiscounts > tbody > tr').each(function(idx){
							if ($(this).find('.cpNoDiscounts').length > 0) {
								/* TO DO */
							} else {
								if(idx > index)
								{
									var $next_tr = $(this),
										next_id = $next_tr.attr('data-id'),
										next_space_id = $('select[name="space_id['+next_id+']"]').val(),
										next_price_id = $('select[name="price_id['+next_id+']"]').val(),
										next_min_days = $('input[name="min_days['+next_id+']"]').val(),
										next_max_days = $('input[name="max_days['+next_id+']"]').val();
								}
								
								if(space_id == next_space_id && price_id == next_price_id && min_days == next_min_days && max_days == next_max_days)
								{
									duplidated = true;
									$duplicated_tr = $tr;
									$duplicated_next_tr = $next_tr;
										
									return false;
								}
							}
						});
					});
					if(duplidated == true)
					{
						$('#duplicateDiscountsModal').data('tr', $duplicated_tr).data('next_tr', $duplicated_next_tr).modal('show');
					}else{
						var l = Ladda.create( $(form).find(":submit").get(0) );
						l.start();
						return true;
					}
					return false;
				}
			});
		}
		
		$(document).on("click", ".cpAddPrice", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			
			var $tbody = $("#tblPrices tbody"),
				index = Math.ceil(Math.random() * 999999);
			
			var clone_text = $("#tblPricesClone").find("tbody").html();
			clone_text = clone_text.replace(/\{INDEX\}/g, 'cp_' + index);
			if($tbody.find(".cpNoPrices").length == 0)
			{
				$tbody.append(clone_text);
			}else{
				$tbody.html(clone_text);
			}
			$datepick = $('.datepick');
			if ($datepick.length > 0) {
				myDatepickInit.call(null);
	        }
		}).on("click", ".cpRemovePrice", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $tbody = $("#tblPrices tbody"),
				$tr = $(this).closest("tr");
			$tr.css("backgroundColor", "#FFB4B4").fadeOut("slow", function () {
				$tr.remove();
				if($tbody.find('tr').length == 0)
				{
					$tbody.html('<tr><td colspan="5" class="cpNoPrices">'+myLabel.no_prices_defined+'</td></tr>');
				}
			});	
			return false;
		}).on("click", ".cpAddDiscount", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			
			var $tbody = $("#tblDiscounts tbody"),
				index = Math.ceil(Math.random() * 999999);
			
			var clone_text = $("#tblDiscountsClone").find("tbody").html();
			clone_text = clone_text.replace(/\{INDEX\}/g, 'cp_' + index);
			if($tbody.find(".cpNoDiscounts").length == 0)
			{
				$tbody.append(clone_text);
			}else{
				$tbody.html(clone_text);
			}
			if($(".touchspin3_cp_" + index).length > 0)
			{
				$(".touchspin3_cp_" + index).TouchSpin({
					verticalbuttons: true,
		            buttondown_class: 'btn btn-white',
		            buttonup_class: 'btn btn-white',
		            max: 4294967295
		        });
			}
		}).on("click", ".cpRemoveDiscount", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $tbody = $("#tblDiscounts tbody"),
				$tr = $(this).closest("tr");
			$tr.css("backgroundColor", "#FFB4B4").fadeOut("slow", function () {
				$tr.remove();
				if($tbody.find('tr').length == 0)
				{
					$tbody.html('<tr><td colspan="6" class="cpNoDiscounts">'+myLabel.no_discounts_defined+'</td></tr>');
				}
			});	
			return false;
		}).on("change", ".cpSpace", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this),
				value = $(this).val(),
				index = $this.attr('data-index');
			$.get("index.php?controller=pjAdminPrices&action=pjActionGetDateRange", {
				"space_id": value,
				"index": index
			}).done(function (data) {
				$('#cpPrice_' + index).html(data);
			});	
			return false;
		}).on("change", ".cpType", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $sign = $('option:selected', this).attr('data-sign');
			$(this).closest('tr').find('.sign-discount-type').html($sign)
		}).on("click", "#btnShowDuplicatePrice", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $tr = $('#duplicatePricesModal').data('tr'),
				$next_tr = $('#duplicatePricesModal').data('next_tr'),
				seconds = 2000,
				tr_background = $tr.css('backgroundColor'),
				next_tr_background = $next_tr.css('backgroundColor');
			$tr.css('backgroundColor', '#FFB4B4');
			$next_tr.css('backgroundColor', '#FFB4B4');
			setTimeout(function(){
				$tr.css("backgroundColor", tr_background);
				$next_tr.css("backgroundColor", next_tr_background);
			}, seconds);
			$('#duplicatePricesModal').modal('hide');
			return false;
		}).on("click", "#btnShowDuplicateDiscount", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			
			var $tr = $('#duplicateDiscountsModal').data('tr'),
				$next_tr = $('#duplicateDiscountsModal').data('next_tr'),
				seconds = 2000,
				tr_background = $tr.css('backgroundColor'),
				next_tr_background = $next_tr.css('backgroundColor');
			$tr.css('backgroundColor', '#FFB4B4');
			$next_tr.css('backgroundColor', '#FFB4B4');
			setTimeout(function(){
				$tr.css("backgroundColor", tr_background);
				$next_tr.css("backgroundColor", next_tr_background);
			}, seconds);
			$('#duplicateDiscountsModal').modal('hide');
			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';
			    }
		    }
		});
		
		if ($datepick.length > 0) {
			myDatepickInit.call(null);
        }
	});
})(jQuery);