(function(jQuery) {

	function ltrim(str){
		return str.replace(/^\s+/, '');
	}

	function rtrim(str) {
		return str.replace(/\s+$/, '');
	}

	function trim(str) {
		return str.replace(/^\s+|\s+$/g, '');
	}

	jQuery.cookie = function (key, value, options) {
	    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
	        options = jQuery.extend({}, options);
	        if (value === null) {
	            options.expires = -1;
	        }
	        if (typeof options.expires === 'number') {
	            var days = options.expires, t = options.expires = new Date();
	            t.setDate(t.getDate() + days);
	        }
	        return (document.cookie = [
	            encodeURIComponent(key), '=',
	            options.raw ? String(value) : encodeURIComponent(String(value)),
	            options.expires ? '; expires=' + options.expires.toUTCString() : '',
	            options.path ? '; path=' + options.path : '',
	            options.domain ? '; domain=' + options.domain : '',
	            options.secure ? '; secure' : ''
	        ].join(''));
	    }
	    options = value || {};
	    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
	    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
	};

	jQuery.fn.toggleLoginarea = function(area) {
		if ( debugTime ) console.time('toggleLoginarea');
		if ( area == 'fon' || !area || area == '' || area == null || area === undefined ) {
			jQuery.cookie(loginareaCookie, 'fon', stdCookieOptions);
			// switch login navigation
			jQuery('#fon_trigger').children('a').remove();
			jQuery('#fon_trigger').html("<span>Finanz Online</span>");
			jQuery('#bku_trigger').children('span').remove();
			jQuery('#bku_trigger').html("<a href='#bku_area'>B&uuml;rgerkarte</a>");
			// show fon area
			jQuery('#fon_area').removeClass('hidden');
			// turn on tabindex for links and inputs in fon area
			jQuery('#fon_area a, #fon_area input').each(function() {
				jQuery(this).attr('tabindex', 0);
			});
			// hide bku area
			jQuery('#bku_area').addClass('hidden');
			// turn off tabindex for links and inputs in bku area
			jQuery('#bku_area a, #bku_area input').each(function() {
				jQuery(this).attr('tabindex', -1);
			});
		} else {
			jQuery.cookie(loginareaCookie, 'bku', stdCookieOptions);
			// switch login navigation
			jQuery('#bku_trigger').children('a').remove();
			jQuery('#bku_trigger').html("<span>B&uuml;rgerkarte</span>");
			jQuery('#fon_trigger').children('span').remove();
			jQuery('#fon_trigger').html("<a href='#fon_area'>Finanz Online</a>");
			// show bku area
			jQuery('#bku_area').removeClass('hidden');
			// turn on tabindex for links and inputs in bku area
			jQuery('#bku_area a, #bku_area input').each(function() {
				jQuery(this).attr('tabindex', 0);
			});
			// hide fon area
			jQuery('#fon_area').addClass('hidden');
			// turn off tabindex for links and inputs in fon area
			jQuery('#fon_area a, #fon_area input').each(function() {
				jQuery(this).attr('tabindex', -1);
			});
		}
		if ( debugTime ) console.timeEnd('toggleLoginarea');
	};

	jQuery.fn.password2text = function() {
		if ( debugTime ) console.time('password2text');
		var value = jQuery(this).val();
		jQuery('<input>').attr({
			'type': 'text',
			'id': jQuery(this).attr('id'),
			'name': jQuery(this).attr('name'),
			'tabindex': jQuery(this).attr('tabindex')
		}).addClass(jQuery(this).attr('class')).val(value).insertAfter(jQuery(this));
		jQuery(this).remove();

		jQuery(this).live('focusin', function() {
			if ( jQuery(this).attr('type') == 'text' ) {
				jQuery('<input>').attr({
					'type': 'password',
					'id': jQuery(this).attr('id'),
					'name': jQuery(this).attr('name'),
					'tabindex': jQuery(this).attr('tabindex')
				}).addClass(jQuery(this).attr('class')).val('').insertAfter(jQuery(this)).focus();
				jQuery(this).remove();
			}
		});

		jQuery(this).live('focusout', function() {
			if ( jQuery(this).attr('type') == 'password' && jQuery(this).val() == '' ) {
				jQuery('<input>').attr({
					'type': 'text',
					'id': jQuery(this).attr('id'),
					'name': jQuery(this).attr('name'),
					'tabindex': jQuery(this).attr('tabindex')
				}).addClass(jQuery(this).attr('class')).val(value).insertAfter(this);
				jQuery(this).remove();
			}
		});
		if ( debugTime ) console.timeEnd('password2text');
	};

	jQuery.fn.label2value = function() {
		if ( debugTime ) console.time('label2value');
		jQuery(this).siblings('label').addClass('hidden');
		var label_text = jQuery(this).siblings('label').html();
		if ( label_text.substr(label_text.length-1, 1) == ':' ) {
			label_text = label_text.substr(0, (label_text.length - 1));
		}
		jQuery(this).val(label_text);
		if ( debugTime ) {
			console.timeEnd('label2value');
		}
	};

	jQuery.fn.toggleValue = function() {
		if ( debugTime ) console.time('toggleValue');
		var text = jQuery(this).val();
		jQuery(this).live('focusin', function() {
			if ( jQuery(this).val() == text ) {
				jQuery(this).val('');
			}
		}).live('focusout', function() {
			if ( jQuery(this).val() == '' ) {
				jQuery(this).val(text);
			}
		});
		if ( debugTime ) console.timeEnd('toggleValue');
	};

	jQuery.fn.setStylesheet = function() {
		if ( debugTime ) console.time('setStylesheet');
		var currentCookieValue = jQuery.cookie(fontsizeCookie);
		jQuery('link[rel*=stylesheet][title^=fontsize_]').each(function() {
			jQuery(this).attr('disabled', true);
			var title = jQuery(this).attr('title');
			if ( title == defaultFontsize && (currentCookieValue == '' || currentCookieValue == null || currentCookieValue === undefined) ) {
				jQuery(this).attr('disabled', false);
				jQuery.cookie(fontsizeCookie, title, stdCookieOptions);
				jQuery('#' + title).addClass('active');
			} else if ( title == currentCookieValue ) {
				jQuery(this).attr('disabled', false);
				jQuery('#' + title).addClass('active');
			}
		});
		if ( debugTime ) console.timeEnd('setStylesheet');
	};

	jQuery.fn.switchStylesheet = function(newFontsize) {
		if ( debugTime ) console.time('switchStylesheet');
		jQuery('#fontsize a').removeClass('active');
		jQuery('link[@rel*=stylesheet][title]').each(function() {
			jQuery(this).attr('disabled', true);
			var title = jQuery(this).attr('title');
			if(title == newFontsize) {
				jQuery(this).attr('disabled', false);
				jQuery.cookie(fontsizeCookie, newFontsize, stdCookieOptions);
				jQuery('#' + newFontsize).addClass('active');
			}
		});
		if ( debugTime ) console.timeEnd('switchStylesheet');
	};

	jQuery.fn.debugArea = function(options) {
		if ( debugTime ) console.time('debugArea');
		var options = jQuery.extend({}, jQuery.fn.debugArea.defaults, options);
		var item = jQuery(this);
		var links = jQuery('<p>').addClass('debuglinks');
		var currentCookieValue = jQuery.cookie(debugareaCookie);
		jQuery(links).append('<a href="#" class="' + options.pushpinLinkClass + '">' + options.pushpinLinkPushText + '</a>');
		jQuery(links).append('<a href="#" class="' + options.toogleLinkClass + '">' + options.toggleLinkHideText + '</a>');
		jQuery(item).prepend(links);
		if ( currentCookieValue == 'hidden' ) {
			jQuery(item).children('ul, h1').hide();
			jQuery(item).find('a.' + options.toogleLinkClass).html(options.toggleLinkShowText);
		}
		if ( currentCookieValue == 'hidden' ) {
			jQuery(item).find('a.' + options.pushpinLinkClass).html(options.pushpinLinkReleaseText);
		}
		jQuery(item).find('a.' + options.toogleLinkClass).click(function() {
			if ( jQuery(item).children('ul:visible').length ) {
				jQuery(item).children('ul, h1').slideUp('fast');
				jQuery(this).html(options.toggleLinkShowText);
			} else {
				jQuery(item).children('ul, h1').slideDown('fast');
				jQuery(this).html(options.toggleLinkHideText);
			}
			return false;
		});
		jQuery(item).find('a.' + options.pushpinLinkClass).click(function() {
			var currentCookieValue = jQuery.cookie(debugareaCookie);
			if ( currentCookieValue == '' || currentCookieValue == null || currentCookieValue === undefined ) {
				jQuery(this).html(options.pushpinLinkReleaseText);
				if ( jQuery(item).children('ul:visible').length ) {
					var newCookieValue = 'visible';
				} else {
					var newCookieValue = 'hidden';
				}
			} else {
				jQuery(this).html(options.pushpinLinkPushText);
				var newCookieValue = null;
			}
			jQuery.cookie(debugareaCookie, newCookieValue, stdCookieOptions);
			return false;
		});
		jQuery(item).find('a').attr('tabindex', -1);
		if ( debugTime ) console.timeEnd('debugArea');
	};

	jQuery.fn.debugArea.defaults = {
		toogleLinkClass: 'toggle_debug',
		toggleLinkHideText: 'Bereich einklappen',
		toggleLinkShowText: 'Bereich ausklappen',
		pushpinLinkClass: 'pushpin_debug',
		pushpinLinkPushText: 'Status speichern',
		pushpinLinkReleaseText: 'Status freigeben'
	};

	jQuery.fn.cleanShortcuts = function() {
		if ( debugTime ) console.time('cleanShortcuts');
		var item = jQuery(this);
		var height = item.height();
		var cookieValue = jQuery.cookie(fontsizeCookie);
		if ( cookieValue == 'fontsize_normal' ) var oneLine = 20;
		else if ( cookieValue == 'fontsize_bigger' ) var oneLine = 30;
		else if ( cookieValue == 'fontsize_big' ) var oneLine = 40;
		if( height > oneLine ) {
			item.addClass("long");
		}
		else if ( height == 0 ) {
			item.remove();
		}
		if ( debugTime ) console.timeEnd('cleanShortcuts');
	};

	jQuery.fn.popup = function(options) {
		if ( debugTime ) console.time('popup');
		var options = jQuery.extend({}, jQuery.fn.popup.defaults, options);
		var positionX = (screen.availWidth / 2) - (options.popupWidth / 2);
		var positionY = (screen.availHeight / 2) - (options.popupHeight / 2);
		
		jQuery(this).removeAttr('target');
		jQuery(this).click(function() {
			window.open(this.href, options.popupName,'top=' + positionY + ', left=' + positionX + ', height=' + options.popupHeight + ', width=' + options.popupWidth + ', status=' + options.status + ', menubar=' + options.menubar + ', resizable=' + options.resizable + ', scrollbars=' + options.scrollbars + ', toolbar=' + options.toolbar + ', location=' + options.location + ', directories=' + options.directories);
			return false;
		})
		if ( debugTime ) console.timeEnd('popup');
	};

	jQuery.fn.popup.defaults = {
		'popupWidth': 736,
		'popupHeight': 585,
		'popupName': 'popup',
		'status': 'no',
		'menubar': 'no',
		'resizable': 'yes',
		'scrollbars': 'yes',
		'toolbar': 'no',
		'location': 'no',
		'directories': 'no'
	};

	jQuery.fn.linkToButton = function(options) {
		if ( debugTime ) console.time('link2button');
		var options = jQuery.extend({}, jQuery.fn.linkToButton.defaults, options);
		var oldLink = this;
		jQuery('<input>', {
			'type': 'button',
			'value': oldLink.text(),
			'class': options['class'],
			'click': function() {
				location = oldLink.attr('href');
			}
		}).insertAfter(oldLink);
		oldLink.detach();
		if ( debugTime ) console.timeEnd('link2button');
	};

	jQuery.fn.linkToButton.defaults = {
		'class': 'button'
	};

	jQuery.fn.truncateText = function(options) {
		if ( debugTime ) console.time('truncateText');
		var item = this;
		var options = jQuery.extend({}, jQuery.fn.truncateText.defaults, options);
		var classes = jQuery(item).attr('class').split(' ');
		var origHeight = jQuery(item).height();
		var origText = jQuery(item).text();

		// search for a class that starts with options.lenghtPrefix and set the var newLength
		jQuery(classes).each(function(i) {
			if ( classes[i].substring(0, options['lengthPrefix'].length) == options['lengthPrefix'] ) {
				var newLength = classes[i].substring(options['lengthPrefix'].length);

				// if the original text is longer than the new length ...
				if ( newLength != '' && origText.length > newLength ) {
					// ... save and truncate text ...
					var newText = jQuery(item).text().substring(0, newLength) + options['postFix'];
					jQuery(item).text(newText);
					// ... save the new height (for restore on mouseleave) ...
					var newHeight = jQuery(item).height();
					// ... and bind mouseevents
					jQuery(item).bind({
						mouseenter: function() {
							jQuery(this).css('height', newHeight);
							jQuery(this).text(origText);
							jQuery(this).animate({
								height: origHeight
							}, options.speedIn);
						},
						mouseleave: function() {
							jQuery(this).animate({
								height: newHeight
							}, options.speedOut, function() {
								jQuery(this).text(newText);
							});
						}
					});
				}
			}
		});
		if ( debugTime ) console.timeEnd('truncateText');
	};

	jQuery.fn.truncateText.defaults = {
		'postFix': " ...",
		'lengthPrefix': "truncate_",
		'speedIn': 250,
		'speedOut': 250
	};

	function debug(obj) {
		if ( window.console && window.console.log ) {
			window.console.log();
		}
	};
})(jQuery);



