var SANTANDER = {
	path 		: 'https://www.santander.nl/templates/santander/',
	font 		: 'https://www.santander.nl/templates/santander/swf/frutiger55.swf',
	priceUrl 	: 'https://www.santander.nl/components/com_calculator/daypremium.php',
	postcodeUrl	: 'https://www.santander.nl/postcodesearch'
};

(function () {
	var root = document.documentElement,
		jsclass = 'tt-js';
	(root.className) ? root.className += ' ' + jsclass : root.className = jsclass;
})();

// application code

SANTANDER.buttons = {
	init : function () {
		jQuery('#page').find('input.submit').each(
			function () {
				var form = this.form,
					a = document.createElement('A');
				a.className = 'button';
				a.href = '#';
				a.innerHTML = '<span>' + this.value + '</span>';
				jQuery(this).replaceWith(a);
				jQuery(a).click(
					function () {
						if (jQuery(form).hasClass('tt-calculator')) {
							var data = SANTANDER.form.data(form);
							tb_show(data, form.action, '');
							SANTANDER.ga.delegate(form.elements.donow.value);
							return false;
						} else if ('search-account-manager' === form.id) {
							var ispc = SANTANDER.postcode(form);
							if (ispc) {
								form.submit();
								return true;
							} else {
								return false;
							}
						} else {
							form.submit();
							return true;
						}
					}
				);
			}
		);
	}
};

SANTANDER.calculator = {
	shift : null,
	init : function () {
		jQuery('form.tt-calculator').each(
			function () {
				var jThis = jQuery(this);
				jThis.keydown(SANTANDER.calculator.watch);
				jThis.keyup(SANTANDER.calculator.watch);
				jThis.find('div.tt-ui-slider').each(
					function () {
						var jjThis = jQuery(this);
						var min = +jjThis.find('span.tt-ui-slider-min').text();
						var max = +jjThis.find('span.tt-ui-slider-max').text();
						var ratio = +jjThis.find('span.tt-ui-slider-ratio').text();
						jjThis.find('span.tt-ui-noscript').replaceWith('<span class="tt-slider"><span></span><b></b></span>');
						window.setTimeout(
							function () {
								SANTANDER.calculator.slider(jjThis, min, max, ratio);
							}, 200
						);
					}
				);
				var inp = [];
				jThis.find('input[type=text]').each(
					function () {
						this.onkeypress = function (e) {
							e = e || window.event;
							return (13 !== e.keyCode);
						};
						inp.push(this);
						this.onblur = function () {
							var i = jQuery.inArray(this, inp);
							if (SANTANDER.calculator.shift) {
								if (i > 0) {
									inp[(i - 1)].focus();
								}
							} else {
								if (i < (inp.length - 1)) {
									inp[(i + 1)].focus();
								}
							}
						};
					}
				);
			}
		);
	},
	watch : function (e) {
		if (16 === e.keyCode) {
			SANTANDER.calculator.shift = (SANTANDER.calculator.shift) ? null : e.keyCode;
		}
	},
	slider : function (el, min, max, ratio) {
		var bar = el.find('span.tt-slider');
		var barWidth = bar.width() - 9; // handle width is set in CSS
		var bg = bar.find('span');
		var inp = el.find('input');
		inp.val(0);
		bar.slider({
			min: min,
			max: max,
			handle : 'b',
			slide: function(e, ui) {
				var val = ui.value;
				//var fact = ((val-min) / ((max-min)/100));
				var fact = ((val-min) / ((max-min)/100));
				bg.width(Math.round((barWidth/100) * fact));
				inp.val((Math.round(val / ratio) * ratio));
			}
		});
	}
};

