(function () {
	'use strict';

	angular
		.module("app")
		.controller("SubscribeController", SubscribeController);

	SubscribeController.$inject = ["$rootScope", "$scope", "$http"];

	function SubscribeController($rootScope, $scope, $http) {
		var vm = this;
		var langIso = '';
		vm.mediaFilename = {};
		vm.showLoading = false;
		vm.formData = {};
		vm.step = 1;
		vm.errorMessage = null;

		var waitIntgrtn = setInterval(function () {
			if (!window.intgrtn) {
				return false;
			}
			clearInterval(waitIntgrtn);

			if (window.intgrtn.lookup("redirectReturningLead", true, "auto") == "auto" && window.intgrtn.lookup("signupRequestID", true)) {
				window.intgrtn.goToBrokerLoginUrlBySignupRequestID(window.intgrtn.lookup("signupRequestID", true));
			}

			window.intgrtn.events.on("form.signup.success", function (form, response) {
				//window.intgrtn.store("signupRequestID", response.data.signupRequestID, 2);
				window.intgrtn.store("signupRequestID", response.details.leadRequest.ID, 2);
				var loader = $(".js-intgrtn-modal-loader").hide();
				var countdownSelectorWrapper = $('.js-intgrtn-countdown-wrapper').hide();

				var timeLeft = 5;

				$('.modal').modal({
					backdrop: 'static',
					keyboard: false
				});
				vm.brokersName = response.details.advertiser.name;
				vm.brokersImageUrl = response.details.advertiser.logo;
				$scope.$applyAsync();

				if (window.intgrtn.lookup("signupRequestID")) {
					countdownSelectorWrapper.show();
					var downloadTimer = setInterval(function () {
						if (timeLeft <= 0) {
							clearInterval(downloadTimer);
						}
						$('.js-intgrtn-countdown').text(timeLeft);
						timeLeft -= 1;
					}, 1000);

					setTimeout(function () {
						window.intgrtn.goToBrokerLoginUrlBySignupRequestID(window.intgrtn.lookup("signupRequestID"));
					}, 6000);

					$('.js-intgrtn-go-to-broker-site').on("click", function () {
						$(this).hide();
						loader.show();
						countdownSelectorWrapper.hide();
						window.intgrtn.goToBrokerLoginUrlBySignupRequestID(window.intgrtn.lookup("signupRequestID"));
					});
				} else {
					$(".modal-signup").modal('hide');
					loader.hide();
				}
			});

			vm.getData();
			$scope.$applyAsync();
		}, 10);

		function applyTranslations(translations, additionalClass) {
			$("[data-i18n]").each(function () {
				var t = $(this).attr("data-i18n");
				switch ($(this).prop("tagName")) {
					case"INPUT":
						t || (t = $(this).attr("placeholder"));
						$(this).attr("placeholder", translations[t]);
						break;
					default:
						t || (t = $(this).text()), $(this).text(translations[t]);
						if (typeof additionalClass !== 'undefined' && additionalClass !== null) {
							$(this).addClass(additionalClass);
						}
				}
			})
		}

		vm.getData = function () {
			if (window.intgrtn) {
				window.intgrtn.getCurrentLocation(function (response) {
					if (response.data && response.data.countryIsoCode && response.data.country) {
						var currentIso = window.intgrtn.lookup('language', true, response.data.countryIsoCode.toLowerCase());

						switch (currentIso) {
							case "mx":
							case "cl":
							case "co":
							case "ar":
							case "uy":
							case "cr":
							case "ec":
							case "pa":
							case "pe":
							case "ve":
								currentIso = "es";
								break;
							case "kw":
							case "om":
							case "bh":
							case "ae":
							case "sa":
							case "qa":
								currentIso = "arabic";
								break;
							case "br":
								currentIso = "pt";
								break;
						}
						langIso = currentIso;

						vm.currentCountry = response.data.country;
						translateToCurrentLanguage(langIso);
						getVideosToCurrentLanguage(langIso);
						translatePasswordBullets(langIso);
					}
					if (!vm.formData.areaCode) {
						if (response.data.areaCode) {
							vm.formData.areaCode = response.data.areaCode;
							window.intgrtn.store("areaCode", vm.formData.areaCode);
						}
					}
					$scope.$applyAsync();
				}, function () {
					translateToCurrentLanguage();
				});
			}
		};

		function translateToCurrentLanguage(langIso) {
			langIso = typeof langIso !== 'undefined' ? langIso : 'default';
			$http({
				url: 'i18n/' + langIso + '.json',
				method: 'GET'
			}).then(function (response) {
				var translations = response.data;
				document.dispatchEvent(new CustomEvent("translationsLoaded", {
					detail: response
				}));
				applyTranslations(translations, "rtl");
			});
		}

		function translatePasswordBullets(langIso) { //If needed to add a new translation - https://translatr.varunmalhotra.xyz/
			langIso = typeof langIso !== 'undefined' ? langIso : 'default';
			$http({
				url: 'i18n/new_password_translations.json',
				method: 'GET'
			}).then(function (response) {
				var translations = response.data;
				var resultObject = translations.find(function (item) {
					return item.locale == langIso;
				});

				if (typeof resultObject !== 'undefined') {
					var passwordTranslationsArray = resultObject.string.split('. ');
					var passwordTranslation = {
						'Password should be {{passwordMinLength}}-{{passwordMaxLength}} characters long.': passwordTranslationsArray[0],
						'Password should contain at least 1 lowercase.': passwordTranslationsArray[1],
						'Password should contain at least 1 uppercase.': passwordTranslationsArray[2],
						'Password should not contain special chars.': passwordTranslationsArray[3],
						'Password should contain at least 1 number.': passwordTranslationsArray[4],
						'Password should contain at least 1 letter.': passwordTranslationsArray[5],
						'Password and confirm password does not match.': passwordTranslationsArray[6],
					};
					document.dispatchEvent(new CustomEvent("passwordTranslation", {
						detail: passwordTranslation,
					}));
				}
			});
		}

		function getVideosToCurrentLanguage(currentLanguage) {
			var langIso = typeof currentLanguage !== 'undefined' ? currentLanguage : 'en';
			$http({
				url: 'media/' + langIso + '-1.mp4',
				method: 'HEAD'
			}).then(function (videoResponse) {
				vm.mediaFilename['1'] = videoResponse.config.url;
			}, function (reason) {
				vm.mediaFilename['1'] = "media/en-1.mp4";
				langIso = 'en';
			}).finally(function () {
				var player = videojs('video1', {"controls": true, "autoplay": "any", preload: "metadata", "poster": "images/videoThumbnail.png"});
				player.src({type: 'video/mp4', src: vm.mediaFilename['1']});

				$http({url: 'media/subtitles/' + langIso + '.vtt', method: 'head'}).then(function (subtitlesResponse) {
					player.addRemoteTextTrack({kind: 'captions', label: '', language: langIso, src: subtitlesResponse.config.url, mode: "showing"});
				});
			});
			$http({
				url: 'media/' + langIso + '-2.mp4',
				method: 'HEAD'
			}).then(function (response) {
				console.log();
				vm.mediaFilename['2'] = 'media/' + langIso + '-2.mp4';
			}, function (reason) {
				vm.mediaFilename['2'] = "media/en-2.mp4";
				langIso = 'en';
			}).finally(function () {
				var player = videojs('video2', {"controls": true, "autoplay": false, "preload": "metadata", poster: "images/popup-video-poster.png"});
				player.src({type: 'video/mp4', src: vm.mediaFilename['2']});
			});
		};
	}
}());
