var jQuery = jQuery || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmCreate = $("#frmCreate"),
			$frmUpdate = $("#frmUpdate"),
			validate = ($.fn.validate !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			multilang = ($.fn.multilang !== 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 (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 ($('#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-idx');
        		var element_id = $(this).attr('id');        		
        		if (element_id.indexOf("date_from_") !== '-1') {
	        		var $toElement = $("#date_to_" + idx);
        			if($toElement.length > 0)
        			{
        				var date_to_value = $toElement.datepicker("getUTCDate");
        				if(date_to_value < selected.date)
    					{
        					$toElement.val($(this).val());
    					}
        			}
        		}

        		if (element_id.indexOf("date_to_") !== '-1') {
        			var $fromElement = $("#date_from_" + idx);
        			var $toElement = $("#date_to_" + idx);
        			if($fromElement.length > 0 && $toElement.length > 0)
        			{
        				var date_from_value = $fromElement.datepicker("getUTCDate");
        				if(date_from_value > selected.date)
    					{
        					$fromElement.val($toElement.val());
    					}
        			}
        		}
            });
        }
        
		if ($frmCreate.length > 0 && validate) {
			$frmCreate.validate({
				onkeyup: false,
				ignore: "",
				submitHandler: function(form){
					$.ajax({
	        	        type: "POST",
	        	        url: "index.php?controller=pjAdminSpaces&action=pjActionCheckPeriods",
	        	        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{
	        	        		var $tr = $('tr[data-idx="'+data.index+'"]');
	        	        		var $next_tr = $('tr[data-idx="'+data.idx+'"]');
	        	        		var tr_background = $tr.css('backgroundColor');
	        					var 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);
	        					}, 2000);
	        	        		swal({
	    			    			title: "",
	    							text: data.text,
	    							type: "warning",
	    							confirmButtonColor: "#DD6B55",
	    							confirmButtonText: "OK",
	    							closeOnConfirm: false,
	    							showLoaderOnConfirm: false
	    						}, function () {
	    							swal.close();
	    						});
	        	        	}
	        	        }
	        	    });
					return false;
				}
			});
		}
		
		if ($frmUpdate.length > 0 && validate) {
			$frmUpdate.validate({
				onkeyup: false,
				ignore: "",
				submitHandler: function(form){
					$.ajax({
	        	        type: "POST",
	        	        url: "index.php?controller=pjAdminSpaces&action=pjActionCheckPeriods",
	        	        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{
	        	        		var $tr = $('tr[data-idx="'+data.index+'"]');
	        	        		var $next_tr = $('tr[data-idx="'+data.idx+'"]');
	        	        		var tr_background = $tr.css('backgroundColor');
	        					var 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);
	        					}, 2000);
	        	        		swal({
	    			    			title: "",
	    							text: data.text,
	    							type: "warning",
	    							confirmButtonColor: "#DD6B55",
	    							confirmButtonText: "OK",
	    							closeOnConfirm: false,
	    							showLoaderOnConfirm: false
	    						}, function () {
	    							swal.close();
	    						});
	        	        	}
	        	        }
	        	    });
					return false;
				}
			});
		}
		function formatPrice (str, obj) {
			if(str == '')
			{
				return '<a href="index.php?controller=pjAdminPrices&action=pjActionIndex">'+myLabel.set_price+'</a>';
			}else{
				return str;
			}
		}
		if ($("#grid").length > 0 && datagrid) {
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminSpaces&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminSpaces&action=pjActionDelete&id={:id}"}
				          ],
				columns: [{text: myLabel.name, type: "text", sortable: true, editable: pjGrid.hasAccessUpdate},
				          {text: myLabel.occupied_now, type: "text", sortable: true, editable: false},
				          {text: myLabel.available_now, type: "text", sortable: true, editable: false},
				          {text: myLabel.price_today, type: "text", sortable: true, editable: false, renderer: formatPrice},
				          {text: myLabel.status, type: "toggle", sortable: true, editable: pjGrid.hasAccessUpdate, positiveLabel: myLabel.active, positiveValue: "T", negativeLabel: myLabel.inactive, negativeValue: "F"}],
				dataUrl: "index.php?controller=pjAdminSpaces&action=pjActionGetSpace",
				dataSpace: "json",
				fields: ['name', 'booked', 'avail', 'price', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminSpaces&action=pjActionDeleteBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminSpaces&action=pjActionSaveSpace&id={:id}",
				select: {
					field: "id",
					name: "record[]",
					cellClass: 'cell-width-2'
				}
			});
		}
		
		$(document).on("click", ".btn-all", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).addClass("btn-primary active").removeClass("btn-default")
			.siblings(".btn").removeClass("btn-primary active").addClass("btn-default");
			var content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache");
			$.extend(cache, {
				status: "",
				q: ""
			});
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminSpaces&action=pjActionGetSpace", "name", "ASC", content.page, content.rowCount);
			return false;
		}).on("click", ".btn-filter", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $this = $(this),
				content = $grid.datagrid("option", "content"),
				cache = $grid.datagrid("option", "cache"),
				obj = {};
			$this.addClass("btn-primary active").removeClass("btn-default")
			.siblings(".btn").removeClass("btn-primary active").addClass("btn-default");
			obj.status = "";
			obj[$this.data("column")] = $this.data("value");
			$.extend(cache, obj);
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminSpaces&action=pjActionGetSpace", "name", "ASC", content.page, content.rowCount);
			return false;
		}).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=pjAdminSpaces&action=pjActionGetSpace", "name", "ASC", content.page, content.rowCount);
			return false;
		}).on("click", ".cpAddDate", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $tbody = $("#tblSpaces tbody"),
				index = Math.ceil(Math.random() * 999999);
			
			var clone_text = $("#tblSpacesClone").find("tbody").html();
			clone_text = clone_text.replace(/\{INDEX\}/g, 'cp_' + index);
			$tbody.append(clone_text);
			if($("#spaces_cp_" + index).length > 0)
			{
				$("#spaces_cp_" + index).TouchSpin({
					verticalbuttons: true,
		            buttondown_class: 'btn btn-white',
		            buttonup_class: 'btn btn-white',
		            max: 4294967295
		        });
			}
			$datepick = $('.datepick');
			if ($datepick.length > 0) {
				myDatepickInit.call(null);
	        }
			return false;
		}).on("click", ".cpRemoveDate", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var $tr = $(this).closest("tr");
			$tr.css("backgroundColor", "#FFB4B4").fadeOut("slow", function () {
				$tr.remove();
			});	
			return false;
		});
		
		function myTinyMceDestroy() {
			
			if (window.tinymce === undefined) {
				return;
			}
			
			var iCnt = tinymce.editors.length;
			
			if (!iCnt) {
				return;
			}
			
			for (var i = 0; i < iCnt; i++) {
				tinymce.remove(tinymce.editors[i]);
			}
		}

		function myTinyMceInit(pSelector) {
			
			if (window.tinymce === undefined) {
				return;
			}
			
			tinymce.init({
				relative_urls : false,
				remove_script_host : false,
				convert_urls : true,
			    selector: pSelector,
			    theme: "silver",
			    height: 400,
			    plugins: [
			        'link image imagetools table'
			      ],
			    contextmenu: "link image imagetools table",
			    setup: function (editor) {
			    	editor.on('change', function (e) {
			    		editor.editorManager.triggerSave();
			    	});
			    }
			});
		}
		if ($datepick.length > 0) {
			myDatepickInit.call(null);
        }
		if ($('.mceEditor').length > 0) {
			myTinyMceDestroy.call(null);
			myTinyMceInit.call(null, 'textarea.mceEditor');
        }
	});
})(jQuery);