SANTANDER.exampleRatesTabs = {
	current : null,
	cache : {},
	init : function () {
		jQuery('#example-tabs a').each(
			function (i) {
				var jThis = jQuery(this);
				var hash = SANTANDER.exampleRatesTabs.hash(this);
				var parent = jThis.parent();
				SANTANDER.exampleRatesTabs.cache[hash] = {
					parent : parent,
					target : jQuery(hash)
				};
				if (0 === i) {
					parent.addClass('hilite');
					SANTANDER.exampleRatesTabs.current = hash;
				} else {
					jQuery(hash).hide();
				}
				jThis.click(
					function () {
						var hash = SANTANDER.exampleRatesTabs.hash(this);
						if (hash !== SANTANDER.exampleRatesTabs.current) {
							var current = SANTANDER.exampleRatesTabs.current;
							var cache = SANTANDER.exampleRatesTabs.cache;
							cache[current].parent.removeClass('hilite');
							cache[current].target.hide();
							cache[hash].parent.addClass('hilite');
							cache[hash].target.show();
							SANTANDER.exampleRatesTabs.current = hash;
						}
						return false;
					}
				);
			}
		);
	},
	hash : function (obj) {
		return obj.href.substring(obj.href.indexOf('#'));
	}
};

SANTANDER.form = {
	data : function (form) {
		var fields = form.elements,
			l = fields.length,
			controls = ['input', 'textarea', 'select'/*, 'button' is evil */],
			exclusions = ['image', 'button', 'reset', 'submit'], // type attr
			field,
			name,
			type,
			obj = {},
			data = [],
			val;
		for (var i = 0; i < l; i++) {
			field = fields[i];
			if (-1 !== SANTANDER.indexOf(field.nodeName.toLowerCase(), controls)) {
				name = field.name || field.id;
				type = field.type && field.type.toLowerCase();
				if (name && !obj[name] && (-1 === SANTANDER.indexOf(type, exclusions))) {
					val = this.value(form, name);
					obj[name] = val;
				}
			}
		}
		return obj;
	},
	value : function (form, name) {
		var field = form.elements[name],
			type  = field.type && field.type.toLowerCase();
		if (!field || (type && (('checkbox' === type) || ('radio' === type)) && !field.checked)) {
			return false;
		}
		if (field.length && !field.options) {
			var l = field.length, radio;
			while (l--) {
				radio = field[l];
				if (radio.checked) {
					return radio.value;
				}
			}
			return false;
		}
		return field.value;
	}
};

SANTANDER.indexOf = function (val, list) {
	for (var i = 0, l = list.length; i < l; i++) {
		if (list[i] === val) {
			return i;
		}
	}
	return -1;
};

SANTANDER.showcase = {
	init : function () {
		var feature = document.getElementById('feature');
		if (feature) {
			var bg = document.createElement('DIV');
			var hor = (jQuery(document.body).hasClass('frontpage')) ? 'right'  : 'left';
			bg.style[hor] = 0;
			jQuery(bg).css({
				position : 'absolute',
				top : (feature.offsetTop - 10) + 'px',
				zIndex : 0,
				width : feature.offsetWidth + 32 + 'px',
				height : feature.offsetHeight + 10 + 'px',
				background : '#ef0000',
				opacity : 0.7
			});
			jQuery('#showcase').append(bg);
		}
	}
};

SANTANDER.siblings = {
	init : function () {
		jQuery('div#page div.content-modules-row').each(
			function () {
				var row = jQuery(this).find('div.content-column');
				if (row.length > 1) {
					var cols = [], reference = 0;
					row.each(
						function () {
							var children = jQuery(this).children(), height = 0;
							height += this.offsetHeight;
							(height > reference) && (reference = height);
							cols.push({
								elementNode : this,
								height : height
							});
						}
					);
					jQuery(cols).each(
						function () {
							var el = this.elementNode;
							if (this.height < reference) {
								var spacer = document.createElement('DIV');
								spacer.style.height = (reference - this.height) + 'px';
								spacer.style.lineHeight = '1px';
								spacer.style.fontSize = '1px';
								jQuery(this.elementNode).find('.stretch').append(spacer);
							}
						}
					);
				}
			}
		);
	}
};

SANTANDER.sifr = function (selector, color) {
	sIFR.replaceElement(named({
		sSelector : selector,
		sFlashSrc : SANTANDER.font,
		sColor : color || "#ffffff",
		sWmode : "transparent"
	}));
};

