var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		"use strict";
		var $frmCreateCampaign = $("#frmCreateCampaign"),
			$frmUpdateCampaign = $("#frmUpdateCampaign"),
			$dialogDelete = $("#dialogDeleteImage"),
			$dialogDeleteRecord = $("#dialogDeleteRecord"),
			dialog = ($.fn.dialog !== undefined),
			datagrid = ($.fn.datagrid !== undefined);
		
		if ($frmCreateCampaign.length > 0) {
			$frmCreateCampaign.validate({
				rules: {
					"title": {
						required: true,
						remote: "index.php?controller=pjAdminCampaigns&action=pjActionCheckTitle"
					}
				},
				messages: {
					"title": {
						remote: myLabel.title_taken
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em"
			});
		}
		if ($frmUpdateCampaign.length > 0) {
			$frmUpdateCampaign.validate({
				rules: {
					"title": {
						required: true,
						remote: "index.php?controller=pjAdminCampaigns&action=pjActionCheckTitle&id=" + $frmUpdateCampaign.find("input[name='id']").val()
					}
				},
				messages: {
					"title": {
						remote: myLabel.title_taken
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em"
			});
		}
		if ($dialogDelete.length > 0 && dialog) 
		{
			$dialogDelete.dialog({
				modal: true,
				autoOpen: false,
				resizable: false,
				draggable: false,
				width: 400,
				buttons: (function () {
					var buttons = {};
					buttons[frApp.locale.button.yes] = function () {
						$.ajax({
							type: "GET",
							dataType: "json",
							url: $dialogDelete.data('href'),
							success: function (res) {
								if(res.code == 200){
									$('#image_container').remove();
									$dialogDelete.dialog('close');
								}
							}
						});
					};
					buttons[frApp.locale.button.no] = function () {
						$dialogDelete.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
		
		function formatDonated(val, obj) {
			return ['<a href="index.php?controller=pjAdminDonations&action=pjActionIndex&campaign_id=', obj.id, '">', val, '</a>'].join("");
		}
		
		if ($("#grid").length > 0 && datagrid) 
		{
			var buttonOpts = [
			                  {type: "edit", url: "index.php?controller=pjAdminCampaigns&action=pjActionUpdate&id={:id}"},
					          {type: "remove", url: "index.php?controller=pjAdminCampaigns&action=pjActionDeleteCampaign&id={:id}"},
					          {type: "menu", url: "#", text: myLabel.more, items: [
	   				                {text: myLabel.preview, url: "index.php?controller=pjAdminOptions&action=pjActionPreview&cid={:id}", target: '_blank'}, 
	   				                {text: myLabel.donations, url: "index.php?controller=pjAdminDonations&action=pjActionIndex&campaign_id={:id}"}
	   				             ]
	   				          }
					          ];
			var actionOpts = [
							   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminCampaigns&action=pjActionDeleteCampaignBulk", render: true, confirmation: myLabel.delete_confirmation},
							   {text: myLabel.exported, url: "index.php?controller=pjAdminCampaigns&action=pjActionExportCampaign", ajax: false}
							];
			if (pjGrid.isEditor === true) 
			{
				buttonOpts = [
			                  {type: "edit", url: "index.php?controller=pjAdminCampaigns&action=pjActionUpdate&id={:id}"},
					          {type: "menu", url: "#", text: myLabel.more, items: [
	   				                {text: myLabel.donations, url: "index.php?controller=pjAdminDonations&action=pjActionIndex&campaign_id={:id}"}
	   				             ]
	   				          }
					          ];
				actionOpts = [
							   {text: myLabel.exported + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', url: "index.php?controller=pjAdminCampaigns&action=pjActionExportCampaign", ajax: false}
							];
			}
			var $grid = $("#grid").datagrid({
				buttons: buttonOpts,
				columns: [{text: myLabel.title, type: "text", sortable: true, editable: true, width: 220, editableWidth: 200},
				          {text: myLabel.donated, type: "text", sortable: true, editable: false, width: 140, renderer: formatDonated},
				          {text: myLabel.deadline, type: "text", sortable: true, editable: false, width: 80},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 100, options: [
				                                                                                     {label: myLabel.active, value: "T"}, 
				                                                                                     {label: myLabel.inactive, value: "F"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminCampaigns&action=pjActionGetCampaign",
				dataType: "json",
				fields: ['title', 'donated', 'deadline', 'status'],
				paginator: {
					actions: actionOpts,
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminCampaigns&action=pjActionSaveCampaign&id={:id}",
				select: {
					field: "id",
					name: "record[]"
				}
			});
			
			if ($dialogDeleteRecord.length > 0 && dialog) 
			{
				$dialogDeleteRecord.dialog({
					modal: true,
					autoOpen: false,
					resizable: false,
					draggable: false,
					width: 400,
					open: function(){
						$dialogDeleteRecord.html('');
						$.get("index.php?controller=pjAdminCampaigns&action=pjActionGetMessage", {
							"id": $dialogDeleteRecord.data('id')
						}).done(function (data) {
							$dialogDeleteRecord.html(data);
							$dialogDeleteRecord.dialog("option", "position", "center");
						});
					},
					buttons: (function () {
						var buttons = {};
						buttons[frApp.locale.button.stop] = function () {
							$.post("index.php?controller=pjAdminCampaigns&action=pjActionStopCampaign", {'id': $dialogDeleteRecord.data('id')}).done(function (data) {
								if(data.code == '200')
								{
									$dialogDeleteRecord.dialog("close");
									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=pjAdminCampaigns&action=pjActionGetCampaign", "title", "ASC", content.page, content.rowCount);
								}
							});
						};
						buttons[frApp.locale.button.yes] = function () {
							$.get($dialogDeleteRecord.data('href')).done(function (data) {
								if(data.code == '200')
								{
									$dialogDeleteRecord.dialog("close");
									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=pjAdminCampaigns&action=pjActionGetCampaign", "title", "ASC", content.page, content.rowCount);
								}
							});
							
						};
						buttons[frApp.locale.button.cancel] = function () {
							$dialogDeleteRecord.dialog("close");
						};
						
						return buttons;
					})()
				});
			}
		}
		
		$(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=pjAdminCampaigns&action=pjActionGetCampaign", "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=pjAdminCampaigns&action=pjActionGetCampaign", "title", "ASC", content.page, content.rowCount);
			return false;
		}).on("click", ".pj-status-1", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			return false;
		}).on("click", ".pj-status-0", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$.post("index.php?controller=pjAdminCampaigns&action=pjActionSetActive", {
				id: $(this).closest("tr").data("object")['id']
			}).done(function (data) {
				$grid.datagrid("load", "index.php?controller=pjAdminCampaigns&action=pjActionGetCampaign");
			});
			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=pjAdminCampaigns&action=pjActionGetCampaign", "title", "ASC", content.page, content.rowCount);
			return false;
		}).on("focusin", ".datepick", function (e) {
			var $this = $(this);
			$this.datepicker({
				firstDay: $this.attr("rel"),
				dateFormat: $this.attr("rev")
			});
		}).on("click", ".pj-form-field-icon-date", function (e) {
			var $dp = $(this).parent().siblings("input[type='text']");
			if ($dp.hasClass("hasDatepicker")) {
				$dp.datepicker("show");
			} else {
				$dp.trigger("focusin").datepicker("show");
			}
		}).on("click", ".icon-remove", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogDelete.data('href', $(this).data('href')).dialog("open");
		}).on("click", ".pj-table-icon-remove", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			var data_id = $(this).closest('tr').attr('data-id');
			data_id = data_id.replace('id_', '');
			$dialogDeleteRecord.data('href', $(this).attr('href')).data('id', data_id).dialog("open");
		});
	});
})(jQuery_1_8_2);