var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateMember = $("#frmCreateMember"),
			$frmUpdateMember = $("#frmUpdateMember"),
			$frmExportMembers = $("#frmExportMembers"),
			$frmImportMember = $("#frmImportMember"),
			$dialogDelete = $("#dialogDelete"),
			gallery = ($.fn.gallery !== undefined),
			dialog = ($.fn.dialog !== undefined),
			tabs = ($.fn.tabs !== undefined),
			chosen = ($.fn.chosen !== 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 (chosen) {
			$("#skill_id").chosen();
			$("#country_id").chosen();
		}
		
		function checkSource()
		{
			var source = $("input:radio[name='source']:checked").val();
			$('.nlSource').hide();
			switch(source)
			{
				case 'csv':
					$('.nlSourceCSV').show();
					break;
				case 'excel':
					$('.nlSourceExcel').show();
					break;
			}
		}
		
		if ($frmCreateMember.length > 0 && validate) {
			$frmCreateMember.validate({
				rules: {
					"email": {
						remote: "index.php?controller=pjAdminMembers&action=pjActionCheckEmail"
					}
				},
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'age')
					{
						error.insertAfter(element.parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		}
		if ($frmUpdateMember.length > 0 && validate) {
			$frmUpdateMember.validate({
				rules: {
					"email": {
						remote: "index.php?controller=pjAdminMembers&action=pjActionCheckEmail&id=" + $frmUpdateMember.find("input[name='id']").val()
					}
				},
				errorPlacement: function (error, element) {
					if(element.attr('name') == 'age')
					{
						error.insertAfter(element.parent().parent());
					}else{
						error.insertAfter(element.parent());
					}
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ""
			});
		}
		
		if ($frmExportMembers.length > 0 && validate) {
			$frmExportMembers.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 ($frmImportMember.length > 0 && validate) {
			
			$frmImportMember.validate({
				rules: {
					"csv":{
						required: function(){
							if($("input:radio[name='source']:checked").val() == 'csv'){
								return true;
							}else{
								return false;
							}
						},
						extension: "csv"
					},
					"members":{
						required: function(){
							if($("input:radio[name='source']:checked").val() == 'excel'){
								return true;
							}else{
								return false;
							}
						}
					}
				},
				messages: {
					csv:{
						extension: myLabel.csv_allowed
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ''
			});
			checkSource.call(null);
		}

		if ($dialogDelete.length > 0 && dialog) {
			$dialogDelete.dialog({
				modal: true,
				resizable: false,
				draggable: false,
				autoOpen: false,
				width: 350,
				buttons: (function () {
					var buttons = {};
					buttons[mlApp.locale.button.delete] = function () {
						$.get("index.php?controller=pjAdminMembers&action=pjActionDeleteAvatar&id=" + $dialogDelete.data('id')).done(function (data) {
							$('.pjMLDeleteAvatar').parent().parent().remove();
							$dialogDelete.dialog("close");
						});
					};
					buttons[mlApp.locale.button.cancel] = function () {
						$dialogDelete.dialog("close");
					};
					
					return buttons;
				})()
			});
		}
				
		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 + ($frmUpdateMember.length > 0 ? "&query_string=" + encodeURIComponent("controller=pjAdminMembers&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) {
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminMembers&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminMembers&action=pjActionDeleteMember&id={:id}"}
				          ],
				columns: [{text: myLabel.name, type: "text", sortable: true, editable: true, width: 210, editableWidth: 190},
				          {text: myLabel.email, type: "text", sortable: true, editable: true, width: 280, editableWidth: 260},
				          {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=pjAdminMembers&action=pjActionGetMember",
				dataType: "json",
				fields: ['name', 'email', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminMembers&action=pjActionDeleteMemberBulk", render: true, confirmation: myLabel.delete_confirmation},
					   {text: myLabel.revert_status, url: "index.php?controller=pjAdminMembers&action=pjActionStatusMember", render: true},
					   {text: myLabel.exported, url: "index.php?controller=pjAdminMembers&action=pjActionExportMember", ajax: false}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminMembers&action=pjActionSaveMember&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=pjAdminMembers&action=pjActionGetMember", "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("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=pjAdminMembers&action=pjActionGetMember", "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=pjAdminMembers&action=pjActionGetMember", "name", "ASC", content.page, content.rowCount);
			return false;
		}).on("click", ".pjMLDeleteAvatar", function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogDelete.data('id', $(this).attr('data-id')).dialog('open');
			return false;
		}).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", "#members_feed", function (e) {
			$(this).select();
		}).on("change", "input:radio", function (e) {
			if ($frmImportMember.length > 0) {
				checkSource.call(null);
			}
			return false;
		});
	});
})(jQuery_1_8_2);