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;
	};

	_OBooks.requestTrial = function(){
		var obtrialrequest = window.open(urls.requestTrial, "obtrialrequest", "width=800,height=600,top=50,left=50,menubar=0,status=0,titlebar=0,toolbar=0");
		// obtrialrequest.close();
	};

	_OBooks.countries = _OBooks.countries || [];

	var urls = {};
	var steps = [
		"step_terms",
		"step_requirement",
		"step_db",
		"step_license",
		"step_final",
		"step_installed"
	];
	var elems = {
		step_terms: null,
		step_requirement: null,
		step_db: null,
		step_license: null,
		step_final: null,
		step_installed: null
	};
	if (_OBooks.is_exe) {
		steps = [
			"step_terms",
			"step_license",
			"step_final",
			"step_installed"
		];
		elems = {
			step_terms: null,
			step_license: null,
			step_final: null,
			step_installed: null
		};
	}

	var currentStep = OBooks.step || 1;
	var totSteps = 6;

	var prevBtn = null;
	var nextBtn = null;
	var stepsDiv = null;
	var txtPassword = null;
	var txtEmail = null;
	var form2 = null;

	var _is = {
		get terms(){
			return currentStep == 1;
		},
		get requirements(){
			return currentStep == 2;
		},
		get db(){
			return currentStep == (steps.length-3);
		},
		get license(){
			return currentStep == (steps.length-2);
		},
		get final(){
			return currentStep == (steps.length-1);
		},
		get installed(){
			return currentStep == steps.length;
		}
	};

	var showFailAlert = function(message){
		if (!message) {
			return;
		}
		$(".ui.message").remove();
		var msg = $('<div class="ui negative message"><i class="close icon"></i><div class="header">' + message + '</div></div>');
		$(".close.icon", msg).click(function(){
			msg.remove();
		});
		msg.prependTo("body");
	};

	var showSuccessAlert = function(message){
		if (!message) {
			return;
		}
		$(".ui.message").remove();
		$('<div class="ui green message">' + message + '</div>').prependTo("body");
		setTimeout(function(){
			$(".ui.message").remove();
		}, 4000);
	};

	var updateVars = function(){

		urls.checkDb = _OBooks.site_url + "/setup/db_exist";
		urls.checkLicense = _OBooks.site_url + "/setup/check_license";
		urls.checkActivation = _OBooks.site_url + "/setup/check_activation";
		urls.activate = _OBooks.site_url + "/setup/activate";
		urls.install = _OBooks.site_url + "/setup/install";
		urls.states = _OBooks.site_url + "/setup/states/";
		urls.company = _OBooks.site_url + "/setup/company";

		urls.requestTrial = "http://app.outputbooks.com/register";

		prevBtn = $("#previous");
		nextBtn = $("#next");
		stepsDiv = $("#cursteps");

		elems.step_terms = $("#step_terms");
		elems.step_requirement = $("#step_requirement");
		elems.step_db = $("#step_db");
		elems.step_license = $("#step_license");
		elems.step_final = $("#step_final");
		elems.step_installed = $("#step_installed");
		elems.form_company = $("#form_company", elems.step_installed);
		elems.composition = $("#isCompositionScheme", elems.form_company);

		txtPassword = $("#password", elems.step_license);
		con_txtPassword = $("#con_password", elems.step_license);
		txtEmail = $("#email", elems.step_license);
		txtCompName = $("#company_name", elems.step_license);
		form2 = $("#form2 input", elems.step_license);
		form2.attr("disabled", "disabled");

		elems.country = $("#countryCode", elems.form_company);
		elems.state = $("#stateId", elems.form_company);

		elems.country.change(function(){
			var cCode = this.value;
			var country = $.grep(_OBooks.countries, function(itm){
				return itm.countryCode == cCode;
			});
			if (country && country[0])
			{
				country = country[0];

				$("#country", elems.form_company).val(country.countryName);
				$("#currency", elems.form_company).val(country.currencyCode);
			}

			getStates(cCode);
		});

		elems.state.change(function(){
			var sId = this.value;
			var state = $.grep(_OBooks.states, function(itm){
				return itm.id == sId;
			});
			if (state && state[0])
			{
				state = state[0];

				$("#stateName", elems.form_company).val(state.name);
				$("#stateCode", elems.form_company).val(state.stateCode);
			}
			else
			{
				$("#stateName", elems.form_company).val(sId);
				$("#stateCode", elems.form_company).val("");
				$("#stateId", elems.form_company).val("");
			}
		});
	};

	var _loader = function(isShow){
		if (isShow)
		{
			// disable btn
			prevBtn && prevBtn.attr("disabled", "disabled");
			nextBtn && nextBtn.attr("disabled", "disabled");
		}
		else
		{
			// enable btn
			prevBtn && prevBtn.removeAttr("disabled");
			nextBtn && nextBtn.removeAttr("disabled");
		}

		$("#loader")[isShow ? "show" : "hide" ]();
	};

	var licenseDetails = null;
	var postData = {
		db: {},
		sysinfo: "",
		license_key: ""
	};

	var processDbForm = function(){
		var dbData = $("#form_db").serializeObject();
		if (!dbData.hostname || !dbData.username || !dbData.database)
		{
			alert("Required Field Missing");
			return false;
		}

		$.post(urls.checkDb, {
			db: dbData
		}, function(resp){
			if (!resp) {
				return false;
			}

			if (resp[0]) {
				if (resp[2] && !resp[2].sysinfo) {
					showFailAlert("Unique ID missing");
					return;
				}

				showSuccessAlert(resp[1]);

				postData.db = dbData;
				postData.sysinfo = resp[2].sysinfo;

				currentStep++;
				updateSteps();
			} else {
				showFailAlert(resp[1]);
			}
		}, "json");
	};

	var processLicenseForm = function(licenseKey){
		// licenseKey = $("#licenseKey").val();

		if (!licenseKey) {
			alert("Licensekey Missing");
			return false;
		}

		$.post(urls.checkLicense, {
			license_key: licenseKey
		}, function(resp){
			if (!resp) {
				return false;
			}

			if (resp[0]) {
				showSuccessAlert(resp[1]);
				licenseDetails = resp[2].license_detail;

				if (licenseDetails.isExpired)
				{
					alert("License key expired");
					licenseDetails = null;
					return false;
				}

				postData.license_key = licenseKey;
				postData.actKey = "";

				$("#actKey").val("");

				if (licenseDetails && (licenseDetails.isTrial || licenseDetails.isDemo)) {
					postData.isActive = true;
					// $(".field.reqkey, .field.actkey").hide();
					$("#lic-active, #lic-notActive").hide();
				} else {
					postData.isActive = false;
					// $(".field.reqkey, .field.actkey").show();
					$("#lic-active").hide();
					$("#lic-notActive").show();
				}

				if (licenseDetails && licenseDetails.data) {
					form2.removeAttr("disabled");
					licenseDetails.data.email && txtEmail.val(licenseDetails.data.email);
					if (licenseDetails.data.comp)
					{
						var compNames = [];
						$.each(licenseDetails.data.comp, function(id, name){
							compNames.push(name);
						});
						compNames = compNames.join("<br>");
						txtCompName.html(compNames);
					}
					// txtEmail.text(licenseDetails.data.email);
				}
			} else {
				showFailAlert(resp[1]);
			}
		}, "json");
	};

	var actModel = $("#appActivationModel");

	var activateLicenseKey = function(){
		if (!postData || !postData.license_key)
		{
			alert("Licensekey Missing");
			return false;
		}

		if (postData.isActive && postData.actKey) {
			return;
		}

		$.post(urls.activate, {
			license_key: postData.license_key
		}, function(resp){
			if (!resp) {
				return false;
			}

			if (resp[0]) {
				showSuccessAlert(resp[1]);

				if (resp[2] && resp[2].isActive && resp[2].actKey) {
					postData.actKey = resp[2].actKey;
					postData.isActive = true;

					$("#lic-active").show();
					$("#lic-notActive").hide();
				}
			} else {
				showFailAlert(resp[1]);
			}

			if (resp[2] && resp[2].reqKey && resp[2].actUrl) {
				$("#actUrl", actModel).attr("href", resp[2].actUrl).text(resp[2].actUrl);
				$("#reqKey", actModel).val(resp[2].reqKey);
				actModel.modal('show');
			}
		}, "json");
	};

	var processActivationForm = function(actKey){

		if (!postData.license_key) {
			alert("Licensekey Missing");
			return false;
		}

		if (postData.isActive) {
			return;
		}

		if (!actKey) {
			alert("Activationkey Missing");
			return false;
		}

		$.post(urls.checkActivation, {
			license_key: postData.license_key,
			actKey: actKey
		}, function(resp){
			if (!resp) {
				return false;
			}

			if (resp[0]) {
				showSuccessAlert(resp[1]);

				if (resp[2] && resp[2].isActive) {
					postData.actKey = actKey;
					postData.isActive = true;

					actModel.modal('hide');

					$("#lic-active").show();
					$("#lic-notActive").hide();
				}
			} else {
				showFailAlert(resp[1]);
			}
		}, "json");
	};

	var getStates = function(countryCode){
		if (countryCode != "IN") {
			$("div#composition, div#pan").hide();
			$("div#gstin label").text("Tax No");
			$("input#gstin").attr("placeholder", "Tax No")
		} else {
			$("div#composition, div#pan").show();
			$("#gstin label").text("GSTIN");
			$("input#gstin").attr("placeholder", "GSTIN")
		}

		$.get(urls.states + countryCode, function(resp){
			if (!resp) {
				_OBooks.states = [];
				updateStates();
				return false;
			}

			if (resp[0] == true && resp[2] && resp[2].states)
			{
				var states = resp[2].states;
				_OBooks.states = states;
				updateStates();
			}
			else
			{
				alert("Error while getting states list.");
			}
		}, "json");
	}

	var install = function(){
		_loader(true);

		$.post(urls.install, postData, function(resp){
			_loader(false);

			if (!resp) {
				return false;
			}

			if (resp[0] == true)
			{
				if (resp[2] && resp[2].countries)
				{
					_OBooks.countries = resp[2].countries;
					updateCountries();
				}

				window.location.reload();

				currentStep++;
				updateSteps();
			}
			else
			{
				showFailAlert(resp[1]);
			}
		}, "json");
	};

	var updateCountries = function(){
		if (!_OBooks.countries || _OBooks.countries.length <= 0) {
			return false;
		}

		$.each(_OBooks.countries, function(key, val){
			var option = $("<option/>");
			option.attr("value", val.countryCode);
			option.text(val.countryName);
			option.appendTo(elems.country);
		});

		elems.country.val("IN");
		elems.country.dropdown("set selected", "IN");
		getStates("IN");
	};

	var updateStates =  function(){
		// if (!_OBooks.states || _OBooks.states.length <= 0)
		// {
			elems.state.empty();
		if (!_OBooks.states || _OBooks.states.length <= 0)
		{
			elems.state.val("");
			$("#stateId").parent().hide();
			$("#stateName").show();
			elems.state.dropdown({allowAdditions: true});
			return false;
		} else {
			$("#stateId").parent().show();
			$("#stateName").hide();
		}

		elems.state.empty();
		elems.state.val("");

		$.each(_OBooks.states, function(key, val){
			var option = $("<option/>");
			option.attr("value", val.id);
			option.text(val.name);
			option.appendTo(elems.state);
		});

		// elems.state.val("35");
		// elems.state.dropdown("set selected", "35");
	};

	var updateCompanyDetails = function(){
		var postData = elems.form_company.serializeObject();

		if (!postData.stateId && !postData.stateName)
		{
			alert("State Required");
			return;
		}

		postData.isCompositionScheme = elems.composition.prop("checked") ? 1 : 0;
		_loader(true);
		$.post(urls.company, postData, function(resp){
			if (!resp || !resp[0])
			{
				if (resp[1])
				{
					console.log(resp[1]);
				}
				_loader(false);
				return false;
			}

			var resp = resp[2];
			// window.location.href = window.location.href.replace(/index\.php.*/ig, "index.php");
			// window.location.reload();
			console.log(window.location.href);
			setTimeout( () => {window.location.reload();_loader(false);},3000);
		}, "json");
	};

	var updateDetails = function(){
		var licTypes = {T: "Trial", F: "Free", P:"Basic", S:"Standard", E:"Enterprise", D:"Demo"};
		var companies = [];

		if (licenseDetails.data && licenseDetails.data.comp)
		{
			companies = licenseDetails.data.comp;
		}
		/*
		for (var i=0, iLen = licenseDetails.companies.length; i<iLen; i++)
		{
			companies.push(licenseDetails.companies[i][1]);
		}
		*/
		companies = companies.join("<br>");

		var finalStep = $("#step_final");
		$("#db_hostname", finalStep).text(postData.db.hostname);
		$("#db_username", finalStep).text(postData.db.username);
		$("#db_database", finalStep).text(postData.db.database);
		$("#license_key", finalStep).text(postData.license_key);
		$("#companies", finalStep).html(companies);
		$("#email", finalStep).html(licenseDetails.data.email);
		$("#expiredOnF", finalStep).text(licenseDetails.expiredOnF);
		$("#licType", finalStep).text(licenseDetails.plan + " - " + licTypes[licenseDetails.plan]);
	};

	var updateSteps = function(){
		prevBtn.removeAttr("disabled");
		prevBtn.show();
		nextBtn.removeAttr("disabled");

		if (currentStep <= 1)
		{
			currentStep = 1;
			prevBtn.attr("disabled", "disabled");
			prevBtn.hide();
			nextBtn.text("I Accept");
		}
		else
		{
			nextBtn.text("Next");
		}

		if (currentStep > steps.length)
		{
			currentStep = steps.length;
			nextBtn.attr("disabled", "disabled");
		}

		for (var i=0,iLen=steps.length; i<iLen; i++)
		{
			elems[steps[i]].hide();
		}

		elems[steps[currentStep-1]].show();

		if (steps[currentStep-1] == steps[1] && _OBooks.isDependent) {
			nextBtn.attr("disabled", "disabled");
		}

		stepsDiv.text(currentStep + " / " + (steps.length));
		$(".ui.modal .content").scrollTop(0);

		if (_is.license) {
			$("#sysinfo").val(postData.sysinfo);
		}

		if (_is.final)
		{
			updateDetails();
			nextBtn.text("Install");
		}

		if (_is.installed)
		{
			nextBtn.text("Finish");
		}

		// localStorage.setItem("currentStep", currentStep);
	};

	var setLicenseKey = function(){
		if (OBooks.licFile)
		{
			if (OBooks.licFile.licenseKey)
			{
				$("#step_license #licenseKey").val(OBooks.licFile.licenseKey);
				processLicenseForm(OBooks.licFile.licenseKey);
			}
			if (OBooks.licFile.email)
			{
				txtEmail.val(OBooks.licFile.email);
			}
		}
	}
	$(document).ready(function(){
		currentStep = OBooks.step || 1;

		_loader(false);

		// currentStep = localStorage.getItem("currentStep") || 1;

		updateVars();
		updateSteps();

		if (OBooks.companies && OBooks.companies.length > 0)
		{
			var _company = OBooks.companies[0];
			$("#id", elems.form_company).val(_company.id);
			$("#name", elems.form_company).val(_company.name);
		}

		elems.country.dropdown({
			transition: "fade up",
			direction: "auto",
			showOnFocus: false,
			match: "text",
			selectFirstResult: false,
			selectOnKeydown: false,
			fullTextSearch: false,
			placeholder: "Select Country.."
		});
		elems.state.dropdown();

		updateCountries();

		prevBtn.click(function(){
			currentStep--;
			updateSteps();
		});

		nextBtn.click(function(ev){
			ev.preventDefault();
			ev.stopPropagation();

			if (!_OBooks.is_exe && _is.db)
			{
				processDbForm();
				setLicenseKey();
				return;
			}
			else if (_is.db)
			{
				setLicenseKey();
			}

			if (_is.license)
			{
				if (!postData.license_key || !licenseDetails || !licenseDetails.data)
				{
					alert("License key issue");
					return;
				}

				if (licenseDetails.isExpired)
				{
					alert("License key expired");
					return;
				}

				if (!txtPassword.val())
				{
					alert("Password field is required");
					return;
				}
				if (txtPassword.val()!=con_txtPassword.val())
				{
					alert("You must confirm your password");
					return;
				}

				if (!licenseDetails.isTrial && !postData.isActive)
				{
					alert("Please activate the device by activation link.");
					return;
				}

				postData.email = txtEmail.val();
				licenseDetails.data.email = txtEmail.val();
				postData.password = txtPassword.val();
				licenseDetails.data.password = txtPassword.val();
			}

			if (_is.final)
			{
				if (
					!postData.license_key ||
					!licenseDetails ||
					!licenseDetails.data ||
					!licenseDetails.data.email ||
					!licenseDetails.data.password
				) {
					return;
				}

// currentStep++;
// updateSteps();

				install();
				return;
			}

			if (_is.installed)
			{
				updateCompanyDetails();
				return false;
			}

			currentStep++;
			updateSteps();
		});
		
		$("#step_license #licenseKey").change(function(){
			processLicenseForm(this.value);
		});

		// activate license key
		$("#lic-notActive > a").click(function(){
			activateLicenseKey();
		});

		var popupParams = {
			allowMultiple: true,
			autofocus: true,
			closable: false,
			observeChanges: true
		};

		actModel = $("#appActivationModel");
		actModel.modal(popupParams);
		$("#activate-btn", actModel).click(function(){
			processActivationForm($("#actKey", actModel).val());
		});
		$(".actions.close").click(function(){
			actModel.modal("hide");
		});

/*
		$("#step_license #actKey").change(function(){
			processActivationForm(this.value);
		});
*/
	});

})(jQuery, window, document, window.OBooks);

