/*!
 * Stiva Forum Script v3.0
 * 
 * http://www.phpjabbers.com/stiva-forum-script/
 * 
 * Copyright 2015, StivaSoft Ltd.
 * 
 */
(function (window, undefined){
	"use strict";
	
	var document = window.document,
		validate = (pjQ.$.fn.validate !== undefined);
    
	function loadDelayedCSS(opts) {
		pjQ.$(window).load(function() {
			  pjQ.$('body').append(pjQ.$('<link rel="stylesheet" type="text/css" />').attr('href', opts.server+'app/web/css/transitions.css'));
		});
	}
	
	function log() {
		if (window.console && window.console.log) {
			for (var x in arguments) {
				if (arguments.hasOwnYacht(x)) {
					window.console.log(arguments[x]);
				}
			}
		}
	}
	
	function assert() {
		if (window && window.console && window.console.assert) {
			window.console.assert.apply(window.console, arguments);
		}
	}
	
	function StivaForum(opts) {
		if (!(this instanceof StivaForum)) {
			return new StivaForum(opts);
		}
				
		this.reset.call(this);
		this.init.call(this, opts);
		
		return this;
	}
	
	StivaForum.inObject = function (val, obj) {
		var key;
		for (key in obj) {
			if (obj.hasOwnYacht(key)) {
				if (obj[key] == val) {
					return true;
				}
			}
		}
		return false;
	};
	
	StivaForum.size = function(obj) {
		var key,
			size = 0;
		for (key in obj) {
			if (obj.hasOwnYacht(key)) {
				size += 1;
			}
		}
		return size;
	};
	
	StivaForum.prototype = {
		reset: function () {
			this.$container = null;
			this.container = null;			
			this.opts = {};
			
			return this;
		},
		disableButtons: function () {
			var $el;
			this.$container.find(".pjCfBtn").each(function (i, el) {
				$el = pjQ.$(el).attr("disabled", "disabled");
			});
		},
		enableButtons: function () {
			this.$container.find(".pjCfBtn").removeAttr("disabled");
		},
		init: function (opts) {
			var self = this;
			this.opts = opts;
			this.container = document.getElementById("pjWrapper");
			this.$container = pjQ.$(this.container);
			
			loadDelayedCSS(opts);
			
			self.bindRegisterForm();
			self.bindLoginForm();
			self.bindForgotForm();
			self.bindProfileForm();
			self.bindAskForm();
			
			if (pjQ.$('.pjCfAddFile').length) 
			{
				var holderSelector = '.pjCfAddFile';
				var hasSelectedClass = 'pjCfAddFileAdded';
				var inputSelector = '.pjCfFileUploadField';
				var $accountImage = pjQ.$('.pjCfAddFileImage img');
				var $accountImageInitialSrc = $accountImage.attr('src');

				pjQ.$(inputSelector).on('change', function(eF) {
					var input = this;
					if(pjQ.$(input).valid())
					{
						if(eF.target.files[0] != undefined)
						{
							pjQ.$(input).closest(holderSelector).toggleClass(hasSelectedClass, input.value !== '');
							$accountImage.attr('src', URL.createObjectURL(eF.target.files[0]));
						}
						pjQ.$('.pjCfBtnReset').on('click', function(e) {
							$accountImage.attr('src', $accountImageInitialSrc);
							pjQ.$(inputSelector).val('');
							pjQ.$(input).closest(holderSelector).removeClass(hasSelectedClass);

							e.preventDefault();
						});
					}
				});
			};
			
			this.$container.on('click', '.pjCfFilter', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var $frm = pjQ.$('#pjCfFormSearch_' + self.opts.index);
				if(pjQ.$('#pjCfFormActivity_' + self.opts.index).length > 0)
				{
					$frm = pjQ.$('#pjCfFormActivity_' + self.opts.index);
				}
				$frm.find("input[name='column']").val(pjQ.$(this).attr('data-column'));
				$frm.find("input[name='direction']").val(pjQ.$(this).attr('data-direction'));
				$frm.submit();
			}).on('click', '.pjCfPagingItem', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var $frm = pjQ.$('#pjCfFormSearch_' + self.opts.index);
				if(pjQ.$('#pjCfFormActivity_' + self.opts.index).length > 0)
				{
					$frm = pjQ.$('#pjCfFormActivity_' + self.opts.index);
				}
				$frm.find("input[name='pjPage']").val(pjQ.$(this).attr('data-page'));
				$frm.submit();
			}).on('click', '.pjCfReply', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				
				var $this = pjQ.$(this),
					$cloneForm = pjQ.$('#pjCfPostReplyClone_' + self.opts.index),
					$replyForm = pjQ.$('#pjCfCommentsReply_' + self.opts.index);
				if($replyForm.length > 0)
				{
					$replyForm.remove();
				}
				$cloneForm.find("input[name='reply_id']").val($this.attr('data-id'));
				var html = $cloneForm.html();
				html = html.replace(/\{INDEX\}/g, self.opts.index);
				html = html.replace(/\{REPLYID\}/g, '&rid=' + $this.attr('data-id'));
				pjQ.$(html).insertAfter($this);
				
				self.bindReplyForm();
			}).on('click', '.pjCfBtnClose', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var index = pjQ.$(this).attr('data-index');
				pjQ.$('#pjCfCommentsReply_' + index).remove();
			}).on('click', '.pjCfVote', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				if (!pjQ.$(this).is('[disabled=disabled]')) 
				{
					var reply_id = pjQ.$(this).attr('data-id'),
						vote = pjQ.$(this).attr('data-vote');
					pjQ.$('.pjCfVote').attr("disabled", "disabled");
					pjQ.$.get([self.opts.folder, "index.php?controller=pjLoad&action=pjActionVote"].join(""), {reply_id: reply_id, vote: vote}).done(function (data) {
						pjQ.$('#pjCfLike_' + reply_id).html(data.likes);
						pjQ.$('#pjCfDisLike_' + reply_id).html(data.dislikes);
						pjQ.$('.pjCfVote').removeAttr("disabled");
					}).fail(function () {
						log('101');
					});
				}
			}).on('click', '.pjCfReport', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var reply_id = pjQ.$(this).attr('data-id');
				
				pjQ.$('#pjCfReportButton_' + self.opts.index).attr('data-id', pjQ.$(this).attr('data-id'));
				pjQ.$('#pjCfReportModal').modal('show');
				pjQ.$('.modal-dialog').css("z-index", "99999");
				
			}).on('click', '#pjCfReportButton_' + self.opts.index, function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var reply_id = pjQ.$(this).attr('data-id');
				
				pjQ.$.get([self.opts.folder, "index.php?controller=pjLoad&action=pjActionReport"].join(""), {reply_id: reply_id}).done(function (data) {
					pjQ.$('#pjCfReportModal').modal('hide');
				}).fail(function () {
					log('101');
				});
			});
				
			var questionID = pjQ.$('#pjCfQuestionID_' + self.opts.index),
				replyID = pjQ.$('#pjCfReplyID_' + self.opts.index),
				showReplyID = pjQ.$('#pjCfShowReply_' + self.opts.index);
			
			if(questionID.length > 0)
			{
				self.$container.find('.pjCfReply').each(function(e){
					var $this = pjQ.$(this);
					if(replyID.length > 0)
					{
						if($this.attr('data-id') == replyID.val())
						{
							$this.trigger('click');
							pjQ.$('html,body').animate({
								scrollTop: $this.offset().top
					        }, 500);
						}
					}else{
						if($this.attr('data-id') == '')
						{
							$this.trigger('click');
							pjQ.$('html,body').animate({
								scrollTop: $this.offset().top
					        }, 500);
						}
					}
				});
			}
			if(showReplyID.length > 0)
			{
				pjQ.$('html,body').animate({
					scrollTop: pjQ.$('#pjCfComment_' + showReplyID.val()).offset().top
		        }, 1000);
			}
		},
		bindReplyForm: function()
		{
			var self = this;
			var $frmReply = pjQ.$('#pjCfReplyForm_' + self.opts.index);
			
			if($frmReply.length > 0)
			{
				$frmReply.validate({
					rules: {
						"captcha": {
							remote: self.opts.folder + "index.php?controller=pjFront&action=pjActionCheckCaptcha"
						}
					},
					ignore: "",
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						error.appendTo(element.next().find('ul'));	
					},
					highlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	$element.parent().addClass('has-error');
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	$element.parent().removeClass('has-error').addClass('has-success');
		            },
		            submitHandler: function(form){
		            	self.disableButtons.call(self);
		            	pjQ.$.post([self.opts.folder, "index.php?controller=pjLoad&action=pjActionSaveReply"].join(""), $frmReply.serialize()).done(function (data) {
							var $msg_container = pjQ.$('#pjCfReplyMessage_' + self.opts.index);
							if(data.status != 'ERR')
							{
								$msg_container.addClass('alert-success');
								var rand = Math.floor((Math.random()*999999)+1),
									$cloneCaptchaImg = pjQ.$('#pjCfPostReplyClone_' + self.opts.index).find('.pjCfCaptchaImage').eq(0),
									$name = $frmReply.find("input[name='name']"),
									$email = $frmReply.find("input[name='email']"),
									$captchaImg = $frmReply.find('.pjCfCaptchaImage').eq(0);
								
								var imageSrc = self.opts.folder + 'index.php?controller=pjFront&action=pjActionCaptcha&rand=' + rand;
								$cloneCaptchaImg.attr("src", imageSrc);
								$captchaImg.attr("src", imageSrc);
								
								$frmReply.find("textarea[name='description']").val("");
								$frmReply.find("input[name='captcha']").val("");
								if ( !$name.is('[readonly]') ) {
									$name.val("");
									$email.val("");
								}
								self.enableButtons.call(self);
								if(data.status == 'Approved')
								{
									window.setTimeout(function() {
										window.location.href = $frmReply.find("input[name='redirect_url']").val();
									}, 2000);
								}
							}else{
								$msg_container.addClass('alert-danger');
								self.enableButtons.call(self);
							}
							$msg_container.html(data.text).show();
						}).fail(function () {
							log('101');
						});
		            	return false;
		            }
				});
			}
		},
		bindRegisterForm: function()
		{
			var self = this;
			var $frmRegister = pjQ.$('#pjSFRegisterForm_' + self.opts.index);
			
			if($frmRegister.length > 0)
			{
				$frmRegister.validate({
					rules: {
						"email": {
							remote: self.opts.folder + "index.php?controller=pjLoad&action=pjActionCheckEmail"
						},
						"captcha": {
							remote: self.opts.folder + "index.php?controller=pjFront&action=pjActionCheckCaptcha"
						},
						"reenter_password":{
							equalTo: "#pjSFPassword"
						},
						"avatar":{
							extension: "jpg|jpeg|png|gif|bmp"
						}
					},
					ignore: "",
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						if(element.attr('name') == 'avatar')
						{
							error.appendTo(element.parent().parent().next().find('ul'));	
						}else{
							error.appendTo(element.next().find('ul'));	
						}
					},
					highlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	if($element.attr('name') == 'avatar')
		            	{
		            		$element.parent().parent().parent().addClass('has-error');
		            	}else{
		            		$element.parent().addClass('has-error');
		            	}
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	if($element.attr('name') == 'avatar')
		            	{
		            		$element.parent().parent().parent().removeClass('has-error').addClass('has-success');
		            	}else{
		            		$element.parent().removeClass('has-error').addClass('has-success');
		            	}
		            }
				});
			}
		},
		bindLoginForm: function()
		{
			var self = this;
			var $frmLogin = pjQ.$('#pjSFLogInForm_' + self.opts.index);
			
			if($frmLogin.length > 0)
			{
				$frmLogin.validate({
					ignore: "",
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						error.appendTo(element.next().find('ul'));
					},
					highlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	$element.parent().addClass('has-error');
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	$element.parent().removeClass('has-error').addClass('has-success');
		            }
				});
			}
		},
		bindForgotForm: function()
		{
			var self = this;
			var $frmForgot = pjQ.$('#pjSFForgotForm_' + self.opts.index);
			
			if($frmForgot.length > 0)
			{
				$frmForgot.validate({
					ignore: "",
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						error.appendTo(element.next().find('ul'));
					},
					highlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	$element.parent().addClass('has-error');
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	$element.parent().removeClass('has-error').addClass('has-success');
		            }
				});
			}
		},
		bindProfileForm: function()
		{
			var self = this;
			var $frmProfile = pjQ.$('#pjSFProfileForm_' + self.opts.index),
				$activityContainer = pjQ.$('#pjCfActivity_' + self.opts.index);
			
			if($activityContainer.length > 0)
			{
				pjQ.$('html,body').animate({
					scrollTop: $activityContainer.offset().top
		        }, 500);
			}
			if($frmProfile.length > 0)
			{
				$frmProfile.validate({
					rules: {
						"email": {
							remote: self.opts.folder + "index.php?controller=pjLoad&action=pjActionCheckEmail&id=" + $frmProfile.find("input[name='id']").val()
						},
						"avatar":{
							extension: "jpg|jpeg|png|gif|bmp"
						}
					},
					ignore: "",
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						if(element.attr('name') == 'avatar')
						{
							error.appendTo(element.parent().parent().next().find('ul'));	
						}else{
							error.appendTo(element.next().find('ul'));	
						}
					},
					highlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	if($element.attr('name') == 'avatar')
		            	{
		            		$element.parent().parent().parent().addClass('has-error');
		            	}else{
		            		$element.parent().addClass('has-error');
		            	}
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	if($element.attr('name') == 'avatar')
		            	{
		            		$element.parent().parent().parent().removeClass('has-error').addClass('has-success');
		            	}else{
		            		$element.parent().removeClass('has-error').addClass('has-success');
		            	}
		            }
				});
			}
		},
		bindAskForm: function()
		{
			var self = this;
			var $frmAsk = pjQ.$('#pjSFAskForm_' + self.opts.index);
			
			if($frmAsk.length > 0)
			{
				$frmAsk.validate({
					rules: {
						"captcha": {
							remote: self.opts.folder + "index.php?controller=pjFront&action=pjActionCheckCaptcha"
						}
					},
					ignore: "",
					onkeyup: false,
					errorElement: 'li',
					errorPlacement: function (error, element) {
						if(element.attr('name') == 'avatar')
						{
							error.appendTo(element.parent().parent().next().find('ul'));	
						}else{
							error.appendTo(element.next().find('ul'));	
						}
					},
					highlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	if($element.attr('name') == 'avatar')
		            	{
		            		$element.parent().parent().parent().addClass('has-error');
		            	}else{
		            		$element.parent().addClass('has-error');
		            	}
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	if($element.attr('name') == 'avatar')
		            	{
		            		$element.parent().parent().parent().removeClass('has-error').addClass('has-success');
		            	}else{
		            		$element.parent().removeClass('has-error').addClass('has-success');
		            	}
		            }
				});
			}
		}
	};
	
	window.StivaForum = StivaForum;	
})(window);