SANTANDER.toggleDisplay = {
	firstcurrent : null,
	current : null,
	init : function (selector, hidefirst) {
		jQuery(selector).each(
			function (i) {
				var jThis = jQuery(this);
				this.style.cursor = 'pointer';
				if (i > 0) {
					jThis.next().hide();
				} else {
					jThis.next().show();
					SANTANDER.toggleDisplay.current = this;
					if (!hidefirst) {
						jThis.addClass('hilite');
					} else {
						jThis.next().hide();
						SANTANDER.toggleDisplay.firstcurrent = this;
					}
				}
				jThis.mouseover(SANTANDER.toggleDisplay.over);
				jThis.mouseout(SANTANDER.toggleDisplay.out);
				jThis.click(SANTANDER.toggleDisplay.click);
			}
		);
	},
	over : function () {
		jQuery(this).addClass('hilite');
	},
	out : function () {
		if (this == SANTANDER.toggleDisplay.firstcurrent || this !== SANTANDER.toggleDisplay.current) {
			jQuery(this).removeClass('hilite');
		}
	},
	click : function () {
		if (this == SANTANDER.toggleDisplay.firstcurrent || this !== SANTANDER.toggleDisplay.current) {
			SANTANDER.toggleDisplay.firstcurrent = null;
			var that = this;
			jQuery(SANTANDER.toggleDisplay.current).next().slideUp(
				200,
				function () {
					jQuery(SANTANDER.toggleDisplay.current).removeClass('hilite');
					jQuery(that).addClass('hilite');
					SANTANDER.toggleDisplay.current = that;
					jQuery(that).next().slideDown(300);

				}
			);
		}
	}
};

SANTANDER.tooltip = {
	diff : 0,
	init : function (root) {
		var page = (root && jQuery(root)) || jQuery('#page');
		var content = jQuery('#content');
		page.find('div.tooltip').each(
			function (e) {
				if (!root) {
					var tip = this.parentNode.removeChild(this);
					content.append(tip);
				} else {
					var tip = this;
				}
				jQuery(tip).hide();
				jQuery(tip).click(
					function (e) {
						jQuery(tip).hide();
						jQuery('a.info-button').each(
							function () {
								this.style.zIndex = '';
							}
						);
					}
				);
			}
		);
		page.find('a.info-button').each(
			function (e) {
				var jThis = jQuery(this), t = null;
				jThis.mouseover(
					function () {
						var that = this;
						t = window.setTimeout(
							function () {
								var id = that.href.substring(that.href.indexOf('#'));
								id = jQuery(id);
								id.css({
									top : (that.offsetTop + 15) + 'px',
									left : (that.offsetLeft + 18) + 'px'
									   });
								id.fadeIn(200);
							}, 200
						);
					}
				);
				jThis.mouseout(
					function () {
						if (t) {
							window.clearTimeout(t);
							t = null;
							var id = this.href.substring(this.href.indexOf('#'));
							id = jQuery(id);
							id.fadeOut(100);
						}
					}
				);
				jThis.click(
					function () {
						return false;
					}
				);
			}
		);
		/*
		page.click(
			function (e) {
				var trigger = e.target.parentNode;
				if (jQuery(trigger).hasClass('info-button')) {
					var id = trigger.href.substring(trigger.href.indexOf('#'));
					id = jQuery(id);
					id.css({
						top : (trigger.offsetTop - 8) + 'px',
						left : (trigger.offsetLeft - 8) + 'px'
					});
					if (('none') === id[0].style.display) {
						id[0].style.display = '';
						//trigger.style.zIndex = '102';
						//e.target.style.zIndex = '103';
					} else {
						id[0].style.display = 'none';
						//trigger.style.zIndex = '';
						//e.target.style.zIndex = '';
					}
					e.preventDefault();

				}
			}
		);
		*/
	},
	toggle : function (id, trigger) {
		id.css({
			top : (trigger.offsetTop - 8) + 'px',
			left : (trigger.offsetLeft - 8) + 'px'
		});
		id.toggle();
	}
};