var fontsizeCookie = 'usp_fontsize';
var defaultFontsize = 'fontsize_normal';
var loginareaCookie = 'usp_login';
var debugareaCookie = 'usp_debugarea';
var stdCookieOptions = { 'path': '/', 'expires': 3560 };
var debugTime = false;

jQuery(document).ready(function() {

	// set stylesheet initial
	jQuery.fn.setStylesheet();

	// switch stylesheet on click
	jQuery('#fontsize a').click(function() {
		jQuery.fn.switchStylesheet(jQuery(this).attr('id'));
		return false;
	});

	// debug area
	jQuery('#debug').debugArea();

	// html optimieren
	if ( debugTime ) console.time('html optimieren');
	jQuery('ul.overview li:last').css('margin-bottom', 0);
	jQuery('div.overview_content > p:last').css('margin-bottom', 0);
	jQuery('div.overview_content > ul:last').css('margin-bottom', 0);
	jQuery('div.overview_content > ul li:last').css('margin-bottom', 0);
	jQuery('div.sidebar_box_space p:last').css('margin-bottom', 0);
	if ( debugTime ) console.timeEnd('html optimieren');

	// truncate all elements with class truncate
	jQuery('.truncate').each(function() {
		jQuery(this).truncateText();
	});

	// transform all links with class link2button to buttons
	jQuery('.link2button').each(function() {
		jQuery(this).linkToButton();
	});

	// links with class popup should open in a popup and not in a "normal" new window
	jQuery("a.popup").each(function() {
		jQuery(this).popup();
	});

	// links should not stay active
	jQuery('a').click(function() {
		jQuery(this).blur();
	});


	function getElementWidth(element, rootElement, lineHeight) {
		if (element && element.length > 0) {
			//cleanup the node so we can calculate its width
			element.children("dfn").remove();//this line should be replaced by a check for all hidden children instead of "dfn"
			element.html(jQuery.trim(element.html()));
			element.html(element.html().replace(/ /ig, "&nbsp;"));
			//calculate the width of the actual element
			height = element.height();
			if (lineHeight && rootElement && height > lineHeight) {
				oldposition = rootElement.css("position");
				rootElement.css("position","absolute");
				width = element.width();
				rootElement.css("position",oldposition)
			} else {
				width = element.width();
			}
			return width;
		}
		return 0;
	}
	
		function getPossibleElementWidth(elementCode, rootElement) {
		var originalWidth = getElementWidth(rootElement);
		var originalHTML = rootElement.html();
		rootElement.html(originalHTML + "<span>" + elementCode + "</span>");
		var width = getElementWidth(rootElement) - originalWidth;
		rootElement.html(originalHTML);
		return width;
	}
	
	function getSpaceWidth(rootElement) {
		return getPossibleElementWidth("&nbsp;",rootElement);
	}
	
	

	// breadcrumb shortening
	var i = 1;
	var sum = 0;
	var breadcrumb = jQuery("#breadcrumb_content");
	var links = breadcrumb.find("a").get();
	var seperatorWidth = getElementWidth(breadcrumb.find("img:first"));
	var home = breadcrumb.find("a:first");
	var homeWidth = getElementWidth(home);
	var spaceWidth = getSpaceWidth(home);
	var lineHeight = home.height()
	var elipsis = " <img src='/USP_Static/img/breadcrumb_spacer.gif' alt='' class='breadcrumb_spacer' /><span> &hellip; </span>";
	var elipsisWidth = getPossibleElementWidth(elipsis, home);
	//left for debugging
	//console.log("elipsis: "+elipsisWidth + " seperator: "+ seperatorWidth + " spaceWidth: " + spaceWidth);
	var availableWidth = (jQuery(".breadcrumb_space").width() - homeWidth - elipsisWidth);
	
	
	jQuery(links.reverse()).each(function() {
		var element = jQuery(this);
		if(i != links.length) { //don't calculate the home link
			var width = getElementWidth(element, breadcrumb, lineHeight);
			sum = (sum + width + seperatorWidth + (2 * spaceWidth));
			//left for debugging
			//console.log(i + "| width:" + width + " sum:" + sum + " available:" + availableWidth);
		}
		
		if(sum > availableWidth && i != null) {
			if(i == links.length) {
				//add the elipsis after the home link when we removed elements
				element.after(elipsis);
			} else {
				//remove element if it's not the home button
				element.addClass("hidden").next("img.breadcrumb_spacer").eq(0).addClass("hidden");
			}
		}
		i = (i + 1);
	});

	// move logout area down when a skiplink has the focus
	if ( jQuery('#logout form').length != 0 ) { // only when loggedin
		jQuery('#skiplinks a').live('focusin', function() {
			jQuery('#logout').css('margin-top', '1.1em');
		}).live('focusout', function() {
			jQuery('#logout').css('margin-top', '0');
		});
	}

	// login area (only if div#login_wrapper is present)
	if ( jQuery('#login_wrapper').length > 0 ) {

		jQuery('#Login #fon_area form').attr('autocomplete', 'off');

		jQuery('#login_wrapper h2').addClass('hidden');

		jQuery("#Login #startMobileBku").click(function(){
			jQuery("#Login #bku_area").html("<iframe src='$!{portal.properties.login_mobilebku_url}' width='215' frameborder='0' scrolling='no'></iframe>");
			return false;
		});

		// add login navigation
		jQuery('#login_type').append('<ul><li id="fon_trigger"><span>Finanz Online</span></li><li id="bku_trigger"><a href="#bku_area">B&uuml;rgerkarte</a></li></ul>');
		jQuery('<input type="button" id="reset_fon_login" value="Zur&uuml;cksetzen" class="button" />').appendTo('#fon_area .login_buttons');

		// set initial login method to bku if cookie is set to bku
		if ( jQuery.cookie(loginareaCookie) == 'bku' ) {
			jQuery.fn.toggleLoginarea('bku');
		}

		// trigger to show the fon area
		jQuery('#fon_trigger a').live('click', function() {
			jQuery.fn.toggleLoginarea('fon');
			return false;
		});

		// trigger to show the bku area
		jQuery('#bku_trigger a').live('click', function() {
			jQuery.fn.toggleLoginarea('bku');
			return false;
		});

		jQuery('#TID').label2value();
		jQuery('#TID').toggleValue();
		jQuery('#BENID').label2value();
		jQuery('#BENID').toggleValue();
		jQuery('#PIN').label2value();
		jQuery('#PIN').password2text();

		jQuery('#reset_fon_login').live('click', function() {
			jQuery('#TID').label2value();
			jQuery('#BENID').label2value();
			jQuery('#PIN').label2value();
			jQuery('#PIN').password2text();
			jQuery(this).blur();
			return false;
		});

		jQuery('#newsletter_categories input[type="checkbox"]:first').click(function() {
			var checked = jQuery(this).attr('checked');
			jQuery('#newsletter_categories').find('input[type="checkbox"]').attr('checked', checked);
		});

		jQuery('#newsletter_categories input[type="checkbox"]:not(:first)').click(function() {
			jQuery('#newsletter_categories input[type="checkbox"]:first').attr('checked', false);
		});

	}

});
