var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var validator,
			$frmCreateFloorplan = $("#frmCreateFloorplan"),
			$frmUpdateFloorplan = $("#frmUpdateFloorplan"),
			$dialogDelete = $("#dialogDelete"),
			$dialogUpdate = $("#dialogUpdateSection"),
			$dialogResizeImage = $("#dialogResizeImage"),
			$fmRect = null,
			gallery = ($.fn.gallery !== undefined),
			dialog = ($.fn.dialog !== undefined),
			tabs = ($.fn.tabs !== undefined),
			validate = ($.fn.validate !== undefined),
			datagrid = ($.fn.datagrid !== undefined),
			$gallery = $("#gallery"),
			$tabs = $("#tabs"),
			tOpt = {
				select: function (event, ui) {
					$(":input[name='tab_id']").val(ui.panel.id);
				}
			};

		if ($tabs.length > 0 && tabs) {
			$tabs.tabs(tOpt);
		}
		$(".field-int").spinner({
			min: 0
		});
		
		if ($frmCreateFloorplan.length > 0 && validate) {
			$frmCreateFloorplan.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		}
		
		if ($frmUpdateFloorplan.length > 0)
		{
			var offset = $("#floorplan").offset(),
				dragOpts = {
					containment: "parent",
					stop: function (event, ui) {
						var id = $(event.target).attr('data-id');
						$.get( "index.php?controller=pjAdminFloorplans&action=pjActionUpdatePos", { id: id, top: ui.position.top, left: ui.position.left}, function( data ) {
							
						});
					}
				};
		}
		function updateSection()
		{
			$frmUpdateFloorplan.find('.fmRect').each(function(e){
				var $this = $(this),
					deg = parseInt($(this).attr('data-deg'), 10);
				var rad = deg * Math.PI / 180;
				$this.resizable({
					aspectRatio: true,
					handles: 'se',
					resize: function(e, ui) {
						var height = $(this).height(),
							width = $(this).width();
			        },
					stop: function(event, ui) {
						var id = $(event.target).attr('data-id'),
							$parent = $this.parent(),
							height = $(this).height(),
							width = $(this).width();
						$parent.css({
							height: height+'px',
							width: width+'px'
						}).draggable(dragOpts);
						
						$.get( "index.php?controller=pjAdminFloorplans&action=pjActionUpdateSize", { id: id, height: height, width: width}, function( data ) {
						
						});
			        }
				});
				$this.rotatable({
					angle: rad,
					stop: function(event, ui){
						var id = $(event.target).attr('data-id');
						
						var transform = $(event.target).css('transform');
						var values = transform.split('(')[1];
						    values = values.split(')')[0];
						    values = values.split(',');
						var a = values[0];
						var b = values[1];
						var c = values[2];
						var d = values[3];
						var scale = Math.sqrt(a*a + b*b);
						var sin = b/scale;
						var deg = Math.round(Math.atan2(b, a) * (180/Math.PI));
						$.get( "index.php?controller=pjAdminFloorplans&action=pjActionUpdateTransform", { id: id, deg: deg}, function( data ) {
							
						});
					}
				});
				$this.parent().draggable(dragOpts);
			});
			$frmUpdateFloorplan.find('.fmInfoIcon').each(function(e){
				var $this = $(this);
				$this.draggable(dragOpts);
			});
		}
		if ($frmUpdateFloorplan.length > 0 && validate) {
			$frmUpdateFloorplan.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
			
			updateSection();

			$("#floorplanHolder").mousedown(function (e) {
				var px = $('.fmFloorplanHolder').scrollLeft();
				var type = $('input[name=type]:checked', $frmUpdateFloorplan).val();
				var offsetTop = 16,
					offsetLeft = 16;
				if(type == 'image')
				{
					offsetTop = 100;
					offsetLeft = 100;
				}
				var $this = $(this),
					t = Math.ceil(e.pageY - offset.top - offsetTop),
					l = Math.ceil(e.pageX - offset.left - offsetLeft + px);
				
				var style = {
						"top": t + "px",
						"left": l + "px",
						'width': '200px',
						'height': '200px',
						"position": "absolute"
					};
				if(type == 'info')
				{
					style = {
						"top": t + "px",
						"left": l + "px",
						"position": "absolute"
					};
				}
				var can = true;
				$("#floorplanHolder").find(".fmIcons").each(function (i) {
					var id = $(this).attr('data-id');
					if (e.target.id == "fmRect_" + id || $(e.target).parents("#fmRect_" + id).size()) { 
						can = false;
			        } 
				});
				if (can == true) 
				{
					$.get( "index.php?controller=pjAdminFloorplans&action=pjActionAddSection", { id: $this.attr('data-id'), top: t, left: l, type: type }, function( data ) {
						if(data.code == '200')
						{
							if(type == 'image')
							{
								$fmRect = $("<div>", {
									css: style,
									attr:{
										"data-id": data.id,
										"data-type": type
									},
									html: '<span id="fmRect_'+data.id+'" data-id="'+data.id+'" data-deg="0" data-type="image" class="fmRect fmCameraIcon fmIcons" style="width: 200px; height: 200px; transform: rotate(0rad);"><span class="fmClose" data-id="'+data.id+'">X</span></span>',
								}).addClass("fmDraggable").draggable(dragOpts);
							}else{
								$fmRect = $("<span>", {
									css: style,
									attr:{
										"id": "fmRect_" + data.id,
										"data-id": data.id,
										"data-type": type
									}
								}).addClass('fmInfoIcon fmIcons').draggable(dragOpts);
							}
							$this.append($fmRect);
							updateSection();
							$dialogUpdate.data('id', data.id).dialog('open');
						}
					});
				}
			});
		}
		
		if ($dialogUpdate.length > 0 && dialog) {
			$dialogUpdate.dialog({
				modal: true,
				resizable: false,
				draggable: false,
				autoOpen: false,
				width: 600,
				open: function(){
					$dialogUpdate.html("");
					$.get( "index.php?controller=pjAdminFloorplans&action=pjActionGetSection", { id: $dialogUpdate.data('id') }, function( data ) {
						$dialogUpdate.html(data);
						validator = $dialogUpdate.find("form").validate({
							errorPlacement: function (error, element) {
								error.insertAfter(element.parent());
							},
							onkeyup: false,
							errorClass: "err",
							wrapper: "em",
							ignore: ""
						});
					});
				},
				buttons: (function () {
					var buttons = {};
					buttons[fmApp.locale.button.save] = function () {
						if (validator.form()) {
							$.post( "index.php?controller=pjAdminFloorplans&action=pjActionUpdateSection", $dialogUpdate.find("form").serialize(), function( resp ) {
								if(resp.code == '200')
								{
									var $rect = $('#fmRect_' + $dialogUpdate.data('id')),
										data = resp.data;
									if($fmRect != null)
									{
										if($fmRect.attr('data-id') == $dialogUpdate.data('id'))
										{
											$rect = $fmRect;
										}
									}
									if(resp.type == 'image')
									{
										var rad = parseInt(data.deg) * Math.PI / 180;
										$rect.css({
											'transform': 'rotate('+rad+'rad)',
											'width': data.width + 'px',
											'height': data.height + 'px'
										});
										$rect.attr('data-deg', data.deg);
										updateSection();
									}
									$dialogUpdate.dialog("close");
								}
							});
						}
					};
					buttons[fmApp.locale.button.delete] = function () {
						$.get( "index.php?controller=pjAdminFloorplans&action=pjActionDeleteSection", { id: $dialogUpdate.data('id') }, function( data ) {
							var $rect = $('#fmRect_' + $dialogUpdate.data('id'));
							if($rect.attr('data-type') == 'image')
							{
								$rect = $rect.parent();
							}
							if($fmRect != null)
							{
								if($fmRect.attr('data-id') == $dialogUpdate.data('id'))
								{
									$rect = $fmRect;
								}
							}
							$rect.remove();
							$dialogUpdate.dialog("close");
						});
					};
					buttons[fmApp.locale.button.cancel] = function () {
						$dialogUpdate.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
		$( ".fmIcons" )
		  	.mouseover(function() {
		  		if($( this ).hasClass('fmInfoIcon'))
		  		{
		  			$( ".fmIcons" ).css('z-index', '1000');
			  		$( this ).css('z-index', '1001');
		  		}else{
		  			$( ".fmIcons" ).parent().css('z-index', '1000');
			  		$( this ).parent().css('z-index', '1001');
		  		}
		  	})
		  	.mouseout(function() {
		  		if($( this ).hasClass('fmInfoIcon'))
		  		{
		  			$( ".fmIcons" ).css('z-index', '1000');
		  		}else{
		  			$( ".fmIcons" ).parent().css('z-index', '1000');
		  		}
		});		
		if ($gallery.length > 0 && gallery) {
			$gallery.gallery({
				compressUrl: "index.php?controller=pjGallery&action=pjActionCompressGallery&foreign_id=" + myGallery.foreign_id,
				getUrl: "index.php?controller=pjGallery&action=pjActionGetGallery&foreign_id=" + myGallery.foreign_id,
				deleteUrl: "index.php?controller=pjGallery&action=pjActionDeleteGallery",
				emptyUrl: "index.php?controller=pjGallery&action=pjActionEmptyGallery&foreign_id=" + myGallery.foreign_id,
				rebuildUrl: "index.php?controller=pjGallery&action=pjActionRebuildGallery&foreign_id=" + myGallery.foreign_id,
				resizeUrl: "index.php?controller=pjGallery&action=pjActionResizeGallery&id={:id}&foreign_id=" + myGallery.foreign_id + "&hash=" + myGallery.hash + ($frmUpdateFloorplan.length > 0 ? "&query_string=" + encodeURIComponent("controller=pjAdminFloorplans&action=pjActionUpdate&id=" + myGallery.foreign_id + "&tab_id=tabs-2") : ""),
				rotateUrl: "index.php?controller=pjGallery&action=pjActionRotateGallery",
				sortUrl: "index.php?controller=pjGallery&action=pjActionSortGallery",
				updateUrl: "index.php?controller=pjGallery&action=pjActionUpdateGallery",
				uploadUrl: "index.php?controller=pjGallery&action=pjActionUploadGallery&foreign_id=" + myGallery.foreign_id,
				watermarkUrl: "index.php?controller=pjGallery&action=pjActionWatermarkGallery&foreign_id=" + myGallery.foreign_id
			});
		}
		if ($("#grid").length > 0 && datagrid) {
			function formatImages (str, obj) 
			{
				if(str == '0')
				{
					return str;
				}else{
					return '<a href="index.php?controller=pjAdminFloorplans&action=pjActionUpdate&id='+obj.id+'&tab_id=tab-2">'+str+'</a>';
				}
			}
			var $grid = $("#grid").datagrid({
				buttons: [{type: "view", url: "preview.php?floorplan_id={:id}", target: '_blank'},
				          {type: "install", url: "index.php?controller=pjAdminOptions&action=pjActionInstall&id={:id}"},
				          {type: "edit", url: "index.php?controller=pjAdminFloorplans&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminFloorplans&action=pjActionDeleteFloorplan&id={:id}"}
				          ],
				columns: [{text: myLabel.title, type: "text", sortable: true, editable: true, width: 360, editableWidth: 340},
				          {text: myLabel.images, type: "text", sortable: true, editable: false, width: 90, align: 'center', renderer: formatImages},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 110, options: [
				                                                                                     {label: myLabel.active, value: "T"}, 
				                                                                                     {label: myLabel.inactive, value: "F"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminFloorplans&action=pjActionGetFloorplan",
				dataType: "json",
				fields: ['title', 'cnt_images', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminFloorplans&action=pjActionDeleteFloorplanBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminFloorplans&action=pjActionExportFloorplan", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminFloorplans&action=pjActionSaveFloorplan&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
		}
		
		$(document).on("click", ".btn-all", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$(this).addClass("pj-button-active").siblings(".pj-button").removeClass("pj-button-active");
			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=pjAdminFloorplans&action=pjActionGetFloorplan", "title", "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("pj-button-active").siblings(".pj-button").removeClass("pj-button-active");
			obj.status = "";
			obj[$this.data("column")] = $this.data("value");
			$.extend(cache, obj);
			$grid.datagrid("option", "cache", cache);
			$grid.datagrid("load", "index.php?controller=pjAdminFloorplans&action=pjActionGetFloorplan", "title", "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=pjAdminFloorplans&action=pjActionGetFloorplan", "title", "ASC", content.page, content.rowCount);
			return false;
		}).on("click", ".fmRect", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var title = $dialogUpdate.attr('data-title1');
			$dialogUpdate.dialog('option', 'title', title);
			$dialogUpdate.data('id', $(this).attr('data-id')).dialog('open');
			return false;
		}).on("click", ".fmInfoIcon", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var title = $dialogUpdate.attr('data-title2');
			$dialogUpdate.dialog('option', 'title', title);
			$dialogUpdate.data('id', $(this).attr('data-id')).dialog('open');
			return false;
		}).on("click", ".fmImageItem", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$('#frmUpdateSection').find("input[name='image_id']").val($(this).attr('data-id'));
			$('.fmImageOuter').removeClass('active');
			$(this).parent().addClass('active');
			return false;
		}).on("click", ".pj-delete-floorplan", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogDelete.data('id', $(this).attr('data-id')).dialog('open');
			return false;
		}).on("click", ".pj-resize-floorplan", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogResizeImage.data('id', $(this).attr('data-id')).dialog('open');
			return false;
		}).on("keyup", "#new_width", function (e) {
			var width = $(this).val(),
				originalWidth = parseInt($(this).attr('data-width')),
				originalHeight = parseInt($(this).attr('data-height'));
			if(!isNaN(width))
			{
				var ratio = originalHeight/originalWidth;
				var height = parseInt(width * ratio);
				$('#new_height').val(height);
			}
			return false;
		}).on("click", ".pjFmRestoreImage", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var id = $(this).attr('data-id');
			$.ajax({
				type: "GET",
				url: "index.php?controller=pjAdminFloorplans&action=pjActionRestoreImage&id=" + id,
				success: function (data) {
					if(data.code = '200')
					{
						$dialogResizeImage.dialog('close');
						window.location.href="index.php?controller=pjAdminFloorplans&action=pjActionUpdate&id=" + id + "&restore=1";
					}
				}
			});
			return false;
		}).on("click", ".fmClose", function (e) {
			e.stopPropagation();
			var $this = $(this);
			var id = $this.attr('data-id');
			$.get( "index.php?controller=pjAdminFloorplans&action=pjActionDeleteSection", { id: id }, function( data ) {
				$this.parent().parent().remove();
			});
		});
		
		if ($dialogResizeImage.length > 0) {
			$dialogResizeImage.dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				width: 400,
				buttons: (function () {
					var buttons = {};
					buttons[fmApp.locale.button.resize] = function () {
						var $frm = $dialogResizeImage.find("form");
						$.ajax({
							type: "POST",
							data: $frm.serialize(),
							url: "index.php?controller=pjAdminFloorplans&action=pjActionResizeImage",
							success: function (data) {
								if(data.code = '200')
								{
									$dialogResizeImage.dialog('close');
									window.location.href="index.php?controller=pjAdminFloorplans&action=pjActionUpdate&id=" + $dialogResizeImage.data('id');
								}
							}
						});
					};
					buttons[fmApp.locale.button.cancel] = function () {
						$dialogResizeImage.dialog('close');
					};
					
					return buttons;
				})()
			});
		}
		
		if ($dialogDelete.length > 0) {
			$dialogDelete.dialog({
				autoOpen: false,
				resizable: false,
				draggable: false,
				modal: true,
				buttons: (function () {
					var buttons = {};
					buttons[fmApp.locale.button.delete] = function () {
						$.ajax({
							type: "POST",
							data: {
								id: $dialogDelete.data('id')
							},
							url: "index.php?controller=pjAdminFloorplans&action=pjActionDeleteImage",
							success: function (data) {
								if(data.code = '200')
								{
									window.location.href="index.php?controller=pjAdminFloorplans&action=pjActionUpdate&id=" + $dialogDelete.data('id');
								}
							}
						});
						$dialogDelete.dialog('close');
					};
					buttons[fmApp.locale.button.cancel] = function () {
						$dialogDelete.dialog('close');
					};
					
					return buttons;
				})()
			});
		}
	});
})(jQuery_1_8_2);