SANTANDER.loanscan = {
	offset : null,
	markers : function (id, l) {
		var center = Math.floor(id.offsetWidth / 2);
		var interval = Math.floor((center - (75)) / l);
		var marker = SANTANDER.loanscan.marker();
		for (var i = 0, m, o; i < l; i++) {
			m = id.appendChild(marker.cloneNode(true));
			m.style.left = (center - (m.offsetWidth / 2) + ((i + 1) * interval)) + 'px';
			m = id.appendChild(marker.cloneNode(true));
			m.style.left = (center - (m.offsetWidth / 2) - ((i + 1) * interval)) + 'px';
		}
	},
	result : function () {
		var offset = window.location.toString().split('#');
		if (offset[1]) {
			var params = offset[1].split(';'), l = params.length, pair;
			var header = document.getElementById('loanscan');
			var slider = document.getElementById('loanscan-slider');
			while (l--) {
				pair = params[l].split('=');
				switch (pair[0]) {
					case 'markers':
						if (header) {
							SANTANDER.loanscan.markers(header, pair[1]);
						}
						break;
					case 'offset':
						if (slider) {
							slider.style.left = pair[1] + 'px';
						}
						break;
					case 'result':
						var hilite = '#adc857';
						if (0 !== +pair[1]) {
							var pos = (pair[1] > 0) ? 'right' : 'left';
							jQuery(header).find('span.' + pos).css({background:hilite});
						}
						break;
				}
			}
		}
	},
	init : function () {
		var id = document.getElementById('loanscan');
		var slider = document.getElementById('loanscan-slider');
		var form = document.forms['loanscan-list'];
		if (id && slider && form) {
			var jForm = jQuery(form);
			jForm.find('div.submit input').hide();
			var products = jQuery(id).find('span.product');
			var center = Math.floor(id.offsetWidth / 2);
			var jSteps = jForm.find('div.step'),
				l = jSteps.length,
				sliderOffset = slider.offsetLeft,
				interval = Math.floor((center - (75)) / l),
				maxOffset = sliderOffset + ((l * interval)),
				minOffset = sliderOffset - ((l * interval));

			// generate the markers
			var marker = SANTANDER.loanscan.marker();
			for (var i = 0, m, o; i < l; i++) {
				m = id.appendChild(marker.cloneNode(true));
				m.style.left = (center - (m.offsetWidth / 2) + ((i + 1) * interval)) + 'px';
				m = id.appendChild(marker.cloneNode(true));
				m.style.left = (center - (m.offsetWidth / 2) - ((i + 1) * interval)) + 'px';
			}

			// move the slider
			var radios = jForm.find('input[type=radio]');
			radios.each(
				function () {
					this.checked = false;
					jQuery(this).click(
						function () {
							var next = jQuery(this).parents('div.step').find('a.button');
							next.fadeTo(200, 1);
							next.css({cursor : ''});
							var score = 0;
							radios.each(
								function () {
									if (this.checked) {
										score += +this.value;
									}
								}
							);
							var offset = (sliderOffset + (score * interval));
							if (offset > maxOffset) {
								offset = maxOffset;
							} else if (offset < minOffset) {
								offset = minOffset;
							}
							SANTANDER.loanscan.offset = offset;
							offset += 'px';
							jQuery(slider).animate({
								left : offset
							}, 300);
							products.each(
								function (i) {
									var bg = (
										((score < 0) && (0 === i)) // persoonlijke lening
										|| ((score > 0) && (1 === i)) // doorlopend krediet
									) ? '#adc857' : '';
									this.style.backgroundColor = bg;
								}
							);
						}
					);
				}
			);
			// hide options, generate next/back links
			jSteps.each(
				function (i) {
					var jStep = jQuery(this);
					var h2 = jQuery(this).find('h2');
					var jNext = h2.next();
					if (i > 0) {
						jNext.hide();
						var jPrev = jStep.prev();
						var backLink = SANTANDER.loanscan.backLink('back', '#' + jPrev.id, 'terug');
						jNext.append(backLink);
						jQuery(backLink).click(
							function () {
								var jOl = jPrev.find('ol');
								jNext.slideUp(
									200,
									function () {
										jOl.slideDown(300);
									}
								);
								return false;x
							}
						);
					}
					var last = ((i + 1) === l);
					var text = last ? 'Uitslag' : 'Ga verder';
					var link = last ? '#berekenen' : '#step' + (i + 2);
					var nextLink = SANTANDER.loanscan.nextLink('button', link, text);
					jQuery(nextLink).css({
						opacity : 0.4,
						cursor : 'default'
					});
					jNext.append(nextLink);
					jQuery(nextLink).click(
						function () {
							var answer = SANTANDER.loanscan.checkBox(jNext);
							if (answer) {
								if (!last) {
									var jOl = jStep.next().find('ol');
									jNext.slideUp(
										200,
										function () {
											jOl.slideDown(300);
										}
									);
								} else {
									form.appendChild(SANTANDER.loanscan.field('offset', SANTANDER.loanscan.offset));
									form.appendChild(SANTANDER.loanscan.field('markers', l));
									form.submit();
								}
							}
							return false;
						}
					);
				}
			);
		}
	},
	// the only thing sillier than jQuery is its so-called documentation;
	// we make and append element nodes the good old long winded way because we
	// want proper references, too [ed.]
	field : function (name, value) {
		var inp = document.createElement('INPUT');
		inp.type = 'hidden';
		inp.name = name;
		inp.value = value;
		return inp;
	},
	marker : function () {
		var div = document.createElement('DIV');
		div.className = 'loanscan-marker';
		return div;
	},
	backLink : function (className, href, text) {
		var a = SANTANDER.loanscan.createLink(className, href);
		a.appendChild(document.createTextNode(text));
		return a;
	},
	nextLink : function (className, href, text) {
		var a = SANTANDER.loanscan.createLink(className, href);
		var span = document.createElement('SPAN');
		a.appendChild(span);
		span.appendChild(document.createTextNode(text));
		return a;
	},
	createLink : function (className, href) {
		var a = document.createElement('A');
		a.className = className;
		a.href = href;
		return a;
	},
	checkBox : function (obj) {
		var answer = false;
		obj.find('input').each(
			function () {
				if (this.checked) {
					answer = this.value;
				}
			}
		);
		return answer;
	}
};

