var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateQuestion = $("#frmCreateQuestion"),
			$frmUpdateQuestion = $("#frmUpdateQuestion"),
			dialog = ($.fn.dialog !== undefined),
			tipsy = ($.fn.tipsy !== undefined),
			chosen = ($.fn.chosen !== undefined),
			validate = ($.fn.validate !== undefined),
			datagrid = ($.fn.datagrid !== undefined);
		
		if (chosen) {
			$("#category_id").chosen().change(function(){
				$(this).valid();
			});
			$("#user_id").chosen().change(function(){
				$(this).valid();
			});
		}
		if ($frmCreateQuestion.length > 0 && validate) {
			$frmCreateQuestion.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ''
			});
		}
		if ($frmUpdateQuestion.length > 0 && validate) {
			$frmUpdateQuestion.validate({
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ''
			});
		}
		function formatQuestion(str, obj)
		{
			if(obj.user_id == null)
			{
				return str + '<br/><i>' + myLabel.posted_by + ': ' + obj.name + '</i><br/>' + obj.created;
			}else{
				if(pjGrid.isAdmin == true)
				{
					return str + '<br/><i>' + myLabel.posted_by + ': <a href="index.php?controller=pjAdminUsers&action=pjActionUpdate&id='+obj.user_id+'">' + obj.name + '</a></i><br/>' + obj.created;
				}else{
					return str + '<br/><i>' + myLabel.posted_by + ': ' + obj.name + '</i><br/>' + obj.created;
				}
			}
		}
		function formatReplies(str, obj)
		{
			if(str != '0')
			{
				return '<a href="index.php?controller=pjAdminReplies&action=pjActionIndex&question_id='+obj.id+'">'+str+'</a>';
			}else{
				return str;
			}
		}
		if ($("#grid").length > 0 && datagrid) {
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminQuestions&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminQuestions&action=pjActionDeleteQuestion&id={:id}"}
				          ],
				columns: [{text: myLabel.question, type: "text", sortable: false, editable: false, width: 260, renderer: formatQuestion},
				          {text: myLabel.category, type: "text", sortable: true, editable: false, width: 120},
				          {text: myLabel.views, type: "text", sortable: true, editable: false, width: 55, align: 'center'},
				          {text: myLabel.replies, type: "text", sortable: true, editable: false, width: 63, align: 'center', renderer: formatReplies},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 90, editableWidth: 80, options: [
				                                                                                     {label: myLabel.New, value: "New"}, 
				                                                                                     {label: myLabel.Approved, value: "Approved"},
				                                                                                     {label: myLabel.Banned, value: "Banned"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminQuestions&action=pjActionGetQuestion" + pjGrid.queryString,
				dataType: "json",
				fields: ['question', 'category', 'counts', 'cnt_replies', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminQuestions&action=pjActionDeleteQuestionBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminQuestions&action=pjActionSaveQuestion&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=pjAdminQuestions&action=pjActionGetQuestion", "created", "DESC", 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=pjAdminQuestions&action=pjActionGetQuestion", "created", "DESC", 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=pjAdminQuestions&action=pjActionSetActive", {
				id: $(this).closest("tr").data("object")['id']
			}).done(function (data) {
				$grid.datagrid("load", "index.php?controller=pjAdminQuestions&action=pjActionGetQuestion");
			});
			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=pjAdminQuestions&action=pjActionGetQuestion", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("change", 'input[type=radio][name=posted_by]', function (e) {
			if (this.value == 'registered') {
				$('.pjSFExisting').show();
				$('.pjSFUnregistered').hide();
				$('#user_id').addClass('required');
				$('#name').removeClass('required').valid();
				$('#email').removeClass('required email').valid();
	        }else if (this.value == 'unregistered') {
	        	$('.pjSFExisting').hide();
				$('.pjSFUnregistered').show();
				$('#user_id').removeClass('required').valid();
				$('#name').addClass('required');
				$('#email').addClass('required email');
	        }		
		});
	});
})(jQuery_1_8_2);