toastr.options = {
	"closeButton": false,
	"debug": false,
	"newestOnTop": false,
	"progressBar": false,
	"positionClass": "toast-top-right",
	"preventDuplicates": false,
	"onclick": null,
	"showDuration": "300",
	"hideDuration": "1000",
	"timeOut": "1500",
	"extendedTimeOut": "1000",
	"showEasing": "swing",
	"hideEasing": "linear",
	"showMethod": "fadeIn",
	"hideMethod": "fadeOut"
}

$.fn.serializeObject = function () {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function () {
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

$.fn.toast = function (message, showForSeconds) {
	var me = this;
	$(me).html(message);
	var x = $(me).show(200);
	if (showForSeconds) {
		x.delay(showForSeconds).fadeOut(0);
	}
}

var doPost = function (url, data, callback) {
	$.ajax({
		type: 'POST',
		url: url,
		data: data,
		dataType: 'json',
		success: function (x) {
			callback(x);
		}
	});
}

var redirTo = function (link) {
	reloadPage(link);
}

var getFormData = function (form) {
	return $(form).serializeObject();
}

var simpleSubmit = function (url, form, callback) {

	var data = getFormData(form);

	// leave this in case
	// data.data = JSON.stringify(data);

	console.log("DATA TO: " + url, data);
	doPost(url, data, function (response) {
		console.log("RESPONSE FROM: " + url);
		console.log(JSON.stringify(response));
		if (callback) {
			callback(response);
		} else {
			if (response.success) {
				location.reload();
			} else {
				toastr.error(response.message);
			}
		}
	});

}

var simpleDataSubmit = function (url, data, callback) {
	doPost(url, data, function (response) {
		if (callback) {
			callback(response);
		} else {
			if (response.success) {
				location.reload();
			} else {
				toastr.error(response.message);
			}
		}
	});
}

var reloadPage = function (url, successMsg) {
	var url = url || window.location.href;
	$.get(window.location.href, function (data, status) {
		if (status == 'success') {
			var bodyHtml = /<body.*?>([\s\S]*)<\/body>/.exec(data)[1];
			$('body').html(bodyHtml);
			$('body').removeClass('modal-open');
			$('body').removeAttr('style')
			if (successMsg && successMsg.length > 0) {
				toastr.info(successMsg);
			}
		}
	})
}

var redirTo = function (url, successMsg) {
	reloadPage(url);
}

var refresh = function (successMsg) {
	reloadPage(null, successMsg);
}

var removeLocalStorageKeys = function (form) {
	var lsKey = $(form).attr('ls-key');
	var lsKeys = lsKey ? lsKey.split(',') : [];
	for (var i = 0; i < lsKeys.length; i++) {
		console.log("Removing " + lsKeys[i]);
		window.localStorage.removeItem(lsKeys[i]);
	}
}

var setupMoes = function () {
	$('div[moe]').each(function () {
		var moe = this;
		var start = $(moe).find('a[start]');
		var cancel = $(moe).find('[cancel]');
		var submit = $(moe).find('[submit]');

		var form = $(moe).find('[form]');
		form = form ? form[0] : null;
		form = form ? form : $(moe).find('form');

		var url = $(form).attr('url');
		var successMsg = $(form).attr('success-msg');
		var redir = $(form).attr('redir');

		var info = $(moe).find('[info]');
		info = info ? info[0] : null;

		var isStartShowing = $(start).css('display') != 'none';
		var isFormShowing = $(form).css('display') != 'none';
		var isInfoShowing = info ? $(info).css('display') != 'none' : null;

		var toggleStart = function (e) {
			e.preventDefault();
			if ($(start).attr('show') != undefined) {
				return;
			}
			$(start).toggle();
		};

		var toggleForm = function (e) {
			e.preventDefault();
			if ($(form).attr('show') != undefined) {
				return;
			}
			if (isFormShowing) {
				$(form).hide();
			} else {
				$(form).css('display', 'block');
			}
			isFormShowing = !isFormShowing;
			// $(form).toggle(50);removeLocalStorageKeys(form)
		};

		var toggleInfo = function (e) {
			e.preventDefault();
			if (!info) {
				return;
			}
			if ($(info).attr('show') != undefined) {
				return;
			}
			if (isInfoShowing) {
				$(info).hide();
			} else {
				$(info).css('display', 'block');
			}
			isInfoShowing = !isInfoShowing;
			// $(info).toggle(50);
		};

		var toggleFormAndInfo = function (e) {
			e.preventDefault();
			toggleStart(e);
			toggleForm(e);
			toggleInfo(e);
		}

		$(start).click(toggleFormAndInfo);
		$(cancel).click(toggleFormAndInfo);

		//clear localStrage for the form after cancel

		var cancelMoe = function (e) {
			var frm = $(this).closest('form');
			removeLocalStorageKeys(frm);
		}
		$(moe).off('click', '[cancel]', cancelMoe);
		$(moe).on('click', '[cancel]', cancelMoe)

		$(form).find('[show-if-field]').each(function () {
			var me = this;
			var showIfField = $(me).attr('show-if-field');

			var showIfValue = $(me).attr('show-if-value');

			var showIfFieldEl = $(form).find('[name=' + showIfField + ']');

			var adjust = function () {
				var value = $(showIfFieldEl).val();
				if (value == showIfValue) {
					$(me).show();
				} else {
					$(me).hide();
				}
			}
			$(showIfFieldEl).change(adjust);
			adjust();
		});


		$(moe).off('click', '[submit]');
		var submitHtml = $(submit).html();
		$(moe).on('click', '[submit]', function (e) {
			e.preventDefault();
			$(submit).html('<i class="fa fa-spinner fa-spin"></i> ' + submitHtml);
			$(submit).prop('disabled', true);
			simpleSubmit(url, form, function (response) {
				console.log("RESPONSE", response, "REDIR", redir);

				if (response.success) {
					removeLocalStorageKeys(form);
					if (redir) {
						redirTo(redir + response.data);
					} else {
						refresh(successMsg);
					}
				} else {
					$(submit).html(submitHtml);
					$(submit).prop('disabled', false);
					toastr.error(response.message);
				}
			});
		});

	});
};

$(document).ready(function () {
	setupMoes();
});

$(document).on('setupMoes', function () {
	setTimeout(function () {
		setupMoes();
	}, 1000)
})

$(document).ready(function () {
	$('[dateRanger]').each(function () {
		var dr = $(this);
		var rangeTypeSelect = dr.find('select')[0];
		var date1Input = dr.find('[date1]')[0];
		var date2Input = dr.find('[date2]')[0];
		var d1Val = '';
		var d2Val = '';
		var d1 = function (enable) {
			if (enable) {
				var hasVal = $(date1Input).val();
				if (!hasVal) {
					$(date1Input).val(d1Val);
				}
				$(date1Input).show();
			} else {
				d1Val = $(date1Input).val();
				$(date1Input).val('');
				$(date1Input).hide();
			}
		};
		var d2 = function (enable) {
			if (enable) {
				var hasVal = $(date2Input).val();
				if (!hasVal) {
					$(date2Input).val(d2Val);
				}
				$(date2Input).show();
			} else {
				d2Val = $(date2Input).val();
				$(date2Input).val('');
				$(date2Input).hide();
			}
		};
		var adjustFields = function () {
			var rangeType = $(rangeTypeSelect).val();
			if (rangeType == 'all') {
				d1();
				d2();
			} else if (rangeType == 'on-or-before') {
				d1(true);
				d2();
			} else if (rangeType == 'on-or-after') {
				d1(true);
				d2();
			} else if (rangeType == 'between') {
				d1(true);
				d2(true);
			} else if (rangeType == 'on') {
				d1(true);
				d2();
			} else if (rangeType == 'not-on') {
				d1(true);
				d2();
			} else if (rangeType == 'not-in-between') {
				d1(true);
				d2(true);
			}
		};
		adjustFields();
		$(rangeTypeSelect).change(function () {
			adjustFields();
		});
	});
	$('[numRanger]').each(function () {
		var nr = $(this);
		var rangeTypeSelect = nr.find('select')[0];
		var num1Input = nr.find('[num1]')[0];
		var num2Input = nr.find('[num2]')[0];
		var n1 = function (enable) {
			if (enable) {
				$(num1Input).show();
			} else {
				$(num1Input).hide();
			}
		};
		var n2 = function (enable) {
			if (enable) {
				$(num2Input).show();
			} else {
				$(num2Input).hide();
			}
		};
		var adjustFields = function () {
			var rangeType = $(rangeTypeSelect).val();
			if (rangeType == 'all') {
				n1();
				n2();
			} else if (rangeType == 'less-than') {
				n1(true);
				n2();
			} else if (rangeType == 'greater-than') {
				n1(true);
				n2();
			} else if (rangeType == 'equal-to') {
				n1(true);
				n2();
			} else if (rangeType == 'between') {
				n1(true);
				n2(true);
			} else if (rangeType == 'not-equal-to') {
				n1(true);
				n2();
			} else if (rangeType == 'not-in-between') {
				n1(true);
				n2(true);
			}
		};
		adjustFields('all');
		$(rangeTypeSelect).change(function () {
			adjustFields();
		});
	});
});


//============MOE_MODAL======================================

$.fn.serializeObject = function () {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function () {
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

$.fn.toast = function (message, showForSeconds) {
	var me = this;
	$(me).html(message);
	var x = $(me).show(200);
	if (showForSeconds) {
		x.delay(showForSeconds).fadeOut(0);
	}
}

var doPost = function (url, data, callback) {
	$.ajax({
		type: 'POST',
		url: url,
		data: data,
		dataType: 'json',
		success: function (x) {
			callback(x);
		}
	});
}

var redirTo = function (link) {
	window.location.href = link;
}

var getFormData = function (form) {
	return $(form).serializeObject();
}

var simpleSubmit = function (url, form, callback) {

	var data = getFormData(form);

	// leave this in case
	// data.data = JSON.stringify(data);

	console.log("DATA TO: " + url, data);
	doPost(url, data, function (response) {
		console.log("RESPONSE FROM: " + url);
		console.log(JSON.stringify(response));
		if (callback) {
			callback(response);
		} else {
			if (response.success) {
				location.reload();
			} else {
				toastr.error(response.message);
			}
		}
	});

}

var simpleDataSubmit = function (url, data, callback) {
	doPost(url, data, function (response) {
		console.log(url, data, response);
		if (callback) {
			callback(response);
		} else {
			if (response.success) {
				location.reload();
			} else {
				toastr.error(response.message);
			}
		}
	});
}

var redirTo = function (url) {
	window.location.href = url;
}


var removeLocalStorageKeys = function (form) {
	var lsKey = $(form).attr('ls-key');
	var lsKeys = lsKey ? lsKey.split(',') : [];
	for (var i = 0; i < lsKeys.length; i++) {
		console.log("Removing " + lsKeys[i]);
		window.localStorage.removeItem(lsKeys[i]);
	}
}

$(document).ready(function () {
	$('[moe-toggle]').each(function () {
		var me = this;
		var start = $(me).find('[toggle-start]');
		var toggle = $(me).find('[toggle]');
		$(start).on('click', function (e) {
			$(toggle).toggle();
		});
	});
});

$(document).ready(function () {
	initMoeModal();
});

function initMoeModal(_outer) {
	$((_outer ? _outer + ' ' : '') + '[moe-modal]').each(function () {

		var me = this;
		var start = $(me).find('[start]');
		var form = $(me).find('form');
		var modal = $(me).find('.modal');

		var submit = $(form).find('[submit]');
		var cancel = $(form).find('[cancel]');

		var url = $(form).attr('url');
		var successMsg = $(form).attr('success-msg');
		var redir = $(form).attr('redir');

		var showModal = function () {
			$(modal).modal({
				show: true,
				keyboard: false,
				backdrop: 'static'
			});
			isModalOn = true;
		}

		var hideModal = function () {
			$(modal).modal('hide');
			isModalOn = false;
		}

		$(start).on('click', function (e) {
			e.preventDefault();
			showModal();
		});

		$(cancel).on('click', function (e) {
			e.preventDefault();
			hideModal();

			// if in notes-panel, close panel
			if($(this).closest('.notes-panel-body').length) {
				window.top.notesPanel.cancel();
			}

		});

		$(document).on('keyup', function (e) {
			if (e.keyCode == 27) { // ESC
				hideModal();
			}
		});

		$(form).attr('action', url);
		$(form).attr('method', 'POST');
		$(form).attr('enctype', 'form-data/multipart');

		var submitHtml = $(submit).html();
		$(form).ajaxForm({
			beforeSubmit: function () {
				$(submit).html('<i class="fa fa-spinner fa-spin"></i> ' + submitHtml);
				$(submit).prop('disabled', true);
			},
			success: function (response) {
				console.log(response);
				if (response.success) {

					if($(submit).closest('.notes-panel-body').length) {
						window.top.clearInterval(window.top.notesPanel.saveTimer[$(form).find('[name="persistenceKey"]').val()]);
						localStorage.removeItem('notesPanel_' + $(form).find('[name="persistenceKey"]').val());
						localStorage.removeItem('notesPanel_expanded_' + $(form).find('[name="clientID"]').val());
						window.top.location.reload();
						return false;
					}

					//lsKeys are comma separated
					removeLocalStorageKeys(form)

					if (redir) {
						redirTo(redir + response.data);
					} else {
						refresh(successMsg);
					}
				} else {
					$(submit).html(submitHtml);
					$(submit).prop('disabled', false);
					alert(response.message);
				}
			},
			error:function(){
				$(submit).html(submitHtml);
				$(submit).prop('disabled', false);
				alert("HTTP Error: see console log for details");
			}
		});

	});
}

$(document).ready(function () {
	$('[ajaxForm]').ajaxForm(function (response, status, xhr, form) {
		console.log("Response ", response);

		if (!response.success) {
			toastr.error(response.message);
			return;
		}
		removeLocalStorageKeys(form)
		reloadPage();
	});
});


var initInlineMoe = function () {
	var showForm = function (el) {
		$(el).closest('[inline-moe]').find('[info]').hide();
		$(el).closest('[inline-moe]').find('form').show();
	}

	var hideForm = function (el) {
		$(el).closest('[inline-moe]').find('[info]').show();
		$(el).closest('[inline-moe]').find('form').hide();
		$(el).closest('[inline-moe]').find('form .error').remove();
	}

	var reloadElement = function (reloadUrl, targetElem) {
		console.log("Reloading elem ", $(targetElem), " from " + reloadUrl);
		$(targetElem).load(reloadUrl, function () {
			initInlineMoe();
		});
	}

	$('body').off('click', '[inline-moe] [start]')
	$('body').on('click', '[inline-moe] [start]', function (e) {
		e.preventDefault();
		showForm(this);
	})

	$('body').off('click', '[inline-moe] [submit]');
	$('body').on('click', '[inline-moe] [submit]', function (e) {
		e.preventDefault();
		//submit the form and replace reload-target-class with content from reload-url
		var form = $(this).closest('form');
		var submit = this;
		var submitHtml = $(submit).html();
		$(form).ajaxSubmit({
			beforeSubmit: function () {
				$(submit).html('<i class="fa fa-spinner fa-spin"></i> ' + submitHtml);
				$(submit).prop('disabled', true);
			},
			success: function (response) {

				if (response.success) {
					var reloadTargetClass = $(form).closest('[inline-moe]').attr('reload-target-class');
					var targetElement = $(form).closest('.' + reloadTargetClass);
					var reloadUrl = $(form).closest('[inline-moe]').attr('reload-url');
					reloadElement(reloadUrl, targetElement);
				} else {
					$(submit).html(submitHtml);
					$(submit).prop('disabled', false);
					$(form).prepend('<span class="error" style="color:red;">' + "Error" + '</span>');
				}
			},
			error:function(){
				$(submit).html(submitHtml);
				$(submit).prop('disabled', false);
				alert("HTTP Error: see console log for details");
			}
		});
	})

	$('body').off('click', '[inline-moe] [cancel]');
	$('body').on('click', '[inline-moe] [cancel]', function (e) {
		e.preventDefault();
		hideForm(this);
	})
}

$(document).ready(function () {
	setTimeout(function () {
		initInlineMoe();
	}, 500)
})

$(document).ready(function () {
	$(document).off('click', '#callLink')
	$(document).on('click', '#callLink', function (evt) {
		evt.preventDefault();
		var url = $(this).attr('href');
		var iid = $(this).attr('data-id');
		var custPhone = $('#customPhoneNumber').val();

		var data = {iid: iid};
		if (custPhone) {
			data['customPhoneNumber'] = custPhone;
		}
		$.post(url, data, function (respData) {
			respData = JSON.parse(resp);
			if (!respData.success) {
				alert(respData.message);
			}
		});
	});
});


(function () {
	//make sure the dom gets updated on change for inputs
	$('.page-fields-container').on('keyup', 'input', function () {
		$(this).attr("value", $(this).val());
	});


	//update
	$("#update").on('click', function () {
		var btn = $(this);

		//set text area value 
		$('.page-fields-container textarea').each(function () {
			$(this).text($(this).val());
		});

		$('.page-fields-container input[type=radio]').each(function () {
			if ($(this).prop("checked")) {
				$(this).attr('checked', true);
			}
		});

		$('.page-fields-container input[type=checkbox]').each(function () {
			if ($(this).prop("checked")) {
				$(this).attr('checked', true);
			}
		});

		$('.page-fields-container input[type=checkbox]').each(function () {
			if ($(this).prop("checked")) {
				$(this).attr('checked', true);
			}
		});

		$('.page-fields-container select option:selected').each(function () {
			$(this).attr('selected', true);
		});

		var fieldData = {};

		//simple for now to get only input fields
		$(btn).closest('.page-container').find('.page-fields-container').find('input').each(function (i, el) {
			fieldData[$(el).attr('name')] = $(el).val();
		});

		$(btn).closest('.page-container').find('.page-fields-container').find('select').each(function (i, el) {
			fieldData[$(el).attr('name')] = $(el).val();
		});

		var clientID = $(this).closest(".page-container").attr('client-id');
		var pageID = $(this).closest(".page-container").attr('page-id');
		var programID = $(this).closest(".page-container").attr('program-id');
		var markup = $(btn).closest('.page-container').find('.page-fields-container').html();

		var submitUrl = "";
		if (pageID) {
			submitUrl = "/api/page/submit";
		} else {
			submitUrl = "/api/page/addDirect";
		}


		$.post(submitUrl, {
			clientID: clientID,
			pageID: pageID,
			programID: programID,
			submittedMarkupContent: markup,
			submittedJson: JSON.stringify(fieldData)
		}, function (result) {
			console.log("Result", result);
			reloadPage(window.location.pathname);
			if (result.success) {
				alert("Form submitted successfully");
			} else {
				alert(result.message);
			}
		});
	});

	$("#refresh").on(
			'click',
			function () {
				var btn = $(this);
				var pageID = $(this).closest(".page-container")
						.attr('page-id');
				$.post("/api/page/refresh", {
					pageID: pageID
				}, function (result) {
					console.log("Result", result);
					if (result.success) {
						var resultMarkup = result.message;
						$(btn).closest('.page-container').find('.page-fields-container').html(resultMarkup);
					} else {
						alert(result.message);
					}
				});
			});

})();







