/**
 * @author stefan.schult
 * @id $Id: functions.js 892 2011-02-22 12:50:10Z stefans $
 */
var isStartPage = false;
var startAnchor = '';

function init(fn) {
	try {
		$(fn);
	} catch(ex) {
	}

}

function gotoAnchor(anchorId) {
	try {
		var a = $(anchorId);
		if (a.length != 0) {
			a.attr('href', '#')[0].focus();
			a.removeAttr('href');
		}
	} catch(ex) {
	}
}


init(function() {

	$('body').addClass('JS');
	// Plugins
	$('#iTopContent').liToSelect("h4");
	$('input.preFilled').inpPrefilled();
	$('.contactTeaserMod').toggleHiddenContent('img');
	$('.intrCalcMod').intrCalc();
	$('.expandMod').faq();
	$('.compassMod').compass();
});

init(function() {
	var genSrcs = function(img) {
		var src = $(img).attr('src');
		var i = new Image();
		i.src = $(img).attr('data-hover');
		return {
			normal: img,
			hover: $(i),
			show: function(){
				this.hover.show();
				this.normal.show();
			}
		};
	},
			genLayerCont = function(cont) {
				var h, t = null, mh = false, c = cont.clone();
				c.removeClass('visualBox2');
				var close = $('<a href="javascript:void(0);" class="close">Fenster schließen</a>').click(function(event) {
					hide();
				});
				if ($(document.body).attr('id') == 'homepage') {
					t = $('.teasers');
					h = t.height() + 10;
				} else {
					t = $('#iContent');
					mh = !(cont.parents('#content').length);
					if(cont.attr('data-height') != ''){
						h = cont.attr('data-height');
					}
				}
				function hide() {
					$('.teaser-overlay', t).hide();
					if(mh){
						$('*', cont).show();
					}
				}

				return {
					show: function() {
						var to = $('.teaser-overlay', t);
						if (!$('.teaser-overlay').length) {
							to.hide();
							t.append('<div class="teaser-overlay"><div class="teaser-overlay-cont"/></div>');
							$('.teaser-overlay-cont', t).prepend(close).append(c);
							to = $('.teaser-overlay', t);
							if (h != undefined) {
								to.height(h + 'px');
							}
						}
						if(mh) {
							cont.css('minHeight', cont.height()+'px');
							$('*', cont).hide();
						}
						to.show();

					},
					hide: hide
				};
			},
			srcs = null;

	$(".teaserWithOverlay").each(function() {
		var $two = $(this);
		srcs = genSrcs($('img:first', $two));
		var layer = genLayerCont($two);
		$two.hover(function() {
			srcs.normal.replaceWith(srcs.hover.show());
		}, function() {
			srcs.hover.replaceWith(srcs.normal);
		}).click(function() {
			srcs.show();
			layer.show();
		});
		if ($('.outBody-teaserLayer').length) {
			$(document.body).addClass('teaserLayerBody');
			if (srcs != null) {
				$('.teaserLayer').append($('<div class="teaserLayer-wrapper" />').append($('<div class="teaserLayer-cont" />').append(srcs.normal.clone())))
						;
			}
		}
	});
});

$(window).load(function() {
	if ($('.outBody-teaserLayer').length) {
		setTimeout(function() {
			$('.outBody-teaserLayer').removeClass('outBody-teaserLayer');
			$('.teaserLayer').fadeOut(2000, function() {
				$(document.body).removeClass('teaserLayerBody');
				$(this).removeClass('teaserLayer-init');
				$('.teaserLayer-cont *', this).remove();
			});
		}, 700);
	}
});

init(function() {
	$('p.errorText[id]').each(function() {
		var $t = $(this);
		var id = this.id.substr(6);
		$('label[for=' + id + ']').addClass('invalid');
		$('input[id=' + id + ']').addClass('invalid');
	});
});

init(function() {
	$('.newsbox').each(function() {
		$this = $(this);
		var href = $this.find('a').get(0);
		$(this).click(function() {
			location.href = href;
		});
	});
});

init(function() {
	$('.withSubField').each(function() {
		var $t = $(this);
		var elements = $t.find('label, input');
		var parentRadio = $('input[id=' + $(elements[0]).attr('for') + ']')[0];
		var allRadios = $('input[name=' + $(parentRadio).attr('name') + ']');
		allRadios.each(function() {
			$(this).click(function() {
				if (this != parentRadio) {
					elements[2].value = "";
				} else {
					elements[2].focus();
				}
				;
			});
		});
		$(elements[2]).click(function() {
			parentRadio.checked = true;
		});
	});
});

