(function()
{
 	var app 			= angular.module('app');
 	var nvFinderPath 	= window.location.protocol + "//" + window.location.hostname + "/finder";

 	app.controller('ModuleController', ["$scope", "$http", "$compile", function($scope, $http, $compile)
	{
		$scope.params          = {};
		$scope.loading         = false;
		$scope.tags            = TAGS;
		$scope.icons           = [];
		$scope.page_tags       = [];
		$scope.documents       = [];
		$scope.categories      = [];
		$scope.image_dirs      = [];
		$scope.content_types   = [];
		$scope.pages           = [];
		$scope.menus           = [];
		$scope.video_files     = [];

		$http.get('/ajax/get_pages_array').
		then(function(response)
		{
			$scope.pages = response.data;
		},
		function(response)
		{

		});

		$http.get('/ajax/get_menus_array').
		then(function(response)
		{
			$scope.menus = response.data;
		},
		function(response)
		{

		});

		$http.get('/ajax/get_icons').
		then(function(response)
		{
			$scope.icons = response.data;
		},
		function(response)
		{

		});

		$http.get('/ajax/get_content_types_array').
		then(function(response)
		{
			$scope.content_types = response.data;
		},
		function(response)
		{

		});

		$http.get('/ajax/get_categories_array').
		then(function(response)
		{
			$scope.categories = response.data;
		},
		function(response)
		{

		});

		$http.get('/ajax/get_documents_array').
		then(function(response)
		{
			$scope.documents = response.data;
		},
		function(response)
		{

		});

		$http.get('/ajax/get_tokens/page_tag').
		then(function(response)
		{
			$scope.page_tags = response.data;
		},
		function(response)
		{

		});

		$http.get('/ajax/get_image_dirs_array').
		then(function(response)
		{
			$scope.image_dirs = response.data;
		},
		function(response)
		{

		});

		$http.get('/ajax/get_video_files_array').
		then(function(response)
		{
			$scope.video_files = response.data;
		},
		function(response)
		{

		});

		$scope.setModulePagesDisplay = function()
		{
			setModulePagesDisplay();
		}

		$scope.load_settings = function(id, file_name, e)
		{
			$http.get('/ajax/get_module_settings/' + id).
			then(function(response)
			{
				var d = new RegExp(/[0-9]{4}-[0-9]{2}-[0-9]{2}/);
				var dt = new RegExp(/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/);
				var t = new RegExp(/[0-9]{2}:[0-9]{2}(:[0-9]{2})?/);

				for(var f in response.data)
				{
					if(dt.test(response.data[f].value))
					{
						response.data[f].value = new Date(response.data[f].value);
					}
					else if(d.test(response.data[f].value))
					{
						response.data[f].value = new Date(response.data[f].value + "T09:00:00");
					}
					else if(t.test(response.data[f].value))
					{
						response.data[f].value = new Date("2021-01-01T" + response.data[f].value);
					}
				}

				$scope.params = response.data;

				$http.get('/modulesettings/' + file_name).
				then(function(response)
				{
					$scope.formdata = $compile(response.data)($scope);
					jQuery("#module-settings").html($scope.formdata);

					$scope.load_datasources();

					// Load default values
					if(id == 0)
					{
						if(typeof $scope.params == "undefined")
						{
							$scope.params = [];
						}

						jQuery('[id^="param_"]').each(function()
						{
							try
							{
								var type = jQuery(this).attr("type");
								$scope.params[jQuery(this).attr("id").replace("param_", "")] = {value: (type == "number" || type == "checkbox" ? Number(jQuery(this).attr("data-default")) : jQuery(this).attr("data-default"))};
							}
							catch(e){}
						});
					}

					jQuery('.wickedpick').each(function()
					{
						if(typeof $scope.params[jQuery(this).attr("id").replace("param_", "")] == "undefined")
						{
							val = jQuery(this).attr("data-default")
						}
						else
						{
							val = $scope.params[jQuery(this).attr("id").replace("param_", "")].value;
							val = (val ? val : jQuery(this).attr("data-default"));
							val = val.replace(" AM", "");

							if(val.indexOf(" PM") !== -1)
							{
								val = val.replace(" PM", "");
								parts = val.split(":");
								val = (Number(parts[0])+12) + ":" + parts[1];
							}
						}

						jQuery(this).wickedpicker({
							twentyFour: false,
							title: 'Select Time',
							showSeconds: false,
							now: val
						});
					});

					initializeTokenInputs();

					if(document.getElementById("param_tag_ids"))
					{
						obj = jQuery("#param_tag_ids");
						obj.tokenInput("clear");

						if(typeof $scope.params["tag_ids"].value != "undefined")
						{
							var tag_ids = String($scope.params["tag_ids"].value).split(",");
							var tag_name = "";

							for(var i=0; i<tag_ids.length; i++)
							{
								tag_name = "";

								for(var j=0; j<$scope.tags.length; j++)
								{
									if($scope.tags[j].tag_id == tag_ids[i])
									{
										tag_name = $scope.tags[j].tag;
										break;
									}
								}

								if(tag_name != "")
								{
									obj.tokenInput("add", {id: tag_ids[i], name: tag_name});
								}
							}
						}
					}
				},
				function(response)
				{
					error("Error Loading Module Settings", response.data, true, null);
				});
			},
			function(response)
			{
				error("Error Loading Module Settings", response.data, true, null);
			});
		}

		$scope.load_page_settings = function(id, e)
		{
			$http.get('/ajax/get_page_settings/' + id).
			then(function(response)
			{
				var d = new RegExp(/[0-9]{4}-[0-9]{2}-[0-9]{2}/);
				var dt = new RegExp(/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/);
				var t = new RegExp(/[0-9]{2}:[0-9]{2}(:[0-9]{2})?/);

				for(var f in response.data)
				{
					if(dt.test(response.data[f].value))
					{
						response.data[f].value = new Date(response.data[f].value);
					}
					else if(d.test(response.data[f].value))
					{
						response.data[f].value = new Date(response.data[f].value + "T09:00:00");
					}
					else if(t.test(response.data[f].value))
					{
						response.data[f].value = new Date("2021-01-01T" + response.data[f].value);
					}
				}

				$scope.params = response.data;
				$scope.load_datasources();

				// Load default values
				if(id == 0)
				{
					if(typeof $scope.params == "undefined")
					{
						$scope.params = [];
					}

					jQuery('[id^="field_"]').each(function()
					{
						try
						{
							var type = jQuery(this).attr("type");
							$scope.params[jQuery(this).attr("id").replace("field_", "")] = {value: (type == "number" || type == "checkbox" ? Number(jQuery(this).attr("data-default")) : jQuery(this).attr("data-default"))};
						}
						catch(e){}
					});
				}

				if(document.getElementById("field_tag_ids"))
				{
					obj = jQuery("#field_tag_ids");
					obj.tokenInput("clear");

					if(typeof $scope.params["tag_ids"].value != "undefined")
					{
						var tag_ids = String($scope.params["tag_ids"].value).split(",");
						var tag_name = "";

						for(var i=0; i<tag_ids.length; i++)
						{
							tag_name = "";

							for(var j=0; j<$scope.tags.length; j++)
							{
								if($scope.tags[j].tag_id == tag_ids[i])
								{
									tag_name = $scope.tags[j].tag;
									break;
								}
							}

							if(tag_name != "")
							{
								obj.tokenInput("add", {id: tag_ids[i], name: tag_name});
							}
						}
					}
				}
			},
			function(response)
			{
				error("Error Loading Page Settings", response.data, true, null);
			});
		}

		$scope.load_datasources = function(event)
		{
			setTimeout(function()
			{
				$scope._load_datasources(event);
			}, 100);
		}

		$scope._load_datasources = function()
		{
			// Load any select lists with a data-source
			jQuery('select[data-source]').each(function()
			{
				var select_dom 	= document.getElementById(jQuery(this).attr("id"));
				var select_jq 	= jQuery(this);

				$http.get(select_jq.attr("data-source")).
				then(function(response)
				{
					for(var i=0; i<response.data.length; i++)
					{
						var option   = document.createElement("option");
						option.text  = String(response.data[i].text);
						option.text  = option.text.replace(/^fa-/, "");
						option.text  = option.text.replace(/ far$/, " (regular)");
						option.text  = option.text.replace(/ fal$/, " (light)");
						option.text  = option.text.replace(/ fas$/, " (solid)");
						option.text  = option.text.replace(/ fab$/, " (brand)");
						option.value = response.data[i].value;
						option.setAttribute("ng-value", option.value);
						// select_dom.add(option);
					}

					// Remove junk from AngularJS's value because the <option> didn't exist when it tried to set the value.
					var newval = select_jq.val().replace(/^\? .*?:/g, "").replace(/ \?/g, "");

					// Look for the matching element and set it.
					select_jq.children("option").each(function()
					{
						if(jQuery(this).val() == newval)
						{
							jQuery(this).attr("selected", "selected");
						}
					});

					// Wait a sec and then fire the change event.  This removes the blank select element that AngularJS added.
					setTimeout(function() { select_jq.change(); }, 10);
				},
				function(response)
				{
					error("Error Loading Module Settings", response.data, true, null);
				});
			});
		}

		$scope.getArray=function(n)
		{
			return new Array(n);
		};

		$scope.calc = function(id, count, event)
		{
		}

		// jQuery(window).on("load", function()
		// {
		// 	$scope.load_datasources();
		// });
	}]);

	app.directive('moduleSettings', ["$compile", function($compile)
	{
  		return {
  			templateUrl: '/directives/module-settings',
  			link: function($scope, element, attrs)
  			{
  				$scope.$watch
				(
					function(scope){ return $scope.module_settings_content; },
		          	function(newValue, oldValue)
		          	{
		          		element.html($scope.module_settings_content);
  						$compile(element.contents())($scope);
		          	}
		        );
  			}
    	};
	}]);

	app.directive('ckeditor', function()
	{
  		return {
    		require: '?ngModel',
    		link: function(scope, elm, attr, ngModel)
    		{
      			try
				{
					CKEDITOR.instances[elm[0]].destroy(true);
				}
				catch(e){}

      			var ck = CKEDITOR.replace(elm[0],
				{
					filebrowserBrowseUrl : nvFinderPath,
					filebrowserNvimageBrowseUrl : nvFinderPath + '?type=images',
					filebrowserNvdocumentBrowseUrl : nvFinderPath + '?type=documents',
					filebrowserUploadUrl : nvFinderPath + '/quick_upload?type=files',
					filebrowserNvimageUploadUrl : nvFinderPath + '/quick_upload?type=images',
					filebrowserNvdocumentUploadUrl : nvFinderPath + '/quick_upload?type=documents',
					height: '500px',
					toolbar: [
						{ name: 'document', items: [ 'Source', '-', 'RemoveFormat', '-', 'ShowBlocks' ] },
						{ name: 'insert', items: [ 'nvimage', 'nvpage', 'nvdocument', 'nvlink', 'Unlink', 'nvmodule', 'nvfontawesome', 'Table', 'HorizontalRule' ] },
						{ name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },
						{ name: 'clipboard', items: [ 'PasteText', 'PasteFromWord', '-', 'Scayt' ] },
						{ name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline' ] },
						{ name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'Blockquote', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
						{ name: 'styles', items: [ 'Styles', 'Format', 'FontSize' ] },
						{ name: 'colors', items: [ 'TextColor', 'BGColor' ] }
					]
				});

      			if (!ngModel) return;

      			ck.on('pasteState', function()
      			{
        			scope.$apply(function()
        			{
          				ngModel.$setViewValue(ck.getData());
        			});
      			});

      			ngModel.$render = function(value)
      			{
        			ck.setData(ngModel.$viewValue);
      			};
    		}
  		};
	});

	app.directive('ckeditorBasic', function()
	{
  		return {
    		require: '?ngModel',
    		link: function(scope, elm, attr, ngModel)
    		{
    			try
				{
					CKEDITOR.instances[elm[0]].destroy(true);
				}
				catch(e){}

      			var ck = CKEDITOR.replace(elm[0],
				{
					filebrowserBrowseUrl : nvFinderPath,
					filebrowserNvimageBrowseUrl : nvFinderPath + '?type=images',
					filebrowserNvdocumentBrowseUrl : nvFinderPath + '?type=documents',
					filebrowserUploadUrl : nvFinderPath + '/quick_upload?type=files',
					filebrowserNvimageUploadUrl : nvFinderPath + '/quick_upload?type=images',
					filebrowserNvdocumentUploadUrl : nvFinderPath + '/quick_upload?type=documents',
					height: '200px',
					toolbar: [
						{ name: 'document', items: [ 'Source', '-', 'RemoveFormat', '-', 'ShowBlocks' ] },
						{ name: 'insert', items: [ 'nvimage', 'nvpage', 'nvdocument', 'nvlink', 'Unlink', 'nvmodule', 'nvfontawesome', 'HorizontalRule' ] },
						{ name: 'links', items: [ 'Link', 'Unlink' ] },
						{ name: 'clipboard', items: [ 'PasteText', 'PasteFromWord', '-', 'Scayt' ] },
						{ name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline' ] },
						{ name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock' ] },
						{ name: 'styles', items: [ 'Styles', 'Format', 'FontSize' ] },
						{ name: 'colors', items: [ 'TextColor', 'BGColor' ] }
					]
				});

      			if (!ngModel) return;

      			ck.on('pasteState', function()
      			{
        			scope.$apply(function()
        			{
          				ngModel.$setViewValue(ck.getData());
        			});
      			});

      			ngModel.$render = function(value)
      			{
        			ck.setData(ngModel.$viewValue);
      			};
    		}
  		};
	});
})();
