window.OBooks = window.OBooks || {};

(function ($, window, document, _OBooks, undefined) {
	$.fn.serializeObject = function() {
		var o = {};
		var a = this.serializeArray();
		$.each(a, function() {
			if (o[this.name])
			{
				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;
	};

	$(document).ready(function(){
		var currency = $("#currency");
		var country = $("#country");

		var countryCode = $("#countryCode");
		// countryCode.dropdown();
		countryCode.change(function(){
			currency.val(countryCode.find(":selected").attr("currencycode"));
			// console.log(countryCode.find(":selected").text());
			country.val(countryCode.find(":selected").text());
		});
		countryCode.val("IN");
		// countryCode.dropdown("set selected", "IN");
		countryCode.trigger("change");

		var stateId = $("#stateId");
		var stateCode = $("#stateCode");
		var stateName = $("#stateName");
		stateId.change(function(){
			stateId.find(":selected").attr("value");
			stateName.val(stateId.find(":selected").text());
			stateCode.val(stateId.find(":selected").attr("stateCode"));
		});
		stateId.val(35);
		stateId.trigger("change");
		// stateId.dropdown({allowAdditions: true});

		var tenantName = $("#tenantName");
		tenantName.keypress(function(e){
		// console.log(e.charCode, e.which);
			if (!(/^[a-zA-Z0-9\-]+$/ig).test(String.fromCharCode(e.charCode ? e.charCode : e.which))) {
				e.preventDefault();
			}
		});
		tenantName.change(function(){
			tenantName.val(tenantName.val().toLowerCase().trim().replace(/(\s)/ig, "-"));
		});

		var isRunning = false;
		$("#install").click(function(e){
			if (isRunning)
			{
				return false;
			}

			var data = $("#form_company").serializeObject();

			console.log("Form : ", data);

			var reQuired = [
				{ key: "tenantName", msg: "Tenant Name Required." },
				{ key: "email", msg: "Email Required." },
				{ key: "password", msg: "Password Required." },
				{ key: "country", msg: "Country Required." }
			];

			var error = "";
			$.each(reQuired, function(key, val){
				if (!data[val.key])
				{
					error += val.msg + "\n";
				}
			});

			if (error) {
				alert(error);
				return false;
			}

			isRunning = true;
			$("#install").toggleClass("loading");
			$.post(OBooks.site_url + "/setup/install", data, function(resp){
				isRunning = false;
				console.log("resp : ", resp);
				if (resp && (!e || !e.ctrlKey))
				{
					window.location.reload();
				}
			});
		});
	});
})(jQuery, window, document, window.OBooks);

