(function (window, undefined){
	"use strict";
	pjQ.$.ajaxSetup({
		xhrFields: {
			withCredentials: true
		}
	});
	var document = window.document,
		validate = (pjQ.$.fn.validate !== undefined),
		routes = [];
	
	function log() {
		if (window.console && window.console.log) {
			for (var x in arguments) {
				if (arguments.hasOwnProperty(x)) {
					window.console.log(arguments[x]);
				}
			}
		}
	}
	
	function assert() {
		if (window && window.console && window.console.assert) {
			window.console.assert.apply(window.console, arguments);
		}
	}
	
	function hashBang(value) {
		if (value !== undefined && value.match(/^#!\//) !== null) {
			if (window.location.hash == value) {
				return false;
			}
			window.location.hash = value;
			return true;
		}
		
		return false;
	}
	
	function onHashChange() {
		var i, iCnt, m;
		for (i = 0, iCnt = routes.length; i < iCnt; i++) {
			m = window.location.hash.match(routes[i].pattern);
			if (m !== null) {
				pjQ.$(window).trigger(routes[i].eventName, m.slice(1));
				break;
			}
		}
		if (m === null) {
			pjQ.$(window).trigger("loadFields");
		}
	}
	pjQ.$(window).on("hashchange", function (e) {
    	onHashChange.call(null);
    });
	
	function pjNewsletter(opts) {
		if (!(this instanceof pjNewsletter)) {
			return new pjNewsletter(opts);
		}
				
		this.reset.call(this);
		this.init.call(this, opts);
		
		return this;
	}
	
	pjNewsletter.inObject = function (val, obj) {
		var key;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				if (obj[key] == val) {
					return true;
				}
			}
		}
		return false;
	};
	
	pjNewsletter.size = function(obj) {
		var key,
			size = 0;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				size += 1;
			}
		}
		return size;
	};
	
	pjNewsletter.prototype = {
		reset: function () {
			this.$container = null;			
			this.container = null;
			this.$fieldsContainer = null;
			this.$form = null;
			this.$messageWrapper = null;
			this.$errorWrapper = null;
			this.group_id = null;
			this.opts = {};
			return this;
		},
		
		disableButtons: function () {
			this.$container.find(".btn").each(function (i, el) {
				pjQ.$(el).attr("disabled", "disabled");
			});
		},
		enableButtons: function () {
			this.$container.find(".btn").removeAttr("disabled");
		},
		
		init: function (opts) {
			var self = this;
			this.opts = opts;
			this.container = document.getElementById("pjNewsletterContainer_" + self.opts.index);
						
			self.$container = pjQ.$(self.container);
			self.$fieldsContainer = pjQ.$("#nsl_form_field_" + self.opts.index);
			self.$form = pjQ.$("#nsl_subscribe_form_" + self.opts.index);
			
			this.$container.on("change.nl", ".pjNlGroupSelector", function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				self.group_id = pjQ.$("option:selected", this).val();
				self.loadFields.call(self);
			}).on("change.nl", ".pjNslBirthday", function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var day = self.$form.find("select[name='day']").val();
				var month = self.$form.find("select[name='month']").val();
				var year = self.$form.find("select[name='year']").val();
				if(day != '' && month != '' && year != '')
				{
					self.$form.find("input[name='birthday']").val(year + "-" + month + "-" + day).valid();
				}else{
					self.$form.find("input[name='birthday']").val("");
				}
			});
			
			pjQ.$(window).on("loadFields", this.$container, function (e) {
				
				self.loadFields.call(self);
			});
			
			if (window.location.hash.length === 0) {
				this.loadFields.call(this);
			} else {
				onHashChange.call(null);
			}
		},
		loadFields: function () {
			var self = this,
				index = this.opts.index,
				params = {};
			if(self.$form.find('input[name="group_id"]').length > 0)
			{
				self.group_id = self.$form.find('input[name="group_id"]').val();
			}
			params.locale = this.opts.locale;
			params.index = this.opts.index;
			if(self.group_id != null)
			{
				params.group_id = self.group_id;
			}
			if(self.opts.session_id != '')
			{
				params.session_id = self.opts.session_id;
			}
			pjQ.$.get([this.opts.folder, "index.php?controller=pjFront&action=pjActionLoadField"].join(""), params).done(function (data) {
				self.$fieldsContainer.html(data);
				self.bindForm.call(self);
			}).fail(function () {
				
			});
		},
		resetForm: function(){
			var self = this;
			
			if(self.$form.find('input[name="first_name"]').length > 0)
			{
				self.$form.find('input[name="first_name"]').val("");
			}
			if(self.$form.find('input[name="last_name"]').length > 0)
			{
				self.$form.find('input[name="last_name"]').val("");
			}
			if(self.$form.find('input[name="email"]').length > 0)
			{
				self.$form.find('input[name="email"]').val("");
			}
			if(self.$form.find('input[name="phone"]').length > 0)
			{
				self.$form.find('input[name="phone"]').val("");
			}
			if(self.$form.find('input[name="website"]').length > 0)
			{
				self.$form.find('input[name="website"]').val("");
			}
			if(self.$form.find('select[name="gender"]').length > 0)
			{
				self.$form.find('select[name="gender"]').val("");
			}
			if(self.$form.find('input[name="age"]').length > 0)
			{
				self.$form.find('input[name="age"]').val("");
			}
			if(self.$form.find('select[name="day"]').length > 0)
			{
				self.$form.find('select[name="day"]').val("");
			}
			if(self.$form.find('select[name="month"]').length > 0)
			{
				self.$form.find('select[name="month"]').val("");
			}
			if(self.$form.find('select[name="year"]').length > 0)
			{
				self.$form.find('select[name="year"]').val("");
			}
			if(self.$form.find('input[name="birthday"]').length > 0)
			{
				self.$form.find('input[name="birthday"]').val("");
			}
			if(self.$form.find('input[name="address"]').length > 0)
			{
				self.$form.find('input[name="address"]').val("");
			}
			if(self.$form.find('input[name="city"]').length > 0)
			{
				self.$form.find('input[name="city"]').val("");
			}
			if(self.$form.find('input[name="state"]').length > 0)
			{
				self.$form.find('input[name="state"]').val("");
			}
			if(self.$form.find('select[name="country_id"]').length > 0)
			{
				self.$form.find('select[name="country_id"]').val("");
			}
			if(self.$form.find('input[name="zip"]').length > 0)
			{
				self.$form.find('input[name="zip"]').val("");
			}
			if(self.$form.find('input[name="company_name"]').length > 0)
			{
				self.$form.find('input[name="company_name"]').val("");
			}
			if(self.$form.find('input[name="captcha"]').length > 0)
			{
				self.$form.find('input[name="captcha"]').val("").removeData("previousValue");
				var captcha_img = pjQ.$('#nsl_captcha_image_' + self.opts.index);
				captcha_img.attr("src", captcha_img.attr("src").replace(/(&rand=)\d+/g, '\$1' + Math.ceil(Math.random() * 99999)));
			}
		},
		bindForm: function(){
			var self = this;
			
			self.$messageWrapper = pjQ.$("#pjNslMessageWrapper_" + self.opts.index);
			self.$errorWrapper = pjQ.$("#pjNslErrorWrapper_" + self.opts.index);
			
			if(self.$form.length > 0 && validate)
			{
				var captcha_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionCheckCaptcha"].join("");
				var email_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionCheckEmail"].join("");
				if(self.opts.session_id != '')
				{
					captcha_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionCheckCaptcha", "&session_id=", self.opts.session_id].join("");
					email_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionCheckEmail", "&session_id=", self.opts.session_id].join("");
				}
				self.$form.validate({
					rules: {
						"captcha": {
							remote: {
								url : captcha_url,
								type : 'post',
								data : {
									group_id : function(){
										return self.group_id
									}
								}
							}
						},
						"email": {
							remote: {
								url : email_url,
								type : 'post',
								data : {
									group_id : function(){
										return self.group_id
									}
								}
							}
						}
					},
					onkeyup: false,
					errorClass: "pjNlFieldError",
					ignore: "",
					errorPlacement: function (error, element) {
						error.insertAfter(element);
					},
					highlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	$element.parent().parent().addClass('has-error');
		            },
		            unhighlight: function(ele, errorClass, validClass) {
		            	var $element = pjQ.$(ele);
		            	$element.parent().parent().removeClass('has-error').addClass('has-success');
		            },
		            submitHandler: function (form) {
		            	self.disableButtons.call(self);
						var $form = pjQ.$(form);
						var ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionFormSave"].join("");
						if(self.opts.session_id != '')
						{
							ajax_url = [self.opts.folder, "index.php?controller=pjFront&action=pjActionFormSave", "&session_id=", self.opts.session_id].join("");
						}
						self.$errorWrapper.hide();
						log(self.opts.message.info);
						self.$messageWrapper.html('<label class="message info">' + self.opts.message.info + '</label>').show();
						pjQ.$.post(ajax_url, $form.serialize()).done(function (data) {
							if(data == '100')
							{	
								self.$messageWrapper.html('<label class="message success">' + self.opts.message.success + '</label>');
								self.resetForm.call(self);
							}else if(data == '101'){
								self.$messageWrapper.html('<label class="message error">' + self.opts.message.error + '</label>');
							}else{
								self.$messageWrapper.html('<label class="message error">' + self.opts.validate[data] + '</label>');
							}
							self.enableButtons.call(self);
						}).fail(function () {
							self.enableButtons.call(self);
						});
						return false;
					}
				});
			}
		},
	};
	
	window.pjNewsletter = pjNewsletter;	
})(window);