/*!
 * Fundrasing script v1.0
 * https://www.phpjabbers.com/fundrasing-script/
 * 
 * Copyright 2014, StivaSoft Ltd.
 * 
 */
(function (window, undefined){
	"use strict";
	var document = window.document,
		validate = (pjQ.$.fn.validate !== undefined),
		routes = [
		          	{pattern: /^#!\/loadCampaign$/, eventName: "loadCampaign"},
	          		{pattern: /^#!\/loadForm$/, eventName: "loadForm"}
		          ];
	
	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("loadForm");
		}
	}
	pjQ.$(window).on("hashchange", function (e) {
    	onHashChange.call(null);
    });
	
	function Fundrasing(opts) {
		if (!(this instanceof Fundrasing)) {
			return new Fundrasing(opts);
		}
				
		this.reset.call(this);
		this.init.call(this, opts);
		
		return this;
	}
	
	Fundrasing.inObject = function (val, obj) {
		var key;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				if (obj[key] == val) {
					return true;
				}
			}
		}
		return false;
	};
	
	Fundrasing.size = function(obj) {
		var key,
			size = 0;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				size += 1;
			}
		}
		return size;
	};
	
	Fundrasing.prototype = {
		reset: function () {
			this.$container = null;			
			this.container = null;
			this.opts = {};

			return this;
		},
		disableButtons: function () {
			this.$container.find(".frButton").each(function (i, el) {
				pjQ.$(el).attr("disabled", "disabled").addClass("frButtonDisabled");
			});
		},
		enableButtons: function () {
			this.$container.find(".frButton").removeAttr("disabled").removeClass("frButtonDisabled");
		},
		init: function (opts) {
			var self = this;
			this.opts = opts;
			this.container = document.getElementById("frContainer_" + self.opts.cid);
			
			self.$container = pjQ.$(self.container);
			
			this.$container.on("click.fr", ".frReadMore", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				pjQ.$('#frContainer_' + self.opts.cid + ' .frShortDesc').css('display', 'none');
				pjQ.$('#frContainer_' + self.opts.cid + ' .frFullDesc').css('display', 'block');
				return false;
			}).on("click.fr", ".frReadLess", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				pjQ.$('#frContainer_' + self.opts.cid + ' .frShortDesc').css('display', 'block');
				pjQ.$('#frContainer_' + self.opts.cid + ' .frFullDesc').css('display', 'none');
				return false;
			}).on("keydown.fr", ".frAmountText", function (e) {
				if (e.shiftKey == true) {
		            e.preventDefault();
		        }
		        if ((e.keyCode >= 48 && e.keyCode <= 57) || 
		            (e.keyCode >= 96 && e.keyCode <= 105) || 
		            e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 37 ||
		            e.keyCode == 39 || e.keyCode == 46 || e.keyCode == 190 || e.keyCode == 110) {

		        } else {
		            e.preventDefault();
		        }
		        if(pjQ.$(this).val().indexOf('.') !== -1 && e.keyCode == 190)
		        {
		        	alert(e.keyCode);
		        	e.preventDefault();
		        }
			}).on("click.fr", ".frButtonDonate", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				self.setAmount.call(self, 'loadForm');
			}).on("change.fr", "#frPaymentMethod_" + self.opts.cid, function (e) {
				if(pjQ.$(this).val() == 'creditcard')
				{
					pjQ.$('.frBoxCC').show();
				}else{
					pjQ.$('.frBoxCC').hide();
				}
			}).on("click.fr", ".frTerms", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				pjQ.$('.frTermsContainer').slideToggle();
			}).on("click.fr", ".frCancelDonation", function (e) {
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				var attr = pjQ.$(this).attr('data-completed');
				if (typeof attr !== typeof undefined && attr !== false) {
					hashBang("#!/loadCampaign");
				}else{
					self.setAmount.call(self, 'loadCampaign');
				}
			});
			
			pjQ.$(window).on("loadCampaign", this.$container, function (e) {
				self.loadCampaign.call(self, 0);
			}).on("loadForm", this.$container, function (e) {
				self.loadForm.call(self, 0);
			});
			
			if (window.location.hash.length === 0) {
				this.loadCampaign.call(this);
			} else {
				onHashChange.call(null);
			}
		},
		getPaymentForm: function(obj){
			var self = this,
				params = { "cid": this.opts.cid, "donation_id": obj.donation_id };
			
			pjQ.$.get([this.opts.folder, "index.php?controller=pjFront&action=pjActionGetPaymentForm"].join(""), params).done(function (data) {
				
				var $msg_container = pjQ.$('#frNoticeMessage_' + self.opts.cid);
				$msg_container.removeClass('frError').html(data);
				$msg_container.show();
				switch (obj.payment_method) {
					case 'paypal':
						self.$container.find("form[name='frPaypal']").trigger('submit');
						break;
					case 'authorize':
						self.$container.find("form[name='frAuthorize']").trigger('submit');
						break;
					case 'creditcard':
					case 'bank':
					case 'cash':
						pjQ.$('#frDonateForm_' + self.opts.cid + ' :input').prop("disabled", true);
						pjQ.$('.frCancelDonation').attr('data-completed', '1');
						break;
				}
			}).fail(function () {
				log("Deferred is rejected");
			});
		},
		setAmount: function(loadBang)
		{
			var self = this,
				amount = pjQ.$('#frAmount_' + self.opts.cid).val();
			if(amount != '')
			{
				self.disableButtons.call(self);
				pjQ.$.post([this.opts.folder, "index.php?controller=pjFront&action=pjActionSetAmount&cid=" + self.opts.cid].join(""), {'amount': amount}).done(function (data) {
					if(data.status == 'OK')
					{
						hashBang("#!/" + loadBang);
					}	
				}).fail(function () {
					
				});
			}
		},
		loadCampaign: function () {
			var self = this,
				params = { "cid": this.opts.cid };
			pjQ.$.get([this.opts.folder, "index.php?controller=pjFront&action=pjActionLoadCampaign"].join(""), params).done(function (data) {
				self.$container.html(data);
			}).fail(function () {
				
			});
		},
		loadForm: function () {
			var self = this,
				params = { "amount": self.amount };
			pjQ.$.post([this.opts.folder, "index.php?controller=pjFront&action=pjActionLoadForm&cid=" + this.opts.cid].join(""), params).done(function (data) {
				self.$container.html(data);
				if (validate) 
				{
					pjQ.$('#frDonateForm_' + self.opts.cid).validate({
						onkeyup: false,
						onclick: false,
						onfocusout: false,
						errorClass: "frError",
						validClass: "frValid",
						wrapper: "em",
						errorPlacement: function (error, element) {
							if(element.attr('name') == 'terms')
							{
								error.insertAfter(element.parent());
							}else{
								error.insertAfter(element);
							}
						},
						submitHandler: function (form) {
							self.disableButtons.call(self);
							var $msg_container = pjQ.$('#frNoticeMessage_' + self.opts.cid);
							$msg_container.html(self.opts.message);
							$msg_container.show();
							
							var $form = pjQ.$(form);
							pjQ.$.post([self.opts.folder, "index.php?controller=pjFront&action=pjActionDonate&cid=", self.opts.cid].join(""), $form.serialize()).done(function (data) {
								if (data.status == "OK") {
									self.getPaymentForm.call(self, data);
								} else if (data.status == "ERR") {
									$msg_container.addClass('.frError').html(data.text);
									self.enableButtons.call(self);
								}
							}).fail(function () {
								self.enableButtons.call(self);
							});
							return false;
						}
					});
				}
			}).fail(function () {
				
			});
		}
	};
	window.Fundrasing = Fundrasing;	
})(window);