var jQuery_1_8_2 = $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateReservation = $("#frmCreateReservation"),
			$frmUpdateReservation = $("#frmUpdateReservation"),
			$frmExportReservations = $("#frmExportReservations"),
			$dialogMessage = $("#dialogMessage"),
			validate = ($.fn.validate !== undefined),
			datepicker = ($.fn.datepicker !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			dialog = ($.fn.dialog !== undefined),
			chosen = ($.fn.chosen !== undefined);

		if (validate) {
			$.validator.addMethod("validDates", function (value, element) {
				if($('#date_from').val() != '' && $('#date_to').val() != '' && $('#listing_id').val() != '')
				{
					return parseInt(value, 10) === 1;
				}else{
					return true;
				}
			}, myLabel.dateRangeValidation);
			
			$.validator.addMethod("numDays", function (value, element) {
				if($('#date_from').val() != '' && $('#date_to').val() != '' && $('#listing_id').val() != '')
				{
					return parseInt(value, 10) === 1;
				}else{
					return true;
				}
			}, myLabel.numDaysValidation);
		}
		if ($frmExportReservations.length > 0 && validate) {
			$frmExportReservations.validate({
				rules: {
					"password": {
						required: function(){
							if($('#feed').is(':checked'))
							{
								return true;
							}else{
								return false;
							}
						}
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ".ignore"
			});
		}
		if ($frmCreateReservation.length > 0 && validate) {
			$frmCreateReservation.validate({
				rules: {
					"dates": "validDates",
					"days": "numDays"
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ".ignore"
			});
		}
		if ($frmUpdateReservation.length > 0 && validate) {
			$frmUpdateReservation.validate({
				rules: {
					"dates": "validDates",
					"days": "numDays",
					"uuid": {
						remote: "index.php?controller=pjAdminReservations&action=pjActionCheckUuid&id=" + $frmUpdateReservation.find("input[name='id']").val()
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ".ignore",
				submitHandler: function(form)
				{
					$.post("index.php?controller=pjAdminReservations&action=pjActionUpdate", $frmUpdateReservation.serialize()).done(function (data) {
						if(data.code == '200')
						{
							if (dialog && $dialogMessage.length > 0) 
							{
								$dialogMessage.data('status', data.status).dialog('option', 'position', 'top');
								$dialogMessage.dialog("open");
							}
						}
					});
					
				}
			});
			
			if ($dialogMessage.length > 0 && dialog) {
				
				var buttons = {};
				buttons[myLabel.btn_continue] = function() {
					var $this = $(this);
					if ($this.find("#dialog_confirm").is(":checked")) {
						var $frmMessage = $('#frmSendMessage');
						$.post("index.php?controller=pjAdminReservations&action=pjActionSendMessage", $frmMessage.serialize()).done(function (data) {
							$dialogMessage.html("");
							if (tinymce.editors.length > 0) 
							{
						        tinymce.execCommand('mceRemoveEditor',true, "mceEditor");
						    }
							$this.dialog('close');
							window.location.href = 'index.php?controller=pjAdminReservations&action=pjActionIndex&err=AR01';
						});
					} else {
						if (tinymce.editors.length > 0) 
						{
					        tinymce.execCommand('mceRemoveEditor',true, "mceEditor");
					    }
						$this.dialog('close');
						window.location.href = 'index.php?controller=pjAdminReservations&action=pjActionIndex&err=AR01';
					}
				};
				buttons[myLabel.btn_cancel] = function() {
					$dialogMessage.html("");
					if (tinymce.editors.length > 0) 
					{
				        tinymce.execCommand('mceRemoveEditor',true, "mceEditor");
				    }
					$(this).dialog('close');
					window.location.href = 'index.php?controller=pjAdminReservations&action=pjActionIndex&err=AR01';
				};
				
				$dialogMessage.dialog({
					autoOpen: false,
					resizable: false,
					draggable: false,
					modal: true,
					width: 576,					
					buttons: buttons,
					close: function(event, ui){
						if (tinymce.editors.length > 0) 
						{
					        tinymce.execCommand('mceRemoveEditor',true, "mceEditor");
					    }
					},
					open: function( event, ui ) {
						var reservation_id = $frmUpdateReservation.find("input[name='id']").val();
						$dialogMessage.html("");
						$.get(["index.php?controller=pjAdminReservations&action=pjActionGetContent"].join(""), {id: reservation_id, status: $dialogMessage.data('status')}).done(function (data) {
							$dialogMessage.html(data);
							tinymce.init({
							    selector: "textarea#mceEditor",
							    plugins: [
							        "advlist autolink lists link image charmap print preview anchor",
							        "searchreplace visualblocks code fullscreen",
							        "insertdatetime media table contextmenu paste"
							    ],
							    width: 550,
							    height: 250,
							    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
							    setup: function (editor) {
							    	editor.on('change', function (e) {
							    		editor.editorManager.triggerSave();
							    	});
							    }
							});
							if (tinymce.editors.length > 0) 
							{							
								tinymce.execCommand('mceAddEditor',true, "mceEditor");
							}
						}).fail(function () {
							
						});
					},
				});
			}
		}
		function getPrices($form)
		{
			$.post("index.php?controller=pjAdminReservations&action=pjActionCalcPrices", $form.serialize()).done(function (data) {
				if (data.amount === undefined) {
					return;
				}
				$('#amount').val(data.amount);
				$('#deposit').val(data.deposit);
				$('#security').val(data.security);
				$('#tax').val(data.tax);
			});
		}
		function checkAvailability($form) {
			$.post("index.php?controller=pjAdminReservations&action=pjActionCheckAvailability", $form.serialize()).done(function (data) {
				if (data.code === undefined) {
					return;
				}
				switch (data.code) {
				case 200:
					$("input#dates").val('1').valid();
					break;
				case 100:
					$("input#dates").val('0').valid();
					break;
				}
				if($("input#days").val() == '1' && $("input#dates").val() == '1')
				{
					getPrices($form);
				}
			});
		}
		function checkDays($form) {
			$.post("index.php?controller=pjAdminReservations&action=pjActionCheckDays", $form.serialize()).done(function (data) {
				if (data.code === undefined) {
					return;
				}
				switch (data.code) {
				case 200:
					$("input#days").val('1').valid();
					break;
				case 100:
					$("input#days").val('0').valid();
					break;
				}
				checkAvailability($form);
			});
		}
		
		if ($frmCreateReservation.length > 0 || $frmUpdateReservation.length > 0) {
			var $date_from = $("#date_from");
			$date_from.datepicker({
				firstDay: $date_from.attr("rel"),
				dateFormat: $date_from.attr("rev"),
				dayNames: ($date_from.data("day")).split(","),
			    monthNames: ($date_from.data("months")).split(","),
			    monthNamesShort: ($date_from.data("shortmonths")).split(","),
			    dayNamesMin: ($date_from.data("daymin")).split(","),
				onSelect: function (dateText, inst) {
					$("#date_to").datepicker("option", "minDate", dateText);
					
					var $form = $(this).closest("form");
					checkDays($form);
				}
			});
			
			var $date_to = $("#date_to");
			$date_to.datepicker({
				firstDay: $date_to.attr("rel"),
				dateFormat: $date_to.attr("rev"),
				dayNames: ($date_to.data("day")).split(","),
			    monthNames: ($date_to.data("months")).split(","),
			    monthNamesShort: ($date_to.data("shortmonths")).split(","),
			    dayNamesMin: ($date_to.data("daymin")).split(","),
				onSelect: function (dateText, inst) {
					var $form = $(this).closest("form");
					checkDays($form);
				}
			});
			
			$("#listing_id").bind("change", function (e) {
				var $form = $(this).closest("form");
				checkDays($form);
				if($(this).val() != '')
				{
					var href = $('#pjPcEditListing').attr('data-href');
					href = href.replace("{ID}", $(this).val());
					$('#pjPcEditListing').attr('href', href).show();
				}else{
					$('#pjPcEditListing').hide();
				}
			});
		}
		
		if (chosen) {
			$("#listing_id").chosen();
		}
		
		var $PM = $("#payment_method");
		if ($PM.length > 0) {
			$PM.bind("change", function () {
				if ($("option:selected", this).val() == 'creditcard') {
					$(".vrCC").show();
				} else {
					$(".vrCC").hide();
				}
			});	
		}
		
		if ($("#grid").length > 0 && datagrid) {
			
			function formatListing (val, obj) {
				return ['<a href="index.php?controller=pjAdminListings&action=pjActionUpdate&id=', obj.listing_id,'">', $.datagrid.wordwrap(val, 40, '<br>', true), '</a>'].join("");
			}
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminReservations&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminReservations&action=pjActionDeleteReservation&id={:id}"}
				          ],
				columns: [{text: myLabel.uuid, type: "text", sortable: true, editable: false, width: 90},
				          {text: myLabel.date_from, type: "date", sortable: true, editable: true,
								jqDateFormat: pjGrid.jqDateFormat,
								width: 100,
								editableWidth: 80, 
								renderer: $.datagrid._formatDate, 
								editableRenderer: $.datagrid._formatDate,
								dateFormat: pjGrid.jsDateFormat},
				          {text: myLabel.date_to, type: "date", sortable: true, editable: true, 
								jqDateFormat: pjGrid.jqDateFormat,
								width: 100,
								editableWidth: 80,
								renderer: $.datagrid._formatDate, 
								editableRenderer: $.datagrid._formatDate,
								dateFormat: pjGrid.jsDateFormat},
				          {text: myLabel.listing, type: "text", sortable: true, editable: false, renderer: formatListing, width: 200},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 90, options: [
				                                                                                     {label: myLabel.pending, value: "Pending"}, 
				                                                                                     {label: myLabel.confirmed, value: "Confirmed"},
				                                                                                     {label: myLabel.cancelled, value: "Cancelled"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminReservations&action=pjActionGetReservation" + pjGrid.queryString,
				dataType: "json",
				fields: ['uuid', 'date_from', 'date_to', 'listing_refid', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.export_selected, url: "index.php?controller=pjAdminReservations&action=pjActionExportReservation", ajax: false},
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminReservations&action=pjActionDeleteReservationBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminReservations&action=pjActionSaveReservation&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
			
			$(document).on("click", ".btn-all", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				$(this).addClass("pj-button-hover").siblings(".pj-button").removeClass("pj-button-hover");
				var content = $grid.datagrid("option", "content"),
					cache = $grid.datagrid("option", "cache");
				$.extend(cache, {
					status: ""
				});
				$grid.datagrid("option", "cache", cache);
				$grid.datagrid("load", "index.php?controller=pjAdminReservations&action=pjActionGetReservation", "id", "DESC", content.page, content.rowCount);
				return false;
			}).on("click", ".btn-confirmed", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				$(this).addClass("pj-button-hover").siblings(".pj-button").removeClass("pj-button-hover");
				var content = $grid.datagrid("option", "content"),
					cache = $grid.datagrid("option", "cache");
				$.extend(cache, {
					status: "Confirmed"
				});
				$grid.datagrid("option", "cache", cache);
				$grid.datagrid("load", "index.php?controller=pjAdminReservations&action=pjActionGetReservation", "id", "DESC", content.page, content.rowCount);
				return false;
			}).on("click", ".btn-pending", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				$(this).addClass("pj-button-hover").siblings(".pj-button").removeClass("pj-button-hover");
				var content = $grid.datagrid("option", "content"),
					cache = $grid.datagrid("option", "cache");
				$.extend(cache, {
					status: "Pending"
				});
				$grid.datagrid("option", "cache", cache);
				$grid.datagrid("load", "index.php?controller=pjAdminReservations&action=pjActionGetReservation", "id", "DESC", content.page, content.rowCount);
				return false;
			}).on("click", ".btn-cancelled", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				$(this).addClass("pj-button-hover").siblings(".pj-button").removeClass("pj-button-hover");
				var content = $grid.datagrid("option", "content"),
					cache = $grid.datagrid("option", "cache");
				$.extend(cache, {
					status: "Cancelled"
				});
				$grid.datagrid("option", "cache", cache);
				$grid.datagrid("load", "index.php?controller=pjAdminReservations&action=pjActionGetReservation", "id", "DESC", 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(),
					listing_id: $this.find("option:selected", "select[name='listing_id']").val()
				});
				$grid.datagrid("option", "cache", cache);
				$grid.datagrid("load", "index.php?controller=pjAdminReservations&action=pjActionGetReservation", "id", "ASC", content.page, content.rowCount);
				return false;
			}).on("change", "select[name='listing_id']", function (e) {
				var $this = $(this),
					content = $grid.datagrid("option", "content"),
					cache = $grid.datagrid("option", "cache");
				$.extend(cache, {
					listing_id: $this.val()
				});
				$grid.datagrid("option", "cache", cache);
				$grid.datagrid("load", "index.php?controller=pjAdminReservations&action=pjActionGetReservation", "id", "ASC", content.page, content.rowCount);
				return false;
			});
			
		}
		
		if ($("#export_grid").length > 0 && datagrid) 
		{
			var $grid = $("#export_grid").datagrid({
				buttons: [{type: "view", url: "index.php?controller=pjAdminReservations&action=pjActionExportFeed{:params}", 'target' : "_blank"},
				          {type: "delete", url: "index.php?controller=pjAdminReservations&action=pjActionDeletePassword&id={:id}"}
				          ],
				columns: [{text: myLabel.format, type: "text", sortable: false, editable: false},
				          {text: myLabel.reservations, type: "text", sortable: false, editable: false},
				          {text: myLabel.period, type: "text", sortable: false, editable: false}
				          ],
				dataUrl: "index.php?controller=pjAdminReservations&action=pjActionGetPassword",
				dataType: "json",
				fields: ['format', 'type', 'period'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminReservations&action=pjActionDeletePasswordBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminReservations&action=pjActionSavePassword&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		$(document).on("click", ".pj-form-field-icon-date", function (e) {
			$(this).parent().siblings("input[type='text']").datepicker("show");
		}).on("click change", "#dialog_confirm", function (e) {
			if ($(this).is(":checked")) {
				$dialogMessage.find("textarea").prop("readonly", false).removeClass("pj-form-field-readonly")
					.end().find("input[type='text']").prop("readonly", false).removeClass("pj-form-field-readonly");
			} else {
				$dialogMessage.find("textarea").prop("readonly", true).addClass("pj-form-field-readonly")
					.end().find("input[type='text']").prop("readonly", true).addClass("pj-form-field-readonly");
			}
		}).on("change", "#export_period", function (e) {
			var period = $(this).val();
			if(period == 'last')
			{
				$('#last_label').show();
				$('#next_label').hide();
			}else{
				$('#last_label').hide();
				$('#next_label').show();
			}
		}).on("click", "#file", function (e) {
			$('#tsSubmitButton').val(myLabel.btn_export);
			$('.tsFeedContainer').hide();
			$('.tsPassowrdContainer').hide();
		}).on("click", "#feed", function (e) {
			$('.tsPassowrdContainer').show();
			$('#tsSubmitButton').val(myLabel.btn_get_url);
		}).on("focus", "#reservations_feed", function (e) {
			$(this).select();
		});
	});
})(jQuery_1_8_2);