var jQuery_1_8_2 = jQuery_1_8_2 || $.noConflict();
(function ($, undefined) {
	$(function () {
		var $frmCreateReply = $("#frmCreateReply"),
			$frmUpdateReply = $("#frmUpdateReply"),
			$dialogReset = $('#dialogReset'),
			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();
			});
			$("#question_id").chosen().change(function(){
				$(this).valid();
			});
			$("#reply_id").chosen();
			$("#user_id").chosen().change(function(){
				$(this).valid();
			});
		}
		
		if($dialogReset.length > 0)
		{
			$dialogReset.dialog({
				modal: true,
				resizable: false,
				draggable: false,
				autoOpen: false,
				width: 250,
				buttons: (function () {
					var buttons = {};
					buttons[sfApp.locale.button.ok] = function () {
						$.post(["index.php?controller=pjAdminReplies&action=pjActionReset"].join(""), {id: $dialogReset.data('id')}).done(function (data) {
							if(data.code == '200')
							{
								$dialogReset.dialog("close");
								$('.pjSFLike').html('+ 0');
								$('.pjSFDislike').html('- 0');
							}
						}).fail(function () {
							
						});
					};
					buttons[sfApp.locale.button.cancel] = function () {
						$dialogReset.dialog("close");
					};
					return buttons;
				})()
			});
		}
		
		if ($frmCreateReply.length > 0 && validate) {
			$frmCreateReply.validate({
				rules: {
					"user_id": {
						required: function(e){
							if ($('#registered').is(':checked')) {
		                        return true;
		                    } else {
		                        return false;
		                    }
						}
					},
					"name": {
						required: function(e){
							if ($('#unregistered').is(':checked')) {
		                        return true;
		                    } else {
		                        return false;
		                    }
						}
					},
					"email": {
						required: function(e){
							if ($('#unregistered').is(':checked')) {
		                        return true;
		                    } else {
		                        return false;
		                    }
						},
						email: function(e){
							if ($('#unregistered').is(':checked')) {
		                        return true;
		                    } else {
		                        return false;
		                    }
						}
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ''
			});
		}
		if ($frmUpdateReply.length > 0 && validate) {
			$frmUpdateReply.validate({
				"user_id": {
					required: function(e){
						if ($('#registered').is(':checked')) {
	                        return true;
	                    } else {
	                        return false;
	                    }
					}
				},
				"name": {
					required: function(e){
						if ($('#unregistered').is(':checked')) {
	                        return true;
	                    } else {
	                        return false;
	                    }
					}
				},
				"email": {
					required: function(e){
						if ($('#unregistered').is(':checked')) {
	                        return true;
	                    } else {
	                        return false;
	                    }
					},
					email: function(e){
						if ($('#unregistered').is(':checked')) {
	                        return true;
	                    } else {
	                        return false;
	                    }
					}
				},
				errorPlacement: function (error, element) {
					error.insertAfter(element.parent());
				},
				onkeyup: false,
				errorClass: "err",
				wrapper: "em",
				ignore: ''
			});
		}
		function formatReply(str, obj)
		{
			return '<a href="index.php?controller=pjAdminQuestions&action=pjActionUpdate&id='+obj.question_id+'">' + obj.question + '</a><br/><i>' + myLabel.category + ': ' + obj.category + '</i><br/>' + str;
		}
		function formatCreated(str, obj)
		{
			if(obj.report == 0)
			{
				return str + '<br/>' + myLabel.rate + ': ' + '<span class="green">'+obj.likes+'</span> / <span class="red">'+obj.dislikes+'</span>';
			}else{
				return str + '<br/>' + myLabel.rate + ': ' + '<span class="green">'+obj.likes+'</span> / <span class="red">'+obj.dislikes+'</span><br/><span class="red bold">' + myLabel.reported + '</span>';
			}
		}
		if ($("#grid").length > 0 && datagrid) {
			
			var $grid = $("#grid").datagrid({
				buttons: [{type: "edit", url: "index.php?controller=pjAdminReplies&action=pjActionUpdate&id={:id}"},
				          {type: "delete", url: "index.php?controller=pjAdminReplies&action=pjActionDeleteReply&id={:id}"}
				          ],
				columns: [{text: myLabel.reply, type: "text", sortable: false, editable: false, width: 380, renderer: formatReply},
				          {text: myLabel.date_time, type: "text", sortable: true, editable: false, width: 120, renderer: formatCreated},
				          {text: myLabel.status, type: "select", sortable: true, editable: true, width: 100, editableWidth: 90, options: [
				                                                                                     {label: myLabel.New, value: "New"}, 
				                                                                                     {label: myLabel.Approved, value: "Approved"},
				                                                                                     {label: myLabel.Banned, value: "Banned"}
				                                                                                     ], applyClass: "pj-status"}],
				dataUrl: "index.php?controller=pjAdminReplies&action=pjActionGetReply" + pjGrid.queryString,
				dataType: "json",
				fields: ['description', 'created', 'status'],
				paginator: {
					actions: [
					   {text: myLabel.delete_selected, url: "index.php?controller=pjAdminReplies&action=pjActionDeleteReplyBulk", render: true, confirmation: myLabel.delete_confirmation}
					],
					gotoPage: true,
					paginate: true,
					total: true,
					rowCount: true
				},
				saveUrl: "index.php?controller=pjAdminReplies&action=pjActionSaveReply&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=pjAdminReplies&action=pjActionGetReply", "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=pjAdminReplies&action=pjActionGetReply", "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=pjAdminReplies&action=pjActionSetActive", {
				id: $(this).closest("tr").data("object")['id']
			}).done(function (data) {
				$grid.datagrid("load", "index.php?controller=pjAdminReplies&action=pjActionGetReply");
			});
			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=pjAdminReplies&action=pjActionGetReply", "created", "DESC", content.page, content.rowCount);
			return false;
		}).on("change", "#category_id", function (e) {
			$.get( "index.php?controller=pjAdminReplies&action=pjActionGetQuestions", { category_id: $(this).val()}, function( data ) {
				$('#pjSFQuestions').html(data);
				$("#question_id").chosen();
			});			
		}).on("change", "#question_id", function (e) {
			var question_id = $(this).val();
			$.get( "index.php?controller=pjAdminReplies&action=pjActionGetReplies", { question_id: question_id}, function( data ) {
				$('#pjSFReplies').html(data);
				$("#reply_id").chosen();
			});
			if(question_id == '')
			{
				$('#pjSfEditQuestion').css('display', 'none');
			}else{
				$('#pjSfEditQuestion').attr('href', 'index.php?controller=pjAdminQuestions&action=pjActionUpdate&id=' + question_id).css('display', 'inline-block');
			}
		}).on("change", "#reply_id", function (e) {
			var reply_id = $(this).val();
			if(reply_id == '')
			{
				$('#pjSfEditReply').css('display', 'none');
			}else{
				$('#pjSfEditReply').attr('href', 'index.php?controller=pjAdminReplies&action=pjActionUpdate&id=' + reply_id).css('display', 'inline-block');
			}
		}).on("change", "#user_id", function (e) {
			var user_id = $(this).val();
			if(user_id == '')
			{
				$('#pjSfEditUser').css('display', 'none');
			}else{
				$('#pjSfEditUser').attr('href', 'index.php?controller=pjAdminUsers&action=pjActionUpdate&id=' + user_id).css('display', 'inline-block');
			}
		}).on("change", 'input[type=radio][name=posted_by]', function (e) {
			if (this.value == 'registered') {
				$('.pjSFExisting').show();
				$('.pjSFUnregistered').hide();
	        }else if (this.value == 'unregistered') {
	        	$('.pjSFExisting').hide();
				$('.pjSFUnregistered').show();
	        }		
		}).on("click", '.pjSfResetVotes', function (e) {
			if (e && e.preventDefault) {
				e.preventDefault();
			}
			$dialogReset.data('id', $(this).attr('data-id')).dialog('open');
		});
	});
})(jQuery_1_8_2);