/*!
 * >Make an Offer Widget v1.0
 * https://www.phpjabbers.com/make-an-offer-widget/
 * 
 * Copyright 2015, StivaSoft Ltd.
 * 
 */
(function (window, undefined){
	"use strict";
	
	pjQ.$.ajaxSetup({
		xhrFields: {
			withCredentials: true
		}
	});
	
	var document = window.document,
		validate = (pjQ.$.fn.validate !== undefined),
		datepicker = (pjQ.$.fn.datepicker !== undefined),
		dialog = (pjQ.$.fn.dialog !== 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("loadEvents");
		}
	}
	pjQ.$(window).on("hashchange", function (e) {
    	onHashChange.call(null);
    });
	
	function MakeOffer(opts) {
		if (!(this instanceof MakeOffer)) {
			return new MakeOffer(opts);
		}
				
		this.reset.call(this);
		this.init.call(this, opts);
		
		return this;
	}
	
	MakeOffer.inObject = function (val, obj) {
		var key;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				if (obj[key] == val) {
					return true;
				}
			}
		}
		return false;
	};
	
	MakeOffer.size = function(obj) {
		var key,
			size = 0;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) {
				size += 1;
			}
		}
		return size;
	};
	pjQ.$.validator.addMethod('positiveNumber', function (value) { 
		return Number(value) >= 0;
	});
	MakeOffer.prototype = {
		reset: function () {
			this.$container = null;
			this.container = null;
			this.$sectionMakeOffer = null;
			this.opts = {};
			
			this.sortby = null;
			this.space_id = null;
			return this;
		},
		disableButtons: function () {
			var $el;
			this.$container.find(".btn").each(function (i, el) {
				$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("spContainer_" + this.opts.index);
			this.$container = pjQ.$(this.container);
			
			this.$container.on('click.sp', '.btnSectionTrigger', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				self.$sectionMakeOffer.toggleClass('sectionMakeOfferStepOne');
			}).on('click.sp', '.btnFormRemove', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				self.$sectionMakeOffer.removeClass('sectionMakeOfferStepOne');
			}).on('click.sp', '.btnFormBack', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				pjQ.$('#frmSubmitEmail_'+ self.opts.index).hide();
				pjQ.$('#frmRequestMakeOffer_'+ self.opts.index).show();
			}).on('click.sp', '.btnSectionRemove', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				self.$sectionMakeOffer.addClass('sectionMakeOfferHidden');
			});
			
			pjQ.$('.pjCBOfferPrice').on('click.sp', function(e){
				if (e && e.preventDefault) {
					e.preventDefault();
				}
				pjQ.$('.btnSectionTrigger').trigger('click.sp');
			});
			
			pjQ.$(window).on("loadForm", this.container, function (e) {
				self.loadForm.call(self);
			});
			
			if (window.location.hash.length === 0) {
				this.loadForm.call(this);
			} else {
				onHashChange.call(null);
			}
		},
		loadForm: function () {
			var self = this,
				index = this.opts.index,
				params = 	{
								"theme": this.opts.theme,
								"index": this.opts.index
							};
			pjQ.$.get([this.opts.folder, "index.php?controller=pjFront&action=pjActionForm"].join(""), params).done(function (data) {
				self.$container.html(data);
				self.$sectionMakeOffer = self.$container.find('.sectionMakeOffer');
				
				if (validate) 
				{
					var $frmRequest = pjQ.$('#frmRequestMakeOffer_'+ self.opts.index),
						$frmEmail = pjQ.$('#frmSubmitEmail_'+ self.opts.index);
					$frmRequest.validate({
						
						errorPlacement: function (error, element) {
							if(element.parent().parent().hasClass('radio'))
							{
								error.insertAfter(element.parent().parent().parent());
							}else{
								error.insertAfter(element.parent());
							}
						},
						onkeyup: false,
						errorClass: "err",
						wrapper: "em",
						submitHandler: function (form) {
							self.disableButtons.call(self);
							pjQ.$.post([self.opts.folder, "index.php?controller=pjFront&action=pjActionSave"].join(""), $frmRequest.serialize()).done(function (data) {
								if(data.code != '100')
								{
									if(data.code == '200')
									{
										pjQ.$('#pjSpFootMessage_' + self.opts.index).html(data.message);
										self.$sectionMakeOffer.removeClass('sectionMakeOfferStepOne').addClass('sectionMakeOfferStepTwo');
										
										var timeoutValue = 5;
										setTimeout(function() {
											self.$sectionMakeOffer.addClass('sectionMakeOfferHidden');
										}, timeoutValue*1000);
									}else{
										pjQ.$('#pjSpMessage_' + self.opts.index).html(data.message);
										$frmRequest.hide();
										$frmEmail.show();
									}
								}
								self.enableButtons.call(self);
							}).fail(function () {
								self.enableButtons.call(self);
							});
							return false;
						}
					});
					
					$frmEmail.validate({
						
						errorPlacement: function (error, element) {
							error.insertAfter(element.parent());
						},
						onkeyup: false,
						errorClass: "err",
						wrapper: "em",
						submitHandler: function (form) {
							self.disableButtons.call(self);
							pjQ.$.post([self.opts.folder, "index.php?controller=pjFront&action=pjActionSaveEmail"].join(""), $frmEmail.serialize()).done(function (data) {
								if(data.code == '200')
								{
									var $message = pjQ.$('#pjSpFootMessage_' + self.opts.index);
									$message.html($message.attr('data-thank'));
									self.$sectionMakeOffer.removeClass('sectionMakeOfferStepOne').addClass('sectionMakeOfferStepTwo');
									
									var timeoutValue = 5;
									setTimeout(function() {
										self.$sectionMakeOffer.addClass('sectionMakeOfferHidden');
									}, timeoutValue*1000);
								}
								self.enableButtons.call(self);
							}).fail(function () {
								self.enableButtons.call(self);
							});
							return false;
						}
					});
				}
			}).fail(function () {
				self.enableButtons.call(self);
			});
		}
	};
	
	window.MakeOffer = MakeOffer;	
})(window);