init(function() {
	$('.subFields').each(function() {
		if (this.id != "" && this.id.indexOf("-subField") != -1) {
			$t = $(this);
			var n = this.id.substring(0, this.id.lastIndexOf("-subField"));
			$("[name=" + n + "]:checkbox").each(function() {
				$(this).data("subFieldId", $t[0].id);
				$(this).click(function() {
					$s = $('#' + $(this).data("subFieldId"));
					if (this.checked) {
						$s.removeClass("inv");
					} else {
						$s.addClass("inv");
					}
				});
				if (this.checked) {
					$t.removeClass("inv");
				} else {
					$t.addClass("inv");
				}
			});
			$("[name=" + n + "]:radio").each(function() {
				var boxValue = $('#' + n + $t.attr('id').substring($t.attr('id').lastIndexOf("-")))[0].value;
				var $b = $t;
				$(this).click(function() {
					if (this.value == boxValue && this.checked) {
						$b.removeClass("inv");
					} else {
						$b.addClass("inv");
					}
				});
				if (this.checked)
					$(this).trigger('click');
			});
		}
		;
	});
});

init(function() {
	var tempHash = location.hash;
	var tabContBox = $('.tabCont');
	var firstTab = $();
	var tabAnchor = '';
	var doNotHashAction = false;
	tabContBox.each(function(i) {
		if (i > 0) return;
		var $self = $(this).parents('.tabNavi');
		tabAnchor = $self.prev().attr('id');
		$self.find(".tabNavigation").tabs('.' + this.className.replace(' ', '.') + " > div");
		$self.find('.tabNavigation a').each(function(i) {
			if (i == 0) {
				firstTab = $(this);
			}
			var fa = $(this.href.substring(this.href.indexOf('#')) + ' a:first');
			fa.addClass('firstAnchor');
			fa.data('anchorId', fa.attr('id'));
			fa.attr('id', fa.data('anchorId') + '_');
			if ('#' + fa.data('anchorId') == tempHash) {
				startAnchor = tabAnchor;
			}
			this.href = location.href.substring(0, location.href.indexOf('#')) + '#' + fa.data('anchorId');
			$(this).click(function() {
				if (!doNotHashAction) {
					location.hash = fa.data('anchorId');
				}
				doNotHashAction = false;
				return false;
			}).data('elemPos', i);
		});
	});

	var firstLoad = true;
	// Bind an event to window.onhashchange that, when the hash changes, gets the
	// hash and adds the class "selected" to any matching nav link.
	$(window).bind('hashchange', function() {
		var hash = location.hash;
		if (firstLoad && hash == "" && $('.tabNavi').length != 0) {
			//			location.replace(location.href + '#' + $('.tabNavi .tabCont:first a:first').data('anchorId'));
			gotoAnchor('#top');
		} else if (!firstLoad && hash == "" && $('.tabNavi').length != 0) {
			if (!firstTab.hasClass('.current')) {
				doNotHashAction = true;
				firstTab.trigger('click');

			}
		}
		;
		var anchor = ($('.tabCont a[id*=' + hash.substring(1) + ']'));
		if (anchor.length > 0) {
			var tabCont = $(hash + '_').parents('div:first');
			var a = tabCont.parents('.tabNavi').find('a[href$=' + hash + ']:first');
			a.trigger('click');
			if (firstLoad && a.data('elemPos') > 0) {
				$('#top').trigger('focus');
			}
			;
		}
		firstLoad = false;
	});

	$(window).trigger('hashchange');
});

init(function() {
	$('.recommMail').each(function() {
		var $this = $(this);
		var $inp = $(this).find("input[name*=recipient]");
		var $fieldset = $($inp.parents()[1]);
		var $hidden = $inp.clone(true);
		$hidden.attr({type:'hidden'});
		var $inps = null;
		$inp.attr({name:'foobar'}).blur(function(event) {
			var v = "";
			$inps.each(function() {
				if (v == "") {
					v += $(this).val();
				} else if ($(this).val() != "") {
					v += "," + $(this).val();
				}
			});
			$hidden.val(v);
		});

		for (var i = 0; i < 2; i++) {
			$i = $($inp.parents()[0]).clone(true);
			$i.find('sup').remove();
			var id = $i.find('label').attr('for') + "-" + (i + 1);
			$i.find('label').text($i.find('label').text() + ' ' + (i + 2)).attr({'for':id});
			$i.find('input').attr({'id': id});
			$fieldset.append($i);
		}
		var hVals = $hidden.val().split(",");
		$inps = $fieldset.find('input[type=text]').each(function(i) {
			if (hVals[i]) {
				$(this).val(hVals[i]);
			} else {
				$(this).val('');
			}
			;
		});
		$this.append($hidden);
	});
});

init(function() {
	if ($('.images').length > 0) {
		$('body').append($('<div class="simple_overlay" id="gallery"><a class="prev">zurück</a><a class="next">vor</a><div class="info"></div><img class="progress" src="/fileadmin/layout/img/overlay/loading.gif" /></div>'));
		$('.images').each(function() {
			$(this).find('li:nth-child(4n)').next().addClass('bC');
			$(this).find('ul img').each(function() {
				$(this).css('margin-top', -$(this).height() / 2);
			});
			try {
				$(this).find('a').overlay({
					target: '#gallery',
					expose: '#f1f1f1'
				}).gallery({
					speed: 800,
					template: '<span>Bild ${index} von ${total}</span>'
				});
			} catch(ex) {
			}
		});
	}
});

