
var SCBFIWidget = SCBFIWidget || {};

var SCBFIWidgetOptions = {
	apiUrl: 'https://api.santanderconsumer.fi'
};

(function () { 
	"use strict";

	// Object.assign() browser polyfill
	if (!Object.assign) {
		Object.defineProperty(Object, 'assign', {
			enumerable: false,
			configurable: true,
			writable: true,
			value: function (target) {
				'use strict';
				if (target === undefined || target === null) {
					throw new TypeError('Cannot convert first argument to object');
				}

				var to = Object(target);
				for (var i = 1; i < arguments.length; i++) {
					var nextSource = arguments[i];
					if (nextSource === undefined || nextSource === null) {
						continue;
					}
					nextSource = Object(nextSource);

					var keysArray = Object.keys(Object(nextSource));
					for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
						var nextKey = keysArray[nextIndex];
						var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
						if (desc !== undefined && desc.enumerable) {
							to[nextKey] = nextSource[nextKey];
						}
					}
				}
				return to;
			}
		});
	}

	SCBFIWidget = {
		elements: document.querySelectorAll("[data-scbfiwidgetid]"),
		windowWidth: window.innerWidth,
		state: {
			translationsLoaded: false,
			cssLoaded: false
		},
		options: SCBFIWidgetOptions || {},
		icons: {
			arrowRight: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" /><path d="M0 0h24v24H0z" fill="none" /></svg>'
		},
		addAccentColorStyles: function (elem, widgetClass, color) {
			elem.insertAdjacentHTML('afterbegin', '<style type="text/css">' +
				widgetClass + ' .SCBFI-widget-accent-color, ' + widgetClass + ' a.SCBFI-widget-accent-color, ' + widgetClass + ' a.SCBFI-widget-accent-color:visited { color: ' + color + ' !important; }' +
				widgetClass + ' .SCBFI-widget-button { background-color: ' + color + ' !important; border-color: ' + color + ' !important;  }' +
				widgetClass + ' .SCBFI-widget-button:hover { background-color: #fff !important; color: ' + color + ' !important; }' +
				widgetClass + ' .SCBFI-widget-button-invert { background-color: #fff !important; border-color: ' + color + ' !important; color: ' + color + ' !important; }' +
				widgetClass + ' .SCBFI-widget-button-invert:hover { background-color: ' + color + ' !important; }' +
				widgetClass + ' .SCBFI-widget-icon svg { fill: ' + color + ' !important; }' +
				widgetClass + ' .SCBFI-widget-vek-link-container .SCBFI-widget-vek-link { color: ' + color + ' !important; }' +
				'</style>');
		},
		addClass: function (el, className) {
			if (el.classList) {
				el.classList.add(className);
			} else {
				el.className += ' ' + className;
			}
		},
		cleanPricingCalculationData: function (data) { // get rid of the columns without value
			var visibleCols = [],
				removeCols = [],
				i, j;

			for (i = 0; data.maturities.length > i; i = i + 1) {
				removeCols.push(i);
			}

			for (i = 0; data.calculation.length > i; i = i + 1) {
				for (j = 0; data.calculation[i].maturities.length > j; j = j + 1) {
					if (data.calculation[i].maturities[j].monthlyPayment !== null && visibleCols.indexOf(j) < 0) {
						visibleCols.push(j);
						if (removeCols.indexOf(j) >= 0) {
							removeCols.splice(removeCols.indexOf(j), 1);
						}
					}
				}
			}

			for (i = removeCols.length - 1; i >= 0; i = i - 1) {
				data.maturities.splice(removeCols[i], 1);
			}

			for (i = 0; data.calculation.length > i; i = i + 1) {
				for (j = removeCols.length - 1; j >= 0; j = j - 1) {
					data.calculation[i].maturities.splice(removeCols[j], 1);
				}
			}

			return data;
		},
		getAvailableMaturities: function (data, amountIndex) {
			var availableMaturities = [],
				i = 0;

			for (i = 0; i < data.calculation[amountIndex].maturities.length; i = i + 1) {
				if (data.calculation[amountIndex].maturities[i].monthlyPayment !== null) {
					availableMaturities.push(data.calculation[amountIndex].maturities[i]);
				}
			}

			return availableMaturities;
		},
		getFinanceLink: function (data, amount, maturity) {
			return SCBFIWidget.options.apiUrl + '/widget-redirect/' + data.id + '/' + amount + '/' + maturity;
		},
		getLoanData: function (calculationData, amount, maturity) {
			var loanData;

			calculationData.forEach(function (item) {
				if (item.amount === amount) {
					loanData = { amount: item.amount };

					if (item.maturities && item.maturities.length > 0) {
						item.maturities.forEach(function (maturityItem) {
							if (maturityItem.maturity === maturity) {
								loanData = Object.assign({}, loanData, maturityItem);
							}
						});
					}
				}
			});

			return loanData;
		},
		getTermsCampaignText: function (data, amount, maturity) {
			var periodTexts = [],
				periodText,
				termsData,
				self = this,
				i;

			if (data.pricingData.campaignCalc !== null && data.pricingData.campaignCalc.length > 0) {
				for (i = 0; data.pricingData.campaignCalc.length > i; i = i + 1) {
					if (data.pricingData.campaignCalc[i].periodEnd - data.pricingData.campaignCalc[i].periodStart > 0) {
						periodText = (data.pricingData.campaignCalc[i].periodStart + 1) + '-' + (data.pricingData.campaignCalc[i].periodEnd + 1);
						termsData = self.getLoanData(data.pricingData.campaignCalc[i].calculation, amount, maturity);

						if (termsData) {
							periodTexts.push(SCBFIWidgetTranslations.Periods[data.lang] + ' ' + periodText + ': ' + (termsData.monthlyPayment ? termsData.monthlyPayment.toLocaleString('fi-FI', { minimumFractionDigits: 2 }) : '0') + '€/' + SCBFIWidgetTranslations.month[data.lang]);
						}
					}
				}

				periodText = periodTexts.join(', ');

				return periodText.length > 0 ? '(' + periodText + ')' : '';
			}

			return '';
		},
		insertVekLink: function (containerdata, data, amount, maturity) {
			var vekLink;

			if (data.hasOwnProperty('showVekText') && data.showVekText === false) {
				return '';
			}

			if (containerdata && amount && maturity && data.id) {
				containerdata.innerHTML = '';
				vekLink = document.createElement('a');
				vekLink.innerHTML = SCBFIWidgetTranslations.vekText[data.lang];
				vekLink.href = SCBFIWidget.options.apiUrl + '/widget-vek/' + data.id + '/' + amount + '/' + maturity;
				vekLink.classList.add('SCBFI-widget-vek-link');
				vekLink.target = '_blank';

				containerdata.appendChild(vekLink);
			}
		},
		createTermsText: function (text, termsData, periodText) {
			if (termsData) {
				text = text.replace('{{amount}}', termsData.amount ? termsData.amount.toLocaleString('fi-FI', { minimumFractionDigits: 2 }) : '0');
				text = text.replace('{{maturity}}', termsData.maturity ? termsData.maturity.toLocaleString('fi-FI') : '0');
				text = text.replace('{{monthlyPayment}}', termsData.monthlyPayment ? termsData.monthlyPayment.toLocaleString('fi-FI', { minimumFractionDigits: 2 }) : '0');
				text = text.replace('{{periodText}}', periodText ? periodText : '');
				text = text.replace('{{interestRate}}', termsData.interestRate ? termsData.interestRate.toLocaleString('fi-FI', { minimumFractionDigits: 2 }) : '0');
				text = text.replace('{{administrationFee}}', termsData.administrationFee ? termsData.administrationFee.toLocaleString('fi-FI', { minimumFractionDigits: 2 }) : '0');
				text = text.replace('{{invoiceFee}}', termsData.invoiceFee ? termsData.invoiceFee.toLocaleString('fi-FI', { minimumFractionDigits: 2 }) : '0');
				text = text.replace('{{creditCosts}}', termsData.creditCosts ? termsData.creditCosts.toLocaleString('fi-FI', { minimumFractionDigits: 2 }) : '0');
				text = text.replace('{{totalAmountRepayable}}', termsData.totalAmountRepayable ? termsData.totalAmountRepayable.toLocaleString('fi-FI', { minimumFractionDigits: 2 }) : '0');
				text = text.replace('{{kslEffectiveInterest}}', termsData.kslEffectiveInterest ? termsData.kslEffectiveInterest.toLocaleString('fi-FI', { minimumFractionDigits: 2 }) : '0');

				return text;
			} else {
				return '';
			}
		},
		getTermsText: function (data, text, amount, maturity) {
			var calculation;
			var termsData;
			var periodText = '';

			if (data.hasOwnProperty('showTermsText') && data.showTermsText === false) {
				return '';
			}

			if (amount && maturity) {
				calculation = data.pricingData.calculation;

				termsData = this.getLoanData(calculation, amount, maturity);

				// get campaign terms text
				periodText = this.getTermsCampaignText(data, amount, maturity);		 

				return this.createTermsText(text, termsData, periodText);
			}

			return '';
		},
		init: function () {
			var i = 0;

			// load page widgets
			for (i = 0; i < this.elements.length; i = i + 1) {
				this.loadWidget(this.elements[i], this.elements[i].dataset.scbfiwidgetid);
			}
		},
		initializeWidget: function (data) {
			data.initialized = true;
			SCBFIWidget[data.widgetType].init(data);
		},
		isNumberChar: function (evt) {
			var charCode = (evt.which) ? evt.which : event.keyCode;

			if (charCode > 31 && (charCode < 48 || charCode > 57)) {
				return false;
			} else {
				return true;
			}
		},
		loadCss: function (path) {
			var date = new Date();
			var ts = date.getFullYear().toString() + date.getMonth().toString() + date.getDate().toString() + date.getHours().toString();
			var cssUrl = path + "css/style.css?" + ts;
			var css;

			// create style link
			if (document.createStyleSheet) {
				try {
					this.state.cssLoaded = true;
					document.createStyleSheet(cssUrl);
				} catch (e) {
					console.error("Santander Sales Finance Widget", "Error loading common stylesheet");
				}
			} else {
				this.state.cssLoaded = true;
				css = document.createElement("link");
				css.rel = "stylesheet";
				css.type = "text/css";
				css.media = "all";
				css.href = cssUrl;
				document.getElementsByTagName("head")[0].appendChild(css);
			}
		},
		loadTranslations: function (path) {
			var js;
			var date = new Date();
			var ts = date.getFullYear().toString() + date.getMonth().toString() + date.getDate().toString() + date.getHours().toString();
			var scriptId = "SCBFIWidgetJS-translations";
			var self = this;

			if (document.getElementById(scriptId)) { return false; }

			js = document.createElement("script");
			js.id = scriptId;
			js.src = path + "translations.js?" + ts;
			document.head.appendChild(js);

			js.onload = function () {
				self.state.translationsLoaded = true;
			};

			return js;
		},
		loadWidgetError: function (elem, widgetId, placeholderLoadingDotsInterval) {
			var placeholderLoaderElem = document.getElementById('SCBFI-widget-placeholder-loader-' + widgetId);

			console.error('Woops, error loading Santander Sales Finance Widget: ' + widgetId);

			// remove placeholder loader
			clearInterval(placeholderLoadingDotsInterval);

			if (placeholderLoaderElem) {
				placeholderLoaderElem.parentNode.removeChild(placeholderLoaderElem);
			}

			var html = '';

			html = html + '<div class="SCBFI-widget">';
			html = html + '	<div class="SCBFI-widget-main SCBFI-widget-table SCBFI-widget-table-default">';
			html = html + '		<div class="SCBFI-widget-header">';
			html = html + '			<h2 class="SCBFI-widget-title">Hae ostorahoitusta</h2>';
			html = html + '		</div>';
			html = html + '		<div class="SCBFI-widget-loader" style="display: none;"></div>';
			html = html + '			<div class="SCBFI-widget-content" style="display: block;">';
			html = html + '			<div class="SCBFI-widget-error-msg">';
			html = html + '				<div class="SCBFI-widget-error-msg-container">';
			html = html + '					<div class="SCBFI-widget-error-msg-text">';
			html = html + '						<p>Palvelussa on yhteyshäiriö, joka estää hinnoittelutietojen noutamisen.</p>';
			html = html + '						<p>Voit tehdä alustavan hakemuksen yleisellä hinnoittelulla alla olevan linkin kautta.</p>';
			html = html + '					</div>';
			html = html + '				</div>';
			html = html + '				<p><a class="SCBFI-widget-button SCBFI-widget-get-finance-button" href="https://aplat.santanderconsumer.fi/salesfinance/?cid=1001" target="_blank"><span>Hae ostorahoitusta</span></a></p>';
			html = html + '				<p class="SCBFI-widget-termsText">Ongelmatilanteissa voit olla yhteydessä Santanderin Asiakaspalveluumme <a href="https://mypage.santanderconsumer.fi/" target="_blank">verkkopalvelun kautta</a> tai puhelimitse 09 8564 5451, Ma-Pe klo 9.00-16.00.</p>';
			html = html + '			</div>';
			html = html + '		</div>';
			html = html + '	</div>';
			html = html + '</div>';

			elem.innerHTML = html;

			elem.insertAdjacentHTML('afterbegin', '<style type="text/css">' +
				'.SCBFI-widget * { font-family: "Open Sans", sans-serif !important; }' +
				'.SCBFI-widget { font-family: "Open Sans", sans-serif !important; max-width: 600px !important; font-size: 14px !important; line-height: 20px !important; border: 1px solid #ced0d1 !important; padding: 15px !important; margin: 0 0 20px !important; background: #fff !important; color: #878F97 !important; border-radius: 3px !important; -webkit-box-shadow: 0px 0px 3px 0px rgba(206,208,209,1) !important; box-shadow: 0px 0px 3px 0px rgba(206,208,209,1) !important; }' +
				'.SCBFI-widget-title { font-size: 20px !important; background: none !important; font-weight: 400 !important; line-height: 28px !important; color: #31373D !important; margin: 0 0 20px !important; padding: 0 !important; }' +
				'.SCBFI-widget-termsText { font-size: 12px !important; }' +
				'.SCBFI-widget-button, .SCBFI-widget-button:link, .SCBFI-widget-button:visited { display: inline-block !important; background: #ec0000 !important; border: 2px solid #ec0000 !important; border-radius: 25px !important; color: #fff !important; padding: 10px 15px !important; text-decoration: none !important; -webkit-box-shadow: 0 2px 2px 0 rgba(0,0,0,0.14), 0 3px 1px -2px rgba(0,0,0,0.12), 0 1px 5px 0 rgba(0,0,0,0.2) !important; box-shadow: 0 2px 2px 0 rgba(0,0,0,0.14), 0 3px 1px -2px rgba(0,0,0,0.12), 0 1px 5px 0 rgba(0,0,0,0.2) !important; }' +
				'.SCBFI-widget-termsText a, .SCBFI-widget-instructionText a { color: #428BCA !important; cursor: pointer !important; text-decoration: none !important; }' +
				'.SCBFI-widget-button:hover, .SCBFI-widget-button:active { text-decoration: none !important; color: #ec0000 !important; background: #fff !important;' +
				'</style>');
		},
		loadWidget: function (elem, widgetId) {
			var self = this;
			var xhr = new XMLHttpRequest();
			var allCommonFilesLoadedInterval;

			if (!widgetId && widgetId.length <= 0) { return; }

			// insert placeholder loader
			elem.insertAdjacentHTML('afterend', '<div id="SCBFI-widget-placeholder-loader-' + widgetId + '" style="display: inline-block; height: 30px; width: 60px;  position: relative; overflow: hidden;"><span style="position: absolute; top: -15px; width: 100%; font-size:30px;" id="SCBFI-widget-placeholder-loader-wait-' + widgetId + '"></span></div>');
			
			var placeholderLoadingDotsInterval = window.setInterval(function () {
				var wait = document.getElementById('SCBFI-widget-placeholder-loader-wait-' + widgetId);
				if (wait.innerHTML.length > 5)
					wait.innerHTML = ".";
				else
					wait.innerHTML += ".";
			}, 300);

			if (xhr) {
				xhr.open('GET', SCBFIWidget.options.apiUrl + '/widget-pricing/' + widgetId);
				xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');

				xhr.onload = function () {
					if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
						var data = JSON.parse(xhr.response);

						data.id = widgetId;
						data.parameters = elem.dataset.scbfiwidgetparameters && elem.dataset.scbfiwidgetparameters.length > 0 ? JSON.parse(elem.dataset.scbfiwidgetparameters.replace(/\'/g, '"')) : {};
						self.cssLoaded = true;

						if (self.state.hasOwnProperty(data.widgetType) === false) {
							self.state[data.widgetType] = { "scriptLoaded": false, "items": [] };
						}

						// use user defined lang from element data attribute if exists
						if (data.parameters.hasOwnProperty('lang')) {
							data.lang = data.parameters.lang;
						}

						// add widget item to state
						data.initialized = false;
						data.elem = elem;
						self.state[data.widgetType].items.push(data);

						// load translations file if not loaded
						if (self.state.translationsLoaded === false) {
							self.loadTranslations(data.widgetUrlPath);
						}

						// load common css file (if not loaded)
						if (self.state.cssLoaded === false) {
							self.loadCss(data.widgetUrlPath);
						}

						// wait until all common files are loaded before trying to load widget
						allCommonFilesLoadedInterval = setInterval(function () {
							var placeholderLoaderElem = document.getElementById('SCBFI-widget-placeholder-loader-' + data.id);
							if (self.state.translationsLoaded === true) {
								clearInterval(allCommonFilesLoadedInterval);

								// remove placeholder loader
								clearInterval(placeholderLoadingDotsInterval);

								if (placeholderLoaderElem) {
									placeholderLoaderElem.parentNode.removeChild(placeholderLoaderElem);
								}

								if (self.state[data.widgetType].scriptLoaded === false) {
									self.loadWidgetScript(data); // load widget files if not loaded
								} else {
									self.initializeWidget(data); // init widget
								}
							}
						}, 0);
					} else {
						self.loadWidgetError(elem, widgetId, placeholderLoadingDotsInterval);			
					}
				};

				xhr.onerror = function () {
					self.loadWidgetError(elem, widgetId, placeholderLoadingDotsInterval);
				};

				xhr.send();
			}
		},
		loadWidgetScript: function (data) {
			var self = this;
			var js;
			var date = new Date();
			var scriptId = "SCBFIWidgetJS-" + data.widgetType;
			var ts = date.getFullYear().toString() + date.getMonth().toString() + date.getDate().toString() + date.getHours().toString();

			if (document.getElementById(scriptId)) {
				return;
			}

			js = document.createElement("script");
			js.id = scriptId;
			js.src = data.widgetUrlPath + "widgets/" + data.widgetType + "/widget.js?" + ts;
			document.head.appendChild(js);

			js.onload = function () {
				var i = 0;

				self.state[data.widgetType].scriptLoaded = true;

				// initialize widgets from state
				for (i = 0; i < self.state[data.widgetType].items.length; i = i + 1) {
					if (!self.state[data.widgetType].items[i].initialized) {
						self.initializeWidget(self.state[data.widgetType].items[i]);
					}
				}
			};
		},
		numberInputOnKeyPress: function (e) {
			if (SCBFIWidget.isNumberChar(e) === false) {
				e.preventDefault();
				return false;
			}

			return true;
		},
		numberInputOnPaste: function (e) {
			var oldValue = e.target.value;

			setTimeout(function () {
				if (isNaN(parseInt(e.target.value))) {
					e.target.value = oldValue;
				}
			}, 10);
		},
		removeAllWhiteSpace: function (s) {
			s = s.toString();

			return s.replace(/\s/g, '');
		},
		renderElemTranslations: function (elem, translations, lang) {
			var itemsToTranslate,
				translation = '',
				i;

			if (elem) {
				itemsToTranslate = elem.querySelectorAll('[data-swtransl]');
			} else {
				itemsToTranslate = document.querySelectorAll('[data-swtransl]');
			}

			for (i = 0; i < itemsToTranslate.length; i = i + 1) {
				translation = '';

				if (translations[itemsToTranslate[i].dataset.swtransl] !== undefined && translations[itemsToTranslate[i].dataset.swtransl].hasOwnProperty(lang)) {
					translation = translations[itemsToTranslate[i].dataset.swtransl][lang];

					if (translation.length > 0) {
						itemsToTranslate[i].innerHTML = translation;
					}
				}
			}
		},
		showWidgetLoadingError: function (data, templateElements) {
			var html = '';

			html = html + '<div class="SCBFI-widget-error-msg">';
			html = html + '<div class="SCBFI-widget-error-msg-container">';
			html = html + '<div class="SCBFI-widget-icon-wrap"><span class="SCBFI-widget-icon-error"></span></div>';
			html = html + '<div class="SCBFI-widget-error-msg-text" data-swtransl="errorMessageWidgetLoad"></div>';
			html = html + '</div>';
			html = html + '<p><a class="SCBFI-widget-button SCBFI-widget-get-finance-button" href="' + SCBFIWidget.getFinanceLink(data, '', '') + '" target="_blank"><span data-swtransl="applyForFinance"></span></a></p>';
			html = html + '<p class="SCBFI-widget-termsText" data-swtransl="errorMessageCommonText"></p>';
			html = html + '</div>';

			templateElements.loader.style.display = 'none';
			templateElements.layout.content.style.display = 'block';
			templateElements.layout.content.innerHTML = html;
			this.renderElemTranslations(templateElements.layout.content, SCBFIWidgetTranslations, data.lang);
			//this.loadTranslations(templateElements.layout.content);
		}
	};

	SCBFIWidget.init();
}());