SANTANDER.postcode = function (f) {
	var pc = f.postcode;
	pc.onkeyup = function () {
		if (this.style.borderColor && (/\d{4}/.test(this.value)) || '' === this.value) {
			this.style.borderColor = '';
		}
	};
    var ispc = /\d{4}/.test(pc.value);
	if (ispc) {
		return true;
	} else {
		pc.style.borderColor = '#fe0000';
		return false;
	}
};

SANTANDER.ga = {
	uriMap : {
		'https://www.santander.nl/' : 'homepage',
		'persoonlijke-lening' : 'PL-pagina',
		'doorlopend-krediet' : 'DK-pagina'
	},
	calcMap : {
		'maandlasten' : 'maandlasten',
		'max_leen' : 'maximaallenen',
		'oversluiten' : 'besparenophuidigelening'
	},
	resolve : function (uriRef) {
		var pn = window.location.pathname;
		if ('https://www.santander.nl/' === pn) {
			return 'https://www.santander.nl/';
		} else {
			pn = pn.split('https://www.santander.nl/')[2];
			return pn;
		}
	},
	track : function (path1, path2) {
		var tracker = 'https://www.santander.nl/onclick/' + SANTANDER.ga.uriMap[path1] + 'https://www.santander.nl/' + path2;
		pageTracker2._trackPageview(tracker);
	},
	delegate : function (param) {
		if ('string' === typeof param) {
			param = SANTANDER.ga.calcMap[param];
			SANTANDER.ga.track(SANTANDER.ga.resolve(), param);
		} else {
			var a = param.target;
			if (1 !== a.nodeType) {
				a = a.parentNode;
			}
			if ('a' === a.parentNode.nodeName.toLowerCase()) {
				a = a.parentNode;
			}
			if (a.href) {
				var target;
				var pn = a.href.split('https://www.santander.nl/');
				var pc = pn[(pn.length - 1)];
				var path = window.location.pathname;
				var trackleenscan;
				if ('https://www.santander.nl/' === path) {
					if ('bereken-maandlasten' === pc) {
						if ('persoonlijke-lening' === pn[(pn.length - 2)]) {
							target = 'voorbeeld-PL';
						}
						if ('doorlopend-krediet' === pn[(pn.length - 2)]) {
							target = 'voorbeeld-DK';
						}
					} else if ('leenscan' === pc) {
						target = 'leenscan';
					}
				} else if (
					('https://www.santander.nl/leningen/persoonlijke-lening/bereken-maandlasten' === path
					 || 'https://www.santander.nl/leningen/doorlopend-krediet/bereken-maandlasten' === path)
					&& 'leenscan' === pc
					) {
					target = 'leenscan';
				}
				if (target) {
					SANTANDER.ga.track(SANTANDER.ga.resolve(), target);
				}
			}
		}
	}
};