init(function() {
	$('.contSitemapMod>ul>li:last-child').addClass('lastChild');
});

init(function() {
	$('.expandSingleMod').each(function() {
		var esm = $(this);
		var esmInner = esm.find('div:first');
		var allLinks = esm.find('.iContMod a');
		var allListElements = esm.find('.iContMod li');
		var texts = {
			swingin: esm.find('input[name=expand]').get(0).value,
			expand: esm.find('input[name=expand]').get(0).value
		};
		var isExpanded = false;
		var expander = $('<a href="javascript:void(0);" />').text(texts.expand);
		esmInner.before($('<p class="expander" />').append(expander))
				.addClass('inv');
		expander.click(function() {
			isExpanded = !isExpanded;
			$(this).text((isExpanded) ? texts.swingin : texts.expand);
			expander.toggleClass('swingin');
			esmInner.toggleClass('inv');
			if (isExpanded) {
				allListElements.each(function() {
					// IE8 Bugfix to show style:before
					$(this).replaceWith($(this).clone());
				});
				allLinks.each(function() {
					this.focus();
				});
				this.focus();
			}
			;

			return false;
		});
		$(esm.find('~ div')[0]).addClass('afterExpandSingleMod');
		esm.find('.iContMod .contMod:first').addClass('firstInnerExpandSingleMod');
	});
});

init(function() {
	$('textarea').maxlength({
		events: [], // Array of events to be triggerd
		maxCharacters: 450, // Characters limit
		status:	true, // True to show status indicator bewlow the element
		statusClass: "status", // The class on the status div
		statusText: "Zeichen sind übrig", // The status text
		notificationClass: "notification",	// Will be added to the emement when maxlength is reached
		showAlert: false, // True to show a regular alert message
		alertText: "You have typed too many characters.", // Text in the alert message
		slider:	false // Use counter slider
	});

});

//init(function(){
//	$('.user-zinsrechner-pi10 input[type=radio][name*=variante]').each(function(){
//		if(this.value == "business"){
//			this.checked = true;
//		};
//	});
//});

init(function() {
	$('.user-zinsrechner-pi12').each(function() {
		var firstLoad = true;
		$(this).find('input[type=text]').focus(function() {
			if (this.value == '0' || this.value == '0,00') {
				this.value = '';
			}
		});
		var r = $(this).find('input[type=radio]');
		r.click(function() {
			r.each(function() {
				var s = $(this).parents('p:first').next();
				if (this.checked) {
					s.removeClass('inv');
					if (!firstLoad)
						s.find('input').focus();
				} else {
					s.addClass('inv');
				}
			});
		});
		r.each(function() {
			if (this.checked)
				$(this).trigger('click');
		});
		firstLoad = false;
	});
});

init(function() {

	$('.sliderMod').each(function() {
		function getSelectOption(index) {
			return select.options[index];
		}

		var spanSlider = $(this).find(' > span');
		spanSlider.wrap($('<span class="sliderCont" />'));
		spanSlider.addClass('iSliderCont');
		var afterSelect = spanSlider.text();
		spanSlider.text('');
		var select = $(this).find('select:first')[0];
		var optionsLength = select.options.length - 1;
		for (var i = 0; i <= optionsLength; i++) {
			var o = getSelectOption(i);
			o.text = o.text + " " + afterSelect;
		}
		var output = $('<span />');
		output.text(getSelectOption(select.options.selectedIndex).text);
		$(select).after(output);
		$(select).addClass('inv');
		spanSlider.slider({
			value: select.options.selectedIndex,
			min: 0,
			max: optionsLength,
			slide: function(event, ui) {
				select.options.selectedIndex = ui.value;
				output.text(getSelectOption(select.options.selectedIndex).text);
			},
			change: function(event, ui) {
				select.options.selectedIndex = ui.value;
				output.text(getSelectOption(select.options.selectedIndex).text);
			}
		});
		$(select).change(function() {
			spanSlider.slider('value', this.options.selectedIndex);
		});
	});
	//$('.sliderMod').slider();
});

init(function() {
	$("div#topContent a.link2").click(function() {
		try {
			_gaq.push(['_trackEvent', 'OnlineBanking-Portal', 'Klick']);
		} catch(ex) {
		}
		;
	});
});


// last
init(function() {
	if (startAnchor == '') {
		startAnchor = location.hash;
	}
	if (startAnchor.indexOf('#') != 0) {
		startAnchor = '#' + startAnchor;
	}
	gotoAnchor(startAnchor);
});

