var tb_timer1 = '',
	tb_timer2 = '',
	tb_scrollpos = 0,
    tb_prevfocus = false,
    tb_isopen = false,
    responsiveparent = 'true',
    windowProxies = [],
    mainWindowProxy,
    prevWinSize = [0,0],
    droptimer = false;

// Prevent console errors

(function () {
    'use strict';
    var method,
        noop = function () {
        },
        methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'],
        length = methods.length,
        console = (window.console = window.console || {});
    while (length >= 0) {
        length -= 1;
        method = methods[length];
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

// Trim support

if (typeof String.prototype.trim !== 'function') {
    String.prototype.trim = function () {
        'use strict';
        return this.replace(/^\s+|\s+$/g, '');
    };
}

// indexOf support for old IE

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/ ) {
        'use strict';
        var len = this.length >>> 0;
        var from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0) {
            from += len;
        }
        for (; from < len; from = from + 1) {
            if (from in this && this[from] === elt) {
                return from;
            }
        }
        return -1;
    };
}

// Fix ios5 fixed headers

if ((/iphone|ipod|ipad.*os 5/gi).test(navigator.appVersion)) {
    window.onpageshow = function (evt) {
        'use strict';
        if (evt.persisted) {
            window.scrollTo(0, 0);
        }
    };
}
window.onpageshow = function () {
    'use strict';
    window.setTimeout(function () {
        $(window).trigger('resize orientationchange');
        fitMenu(true);
    }, 500);
};

// Jquery regex

jQuery.expr[':'].regex = function(elem, index, match) {
    'use strict';
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

// Framed document responsiveness (iframes and popups)

function framed() {
    'use strict';
	mainWindowProxy.post({
		'action': 'setframeheightResponse',
		'height': $('body').height()
	});
}

// Turn responsive stylesheets off

function disableResponsive() {
    'use strict';
    require(['jquery.cookie', 'jquery.ibcookie'], function () {
        $.IbCookie('responsive', 'desktop');
        location.reload();
    });
}

// Turn responsive stylesheets on

function enableResponsive() {
    'use strict';
    require(['jquery.cookie', 'jquery.ibcookie'], function () {
        $.IbCookie('responsive', 'default');
        location.reload();
    });
}

// Detect touch capability

function isTouchDevice() {
    'use strict';
    return ('ontouchstart' in window || getMedia() === 'narrow');
}

// Menu functions

function showMenu(ref, evt) {
    'use strict';
    $('BODY').trigger('click');
    window.clearTimeout(droptimer);
    if (ref.closest('LI').hasClass('open') && evt.type === 'click') {
		hideMenu();
        ref.blur();
        return;
    }
    if ($('#menu01drop').length === 0) {
        $('BODY').append('<div id="menu01drop"><div class="a clear" id="menu01dropContent"></div></div>');
    }
    var drop = $('#menu01drop');
    drop.removeAttr('class').removeAttr('style');

    if (!isTouchDevice()) {
        drop.hover(function () {
            window.clearTimeout(droptimer);
        }, function () {
            window.clearTimeout(droptimer);
            droptimer = window.setTimeout('hideMenu()', 250);
        });
    }

    if (drop.data('ref')) {
        drop.find('#menu01dropContent').contents().detach().insertAfter(drop.data('ref'));
    }
    drop.data('ref', ref);
    ref.closest('UL').find('LI.open').removeClass('open');
    ref.closest('UL').addClass('open');
    ref.closest('LI').addClass('open').find('UL:first').detach().appendTo(drop.find('#menu01dropContent'));
    if (ref.attr('data-drop')) {
        drop.removeAttr('class').addClass(ref.attr('data-drop'));
    } else {
        drop.removeAttr('class');
    }
    if (ref.outerWidth() > drop.outerWidth()) {
        drop.css('minWidth', ref.outerWidth());
    } else {
        drop.css('minWidth', '');
    }

    if (ref.offset().left + drop.outerWidth() <= ref.closest('DIV').offset().left + ref.closest('DIV').outerWidth() + 26) {
		// Can fit
        drop
            .css({
                display: 'block',
                left: ref.offset().left - 20 + 'px',
                top: ref.closest('DIV').offset().top + ref.closest('DIV').outerHeight() + 'px'
            });
    } else if (ref.offset().left + ref.outerWidth() - drop.outerWidth() < ref.closest('DIV').offset().left) {
        // Can't fit from neither side
        drop
			.css({
				display: 'block',
				left: ref.closest('DIV').offset().left - 20 + 'px',
				top: ref.closest('DIV').offset().top + ref.closest('DIV').outerHeight() + 'px'
			});
    } else {
		// Can't fit from left
        drop
            .css({
                display: 'block',
                left: ref.offset().left + ref.outerWidth() + 20 - drop.outerWidth() + 'px',
                top: ref.closest('DIV').offset().top + ref.closest('DIV').outerHeight() + 'px'
            });
    }
    $('#box00').bind('click.menu', function (e) {
        hideMenu();
    });

    if (!isTouchDevice()) {
        ref.closest('LI').hover(function () {
            window.clearTimeout(droptimer);
        }, function () {
            window.clearTimeout(droptimer);
            droptimer = window.setTimeout('hideMenu()', 250);
        });
    }

    $('#menu01').css('zIndex', '');
    $(window).bind('resize.menu', function () {
        $('#box00').click();
    });
}

function hideMenu() {
    'use strict';
    $('#box00').unbind('click.menu');
    $(window).unbind('resize.menu');
    var drop = $('#menu01drop');
    if (drop.length === 0) { return; }
    drop.css('display', 'none');
    if (drop.data('ref')) {
        drop.data('ref').closest('UL').removeClass('open').find('LI.open').removeClass('open');
        drop.find('#menu01dropContent').contents().detach().insertAfter(drop.data('ref'));
        drop.removeData('ref');
    }
}

function showMobMenu() {
    'use strict';
    $('#box00').removeAttr('style');
    if ($('#box00').hasClass('open')) {
        $('#box00, #box04, #menu01').removeClass('open').removeAttr('style');
        $(window).unbind('resize.mobmenu');
        $('#header01').unbind('click.mobmenu');
    } else {
        $('#box00').addClass('open');
        $('#box04').css('height', window.screen.height);
        $('#menu01').css('minHeight', window.screen.height);
        setMobMenuSize();
        $(window).bind('resize.mobmenu', function () {
            setMobMenuSize();
        });
        $('#header01').one('click.mobmenu', function () {
            showMobMenu();
        });
    }
}

function setMobMenuSize() {
    'use strict';
    if (getMedia() === 'wide') {
        $('#box00, #box04, #menu01').removeClass('open').removeAttr('style');
        $(window).unbind('resize.mobmenu');
        $('#header01').unbind('click.mobmenu');
    } else {
        var h = $('#menu01').outerHeight() > $(window).height() ? $('#menu01').outerHeight() : $(window).height();
        if ($('#profile01drop').length > 0) {
            if ($('#profile01drop').position().top > 0) {
                if (h < $('#profile01drop').outerHeight() + $('#profile01drop').position().top) {
                    h = $('#profile01drop').outerHeight() + $('#profile01drop').position().top + $('#header01').outerHeight();
                }
            }
        }
        if ($('#box00').outerHeight() !== h) {
            $('#box00').css({ height: h });
        }
    }
}

// Get current active media set

function getMedia() {
    'use strict';
    var st = $(contentholders).css('backgroundImage'),
        ret;
    if (st !== undefined && st !== 'none' && st !== "") {
        ret = st.match(/,([^"]*)["]*\)/)[1];
    } else {
        ret = false;
    }
    return ret;
}

// Get current active frame set

function getFrame() {
    'use strict';
    var ret = false;
    ret = $('BODY').css('borderStyle') === 'solid';
    return ret;
}

// Remove dropdowns

function dropRemove() {
    'use strict';
    if ($('DIV.header03 [data-dropdown].active').length > 0) {
        $('DIV.header03 [data-dropdown].active').removeClass('active');
        $('BODY').removeClass('dropopen');
        $('DIV.header03').detach().prependTo('#menu01');
        if ($('.dropholder').length >  0) {
            $('BODY, HTML').scrollTop($('.dropholder').data('scrollpos'));
            if ($('.dropholder').data('ev')) {
                $('.dropholder').data('ev').abort();
            }
            $('.dropholder').remove();
        }
    }
}

// Fit main menu to screen

function fitMenu(force) {
    'use strict';
    var menu = $('.menu01'),
        w,
        winSize = [$(window).width(), $(window).height()];

    if (!(prevWinSize[0] === winSize[0] && prevWinSize[1] === winSize[1]) || force) {
        prevWinSize = winSize;
        $('#menu01').removeClass('cantfit');
        w = menu.outerWidth() - (parseInt(menu.css('paddingLeft'), 10) + parseInt(menu.css('paddingRight'), 10)) - 10;
        menu.find('> LI:not(.hidden)').each(function () {
            w -= $(this).width();
        });
        if (w < 0) {
            $('#menu01').addClass('cantfit');
        } else {
            $('#menu01').removeClass('cantfit');
        }
    }
}

// Fit tabs on screen

function fitTabs() {
    'use strict';
    $(contentholders).trigger('click.tabs01');
    $('UL.tabs01, DIV.tabs01 UL:first').each(function () {
        var t = $(this),
            exp = t.find('> LI.exp'),
            w1 = 0,
            w2 = 0;
        t.find('> LI.cantfit').removeClass('cantfit');
        w1 = Math.ceil(t.outerWidth()) - parseInt(t.css('padding-left'), 10) - parseInt(t.css('padding-right'), 10) - parseInt(t.find('> LI:not(.exp):not(.hidden):last').css('margin-right'), 10);
        exp.removeClass('hidden');
        t.find('> LI:not(.exp):not(.hidden)').each(function (index) {
            var w3 = Math.floor($(this).outerWidth()) + parseInt($(this).css('margin-left'), 10) + parseInt($(this).css('margin-right'), 10);
            if (w2 + w3 + Math.floor(exp.outerWidth()) > w1 + 1) {
                $(this).addClass('cantfit');
            }
            w2 += w3;
        });
        if (t.find('> LI.cantfit').length > 0) {
            exp.removeClass('hidden');
        } else {
            exp.addClass('hidden');
        }
        if (t.find('> LI.cantfit:has(A.active)').length > 0) {
            t.find('> LI.exp A').addClass('hasactive');
        } else {
            t.find('> LI.exp A').removeClass('hasactive');
        }
    });
}

// Preloader display

function showLoader(text, ms) {
    'use strict';
    window.clearTimeout(showloadertimer);

    var time = 1000;
    if (ms && typeof ms === 'number') {
        time = ms;
    }
    if (!text) {
        text = '&nbsp;';
    }

    tb_scrollpos = $(window).scrollTop();
    showloadertimer = window.setTimeout(function () {
        hideLoader();
        $('BODY').append('<div id="loader03"><div class="loader03 center"><span>' + text + '</span></div></div>');
        tb_show('', '#TB_inline?width=260&amp;height=20&amp;inlineId=loader03&amp;modal=true&amp');
    }, time);
}

function hideLoader() {
    'use strict';
    window.clearTimeout(showloadertimer);
    tb_remove();
    $('#loader03').remove();
}

// Displays generic overlay to reference object

function showLoaderOverlay(ref) {
    'use strict';
    var loader = $('<div class="loading01" />'),
        owner = $(ref),
        ev;
    ev = function () {
        loader.css({
            marginLeft: owner.css('marginLeft'),
            marginRight: owner.css('marginRight'),
            marginTop: owner.css('marginTop'),
            marginBottom: owner.css('marginBottom'),
            left: owner.position().left,
            top: owner.position().top,
            width: owner.width(),
            height: owner.height()
        });
    };
    ev();
    owner.data('loader', loader);
    loader.data('ev', ev);
    $(window).on('resize orientationchange respondUpdate', ev);
    $(ref).after(loader);
}

// Removes generic overlay from reference object

function hideLoaderOverlay(ref) {
    'use strict';
    if ($(ref).data('loader')) {
        var loader = $(ref).data('loader');
        $(window).unbind('resize', loader.data('ev'));
        loader.remove();
        $(ref).data('loader', 'undefined');
    }
}

// Data amount calculations

function bytesToSize(bytes) {
    'use strict';
    var sizes = ['B', 'KB', 'MB', 'GB', 'TB'],
        ret,
        i;
    if (bytes === 0) {
        ret = '0 B';
    } else {
        i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)), 10);
        ret = Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
    }
    return ret;
}

/*
 * jQuery tableHover plugin
 * Version: 0.1.4
 *
 * Copyright (c) 2007 Roman Weich
 * http://p.sohei.org
 *
 * Dual licensed under the MIT and GPL licenses
 * (This means that you can choose the license that best suits your project, and use it accordingly):
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */
(function(C){var A=function(Q){var S=Q.rows;var K=S.length;var P=[];for(var I=0;I<K;I++){var R=S[I].cells;var O=R.length;for(var H=0;H<O;H++){var N=R[H];var M=N.rowSpan||1;var J=N.colSpan||1;var L=-1;if(!P[I]){P[I]=[]}var E=P[I];while(E[++L]){}N.realIndex=L;for(var G=I;G<I+M;G++){if(!P[G]){P[G]=[]}var D=P[G];for(var F=L;F<L+J;F++){D[F]=1}}}}};var B=function(H){var E=0,F,D,G=(H.tHead)?H.tHead.rows:0;if(G){for(F=0;F<G.length;F++){G[F].realRIndex=E++}}for(D=0;D<H.tBodies.length;D++){G=H.tBodies[D].rows;if(G){for(F=0;F<G.length;F++){G[F].realRIndex=E++}}}G=(H.tFoot)?H.tFoot.rows:0;if(G){for(F=0;F<G.length;F++){G[F].realRIndex=E++}}};C.fn.tableHover=function(D){var E=C.extend({allowHead:true,allowBody:true,allowFoot:true,headRows:false,bodyRows:true,footRows:false,spanRows:true,headCols:false,bodyCols:true,footCols:false,spanCols:true,ignoreCols:[],headCells:false,bodyCells:true,footCells:false,rowClass:"hover",colClass:"",cellClass:"",clickClass:""},D);return this.each(function(){var N=[],M=[],J=this,F,K=0,O=[-1,-1];if(!J.tBodies||!J.tBodies.length){return }var G=function(U,X){var W,V,T,R,Q,S;for(T=0;T<U.length;T++,K++){V=U[T];for(R=0;R<V.cells.length;R++){W=V.cells[R];if((X=="TBODY"&&E.bodyRows)||(X=="TFOOT"&&E.footRows)||(X=="THEAD"&&E.headRows)){S=W.rowSpan;while(--S>=0){M[K+S].push(W)}}if((X=="TBODY"&&E.bodyCols)||(X=="THEAD"&&E.headCols)||(X=="TFOOT"&&E.footCols)){S=W.colSpan;while(--S>=0){Q=W.realIndex+S;if(C.inArray(Q+1,E.ignoreCols)>-1){break}if(!N[Q]){N[Q]=[]}N[Q].push(W)}}if((X=="TBODY"&&E.allowBody)||(X=="THEAD"&&E.allowHead)||(X=="TFOOT"&&E.allowFoot)){W.thover=true}}}};var L=function(R){var Q=R.target;while(Q!=this&&Q.thover!==true){Q=Q.parentNode}if(Q.thover===true){H(Q,true)}};var I=function(R){var Q=R.target;while(Q!=this&&Q.thover!==true){Q=Q.parentNode}if(Q.thover===true){H(Q,false)}};var P=function(T){var R=T.target;while(R&&R!=J&&!R.thover){R=R.parentNode}if(R.thover&&E.clickClass!=""){var Q=R.realIndex,U=R.parentNode.realRIndex,S="";C("td."+E.clickClass+", th."+E.clickClass,J).removeClass(E.clickClass);if(Q!=O[0]||U!=O[1]){if(E.rowClass!=""){S+=",."+E.rowClass}if(E.colClass!=""){S+=",."+E.colClass}if(E.cellClass!=""){S+=",."+E.cellClass}if(S!=""){C("td, th",J).filter(S.substring(1)).addClass(E.clickClass)}O=[Q,U]}else{O=[-1,-1]}}};var H=function(R,T){if(T){C.fn.tableHoverHover=C.fn.addClass}else{C.fn.tableHoverHover=C.fn.removeClass}var V=N[R.realIndex]||[],S=[],U=0,Q,W;if(E.colClass!=""){while(E.spanCols&&++U<R.colSpan&&N[R.realIndex+U]){V=V.concat(N[R.realIndex+U])}C(V).tableHoverHover(E.colClass)}if(E.rowClass!=""){Q=R.parentNode.realRIndex;if(M[Q]){S=S.concat(M[Q])}U=0;while(E.spanRows&&++U<R.rowSpan){if(M[Q+U]){S=S.concat(M[Q+U])}}C(S).tableHoverHover(E.rowClass)}if(E.cellClass!=""){W=R.parentNode.parentNode.nodeName.toUpperCase();if((W=="TBODY"&&E.bodyCells)||(W=="THEAD"&&E.headCells)||(W=="TFOOT"&&E.footCells)){C(R).tableHoverHover(E.cellClass)}}};A(J);B(J);for(F=0;F<J.rows.length;F++){M[F]=[]}if(J.tHead){G(J.tHead.rows,"THEAD")}for(F=0;F<J.tBodies.length;F++){G(J.tBodies[F].rows,"TBODY")}if(J.tFoot){G(J.tFoot.rows,"TFOOT")}C(this).bind("mouseover",L).bind("mouseout",I).click(P)})}})(jQuery);

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

// Tooltips

(function($) {
	$(document).ready(function(){
		$tooltip = $("#tooltip");
		if($tooltip.length == 0){
			$tooltip = $('<div id="tooltip"><div id="tooltip-inner">' + locales.simpleloader + '</div><div id="tooltip-arrow"></div></div>');
			$('BODY').append($tooltip);
		}
		$tooltip.bind('click',function(e){
			e.preventDefault();
			e.stopPropagation();
			$('BODY>DIV:first').unbind('mouseup.tooltip');
			$tooltip.css({left: '-1000px', top: '-1000px', width: ''});
			$('#tooltip-arrow').css('marginLeft','');
			$('#tooltip-inner').html(locales.simpleloader);
		});
	});
	$.fn.extend({
		tooltip : function () {
            this.each(function () {
                $this = $(this);
                if (!$this.attr("title") && !$this.attr("alt") && $this.attr('href') !== '#' && !$this.attr('data-tooltip') && !$this.data('tooltip')){ return; }
                if(!$this.data('tooltip')){
                    if($this.attr('title') && $this.attr('title') !== ''){
                        $this.data('tooltip',$this.attr('title')).attr('title','');
                    }
                    if($this.attr('alt') && $this.attr('alt') !== ''){
                        $this.data('tooltip',$this.attr('alt')).attr('alt','');
                    }
                }
                $this.attr('tooltip-text', $this.data('tooltip'));
            });
			this.bind('click.tooltip', function(e) {
                if (getMedia() === 'narrow') {
                    e.preventDefault();
                    e.stopPropagation();
                    $(this).toggleClass('open');
                }
            });
            this.bind('mouseenter.tooltip click.tooltip', function(e){
				e.preventDefault();
				e.stopPropagation();
				$this = $(this);
				var viewport,
                    tmp;

				if ((!$this.attr("title") && !$this.attr("alt") && $this.attr('href') === '#' && !$this.attr('data-tooltip') && !$this.data('tooltip'))){ return; }
                if ($this.outerWidth() > 20 && $this.is('.help01, .help02, .helpico01, .helpico02')) { return; }

				fit = $('BODY').outerWidth() - $this.offset().left - $tooltip.outerWidth();
				if(window.innerWidth){
					viewport = window.innerWidth;
				} else {
					viewport = $(window).width();
				}
				if (!$this.attr("title") && !$this.attr("alt") && $this.attr('href') !== '#' && !$this.attr('data-tooltip') && !$this.data('tooltip')){
					$this.click(function(e){
						e.preventDefault();
						e.stopPropagation();
					});
					$.ajax({
						url: $this.attr('href'),
						success: function(data) {
							$this.data('tooltip',data).trigger('mouseenter.tooltip');
						}
					});
				} else {
					var tooltipcontent;
					if(!$this.data('tooltip')){
						if($this.attr('title') && $this.attr('title') !== ''){
							$this.data('tooltip',$this.attr('title')).attr('title','');
						}
						if($this.attr('alt') && $this.attr('alt') !== ''){
							$this.data('tooltip',$this.attr('alt')).attr('alt','');
						}
					}
					tooltipcontent = $this.data('tooltip');
					$('#tooltip-inner').html(tooltipcontent);
					$tooltip.removeAttr('class');
					if($this.hasClass('showtooltip-right')){
						// try to show tooltip on the right
						if($this.offset().left + $this.outerWidth() + $tooltip.outerWidth() > $('BODY').outerWidth() && $this.offset().left - $tooltip.outerWidth() > 0){
							// can't fit to the right
							$tooltip.attr('class','left side').css({
								left: $this.offset().left - $tooltip.outerWidth() + 'px',
								top: $this.offset().top + 'px'
							});
						} else if($this.offset().left + $this.outerWidth() + $tooltip.outerWidth() > $('BODY').outerWidth() && $this.offset().left - $tooltip.outerWidth() < 0){
							// but can't fit to the left either
							tmp = $('BODY').outerWidth() - ($this.offset().left + $tooltip.outerWidth()) - 15;
							if(tmp < 15){
								tmp = $this.offset().left + tmp;
							} else {
								tmp = $this.offset().left;
							}
							$tooltip.attr('class','left top').css({
								left: tmp + 'px',
								top: $this.offset().top - $tooltip.outerHeight() + 'px'
							});
							$('#tooltip-arrow').css('marginLeft', $this.offset().left - tmp);
						} else {
							// can fit
							$tooltip.attr('class','right side').css({
								left: $this.offset().left + $this.outerWidth() + 'px',
								top: $this.offset().top + 'px'
							});
						}
					} else if($this.hasClass('showtooltip-left')){
						// try to show tooltip on the left
						if($this.offset().left + $this.outerWidth() + $tooltip.outerWidth() < $('BODY').outerWidth() && $this.offset().left - $tooltip.outerWidth() < 0){
							// but can't fit to the right
							$tooltip.attr('class','right side').css({
								left: $this.offset().left + $this.outerWidth() + 'px',
								top: $this.offset().top + 'px'
							});
						} else if($this.offset().left + $this.outerWidth() + $tooltip.outerWidth() > $('BODY').outerWidth() && $this.offset().left - $tooltip.outerWidth() < 0){
							// but can't fit to the left either
							tmp = $('BODY').outerWidth() - ($this.offset().left + $tooltip.outerWidth()) - 15;
							if(tmp < 15){
								tmp = $this.offset().left + tmp;
							} else {
								tmp = $this.offset().left;
							}
							$tooltip.attr('class','left top').css({
								left: tmp + 'px',
								top: $this.offset().top - $tooltip.outerHeight() + 'px'
							});
							$('#tooltip-arrow').css('marginLeft', $this.offset().left - tmp);
						} else {
							// can fit
							$tooltip.attr('class','left side').css({
								left: $this.offset().left - $tooltip.outerWidth() + 'px',
								top: $this.offset().top + 'px'
							});
						}
                    } else if($this.hasClass('showtooltip-dark')){
						if( ($this.offset().left + $tooltip.outerWidth() - $(document).scrollLeft()) > $('BODY').outerWidth()){
							// does not fit in viewport
                            tmp = $('BODY').outerWidth() - ($this.offset().left + $tooltip.outerWidth()) - 15;                           
							if(tmp < 15){
								tmp = $this.offset().left + tmp;
							} else {
								tmp = $this.offset().left;
							}
							$tooltip.attr('class','right top dark').css({
								left: ($this.offset().left - $tooltip.outerWidth()) + 40 + 'px',
								top: $this.offset().top - $tooltip.outerHeight() + 'px'
							});
							$('#tooltip-arrow').css('right', 22);
                        }                        
                        else {
							$tooltip.attr('class','left top dark').css({
								left: $this.offset().left - 40 + 'px',
								top: $this.offset().top - $tooltip.outerHeight() + 'px'
                            });                           
						}
					}
                    
                    else {
						if( ($this.offset().left + $tooltip.outerWidth() - $(document).scrollLeft()) > $('BODY').outerWidth()){
							// does not fit in viewport
							tmp = $('BODY').outerWidth() - ($this.offset().left + $tooltip.outerWidth()) - 15;
							if(tmp < 15){
								tmp = $this.offset().left + tmp;
							} else {
								tmp = $this.offset().left;
							}
							$tooltip.attr('class','right top').css({
								left: tmp + 'px',
								top: $this.offset().top - $tooltip.outerHeight() + 'px'
							});
							$('#tooltip-arrow').css('marginLeft', $this.offset().left - tmp);
						} else if( fit < 0 ){
							$tooltip.css({
								left: $this.offset().left + fit + 'px',
								top: $this.offset().top - $tooltip.outerHeight() + 'px'
							});
						} else {
							$tooltip.attr('class','left top').css({
								left: $this.offset().left + 'px',
								top: $this.offset().top - $tooltip.outerHeight() + 'px'
							});
						}
					}
				}
                if ($this.closest('.select01special').length > 0) {
                    $tooltip.attr('class','left bottom').css({
                        left: $this.offset().left + 'px',
                        top: $this.offset().top + $tooltip.outerHeight() + 'px'
                    });
                }
				$('BODY>DIV:first').one('mouseleave.tooltip', function (e) {
					$this.trigger('mouseleave.tooltip');
				});
			});
			this.bind('mouseleave.tooltip', function(e){
				$('BODY>DIV:first').unbind('mouseup.tooltip');
				$tooltip.css({left: '-1000px', top: '-1000px', width: ''});
				$('#tooltip-arrow').css('marginLeft','');
				$('#tooltip-inner').html(locales.simpleloader);
			});
		}
	});
})(jQuery);

/*
 * jQuery UI Touch Punch 0.2.2
 *
 * Copyright 2011, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */

 (function(b){b.support.touch="ontouchend" in document;if(!b.support.touch){return;}var c=b.ui.mouse.prototype,e=c._mouseInit,a;function d(g,h){if(g.originalEvent.touches.length>1){return;}g.preventDefault();var i=g.originalEvent.changedTouches[0],f=document.createEvent("MouseEvents");f.initMouseEvent(h,true,true,window,1,i.screenX,i.screenY,i.clientX,i.clientY,false,false,false,false,0,null);g.target.dispatchEvent(f);}c._touchStart=function(g){var f=this;if(a||!f._mouseCapture(g.originalEvent.changedTouches[0])){return;}a=true;f._touchMoved=false;d(g,"mouseover");d(g,"mousemove");d(g,"mousedown");};c._touchMove=function(f){if(!a){return;}this._touchMoved=true;d(f,"mousemove");};c._touchEnd=function(f){if(!a){return;}d(f,"mouseup");d(f,"mouseout");if(!this._touchMoved){d(f,"click");}a=false;};c._mouseInit=function(){var f=this;f.element.bind("touchstart",b.proxy(f,"_touchStart")).bind("touchmove",b.proxy(f,"_touchMove")).bind("touchend",b.proxy(f,"_touchEnd"));e.call(f);};})(jQuery);

/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/* NB modified! */

window.matchMedia = window.matchMedia || (function (doc, undefined) {
	var docElem = doc.documentElement,
		refNode = docElem.firstElementChild || docElem.firstChild,
		// fakeBody required for <FF4 when executed in <head>
		fakeBody = doc.createElement('body'),
		div = doc.createElement('div');
	div.id = 'mq-test-1';
	div.style.cssText = "position:absolute;top:-100em";
	fakeBody.style.background = "none";
	fakeBody.appendChild(div);
	var mqRun = function (mq) {
		div.innerHTML = '&shy;<style media="' + mq + '"> #mq-test-1 { width: 42px; }</style>';
		docElem.insertBefore(fakeBody, refNode);
		bool = div.offsetWidth === 42;
		docElem.removeChild(fakeBody);
		return {
			matches: bool,
			media: mq
		};
	},
	getEmValue = function () {
		var ret,
		body = docElem.body,
			fakeUsed = false;
		div.style.cssText = "position:absolute;font-size:1em;width:1em";
		if (!body) {
			body = fakeUsed = doc.createElement("body");
			body.style.background = "none";
		}
		body.appendChild(div);
		docElem.insertBefore(body, docElem.firstChild);
		if (fakeUsed) {
			docElem.removeChild(body);
		} else {
			body.removeChild(div);
		}
		//also update eminpx before returning
		ret = eminpx = parseFloat(div.offsetWidth);
		return ret;
	},
	//cached container for 1em value, populated the first time it's needed
	eminpx,
	// verify that we have support for a simple media query
	mqSupport = mqRun('(min-width: 0px)').matches;
	return function (mq) {
		if (mqSupport) {
			return mqRun(mq);
		} else {
			var min = mq.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/) && parseFloat(RegExp.$1) + (RegExp.$2 || ""),
				max = mq.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/) && parseFloat(RegExp.$1) + (RegExp.$2 || ""),
				minnull = min === null,
				maxnull = max === null,
				currWidth = $('BODY').outerWidth(),
				em = 'em';

			if ( !! min) {
				min = parseFloat(min) * (min.indexOf(em) > -1 ? (eminpx || getEmValue()) : 1);
			}
			if ( !! max) {
				max = parseFloat(max) * (max.indexOf(em) > -1 ? (eminpx || getEmValue()) : 1);
			}
			bool = (!minnull || !maxnull) && (minnull || currWidth >= min) && (maxnull || currWidth <= max);
			return {
				matches: bool,
				media: mq
			};
		}
	};
}(document));

// indexOf support for old IE

/*! Respond.js v1.1.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs  */
/* NB! Modified */

(function(win){

	'use strict';

	//exposed namespace
	var respond = {};
	win.respond = respond;

	//define update even in native-mq-supporting browsers, to avoid errors
	respond.update = function(){};

	//expose media query support flag for external use
	try {
		respond.mediaQueriesSupported = win.matchMedia && win.parent.matchMedia("only all").matches;
	} catch(e){
		respond.mediaQueriesSupported = false;
	}

	//if media queries are supported, exit here
	if( respond.mediaQueriesSupported || $.IbCookie('responsive') === 'desktop' || parseUri(document.location.href).queryKey.responsive === 'false' || window.self !== window.top){
		return;
	}

	//define vars
	var doc = win.document,
		docElem = doc.documentElement,
		mediastyles = [],
		rules = [],
		appendedEls = [],
		parsedSheets = {},
		resizeThrottle = 30,
		head = doc.getElementsByTagName( "head" )[0] || docElem,
		base = doc.getElementsByTagName( "base" )[0],
		links = head.getElementsByTagName( "link" ),
		requestQueue = [],

		//loop stylesheets, send text content to translate
		ripCSS = function(){

			for( var i = 0; i < links.length; i++ ){
				var sheet = links[ i ],
				href = sheet.href,
				media = sheet.media,
				isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";

				//only links plz and prevent re-parsing
				if( !!href && isCSS && !parsedSheets[ href ] ){
					// selectivizr exposes css through the rawCssText expando
					if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
						translate( sheet.styleSheet.rawCssText, href, media);
						parsedSheets[ href ] = true;
					} else {
						if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base) ||
							href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){
							requestQueue.push( {
								href: href,
								media: media
							} );
						}
					}
				}
			}
			makeRequests();
		},

		//recurse through request queue, get css text
		makeRequests	= function(){
			if( requestQueue.length ){
				var thisRequest = requestQueue.shift();

				ajax( thisRequest.href, function( styles ){
					translate( styles, thisRequest.href, thisRequest.media );
					parsedSheets[ thisRequest.href ] = true;

					// by wrapping recursive function call in setTimeout
					// we prevent "Stack overflow" error in IE7
					setTimeout(function(){ makeRequests(); },0);
				} );
			}
		},

		//find media blocks in css text, convert to style blocks
		translate = function( styles, href, media ){
			var qs = styles.match(  /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ),
				ql = qs && qs.length || 0;

			//try to get CSS path
			href = href.substring( 0, href.lastIndexOf( "/" ) );

			var repUrls	= function( css ){
					return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" );
				},
				useMedia = !ql && media;

			//if path exists, tack on trailing slash
			if( href.length ){ href += "/"; }

			//if no internal queries exist, but media attr does, use that
			//note: this currently lacks support for situations where a media attr is specified on a link AND
				//its associated stylesheet has internal CSS media queries.
				//In those cases, the media attribute will currently be ignored.
			if( useMedia ){
				ql = 1;
			}

			for( var i = 0; i < ql; i++ ){
				var fullq, thisq, eachq, eql;

				//media attr
				if( useMedia ){
					fullq = media;
					rules.push( repUrls( styles ) );
				}
				//parse for styles
				else{
					fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1;
					rules.push( RegExp.$2 && repUrls( RegExp.$2 ) );
				}

				eachq = fullq.split( "," );
				eql	= eachq.length;

				for( var j = 0; j < eql; j++ ){
					thisq = eachq[ j ];
					mediastyles.push( {
						media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all",
						rules : rules.length - 1,
						hasquery : thisq.indexOf("(") > -1,
						minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
						maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" )
					} );
				}
			}

			applyMedia();
		},

		lastCall,

		resizeDefer,

		// returns the value of 1em in pixels
		getEmValue = function() {
			var ret,
				div = doc.createElement('div'),
				body = doc.body,
				fakeUsed = false;

			div.style.cssText = "position:absolute;font-size:1em;width:1em";

			if( !body ){
				body = fakeUsed = doc.createElement( "body" );
				body.style.background = "none";
			}

			body.appendChild( div );

			docElem.insertBefore( body, docElem.firstChild );

			ret = div.offsetWidth;

			if( fakeUsed ){
				docElem.removeChild( body );
			}
			else {
				body.removeChild( div );
			}

			//also update eminpx before returning
			ret = eminpx = parseFloat(ret);

			return ret;
		},

		//cached container for 1em value, populated the first time it's needed
		eminpx,

		//enable/disable styles
		applyMedia = function( fromResize ){
			var name = "clientWidth",
				docElemProp = docElem[ name ],
				currWidth = (doc.compatMode === "CSS1Compat" && docElemProp) || doc.body[ name ] || docElemProp,
				styleBlocks	= {},
				lastLink = links[ links.length-1 ],
				now = (new Date()).getTime();

			//throttle resize calls
			if( fromResize && lastCall && now - lastCall < resizeThrottle ){
				clearTimeout( resizeDefer );
				resizeDefer = setTimeout( applyMedia, resizeThrottle );
				return;
			}
			else {
				lastCall = now;
			}

			for( var i in mediastyles ){
				if( mediastyles.hasOwnProperty( i ) ){
					var thisstyle = mediastyles[ i ],
						min = thisstyle.minw,
						max = thisstyle.maxw,
						minnull = min === null,
						maxnull = max === null,
						em = "em";

					if( !!min ){
						min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
					}
					if( !!max ){
						max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
					}

					// if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
					if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){
						if( !styleBlocks[ thisstyle.media ] ){
							styleBlocks[ thisstyle.media ] = [];
						}
						styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] );
					}
				}
			}

			//remove any existing respond style element(s)
			for( var j in appendedEls ){
				if( appendedEls.hasOwnProperty( j ) ){
					if( appendedEls[ j ] && appendedEls[ j ].parentNode === head ){
						head.removeChild( appendedEls[ j ] );
					}
				}
			}

			//inject active styles, grouped by media type
			for( var k in styleBlocks ){
				if( styleBlocks.hasOwnProperty( k ) ){
					var ss = doc.createElement( "style" ),
						css = styleBlocks[ k ].join( "\n" );

					ss.type = "text/css";
					ss.media = k;

					//originally, ss was appended to a documentFragment and sheets were appended in bulk.
					//this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
					head.insertBefore( ss, lastLink.nextSibling );

					if ( ss.styleSheet ){
						ss.styleSheet.cssText = css;
					}
					else {
						ss.appendChild( doc.createTextNode( css ) );
					}

					//push to appendedEls to track for later removal
					appendedEls.push( ss );
				}
			}
		},
		//tweaked Ajax functions from Quirksmode
		ajax = function( url, callback ) {
			var req = xmlHttp();
			if (!req){
				return;
			}
			req.open( "GET", url, true );
			req.onreadystatechange = function () {
				if ( req.readyState !== 4 || req.status !== 200 && req.status !== 304 ){
					return;
				}
				callback( req.responseText );
			};
			if ( req.readyState === 4 ){
				return;
			}
			req.send( null );
		},
		//define ajax obj
		xmlHttp = (function() {
			var xmlhttpmethod = false;
			try {
				xmlhttpmethod = new win.XMLHttpRequest();
			}
			catch( e ){
				xmlhttpmethod = new win.ActiveXObject( "Microsoft.XMLHTTP" );
			}
			return function(){
				return xmlhttpmethod;
			};
		})();

	//translate CSS
	ripCSS();

	//expose update for re-running respond later on
	respond.update = ripCSS;

	//adjust on resize
	function callMedia(){
		applyMedia( true );
		$(document).trigger('respondUpdate', 'call media');
	}
	if( win.addEventListener ){
		win.addEventListener( "resize", callMedia, false );
	}
	else if( win.attachEvent ){
		win.attachEvent( "onresize", callMedia );
	}
})(this);

// Dummy data generation

function generateDummyData (amount) {
	'use strict';
	var d = [1 + Math.round((Math.round(Math.random() * Math.random() * Math.random() * Math.random() * Math.random() * Math.random() * 100) / 100) * 10000) / 10000],
		i,
		tmp;
	for (i = 0; i < amount; i = i + 1) {
		tmp = Math.round((d[d.length - 1] + Math.round(Math.random() * 100 * (Math.random() < 0.5 ? -1 : 1)) / 10000) * 10000) / 10000;
		d.push(tmp);
	}
	return d;
}
function generateDummyData2 (amount, amplitude, baseline) {
	var d = [baseline]
	for (var i=0; i < amount; i++){
		rnd = Math.round(Math.random() * 1000) / 1000; // generate number, 0 <= x < 1.0
		change_percent = 2 * amplitude * rnd;
		if (change_percent > amplitude) {
			change_percent -= (2 * amplitude);
        }
		change_amount = d[d.length-1] * change_percent + ((rnd / 10) * amplitude);
		d.push(Math.round((d[d.length-1] + change_amount) * 10000) / 10000);
	}
	return d;
}

// Highcharts fixes

function fixHighchartsTouch () {
    Highcharts.Chart.prototype.callbacks.push(function(chart) {
      var hasTouch = document.documentElement.ontouchstart !== undefined,
          mouseTracker = chart.pointer,
          container = chart.container,
          mouseMove;

      mouseMove = function (e) {

        // let the system handle multitouch operations like two finger scroll
        // and pinching
        if (e && e.touches && e.touches.length > 1) {
          return;
        }

        if (hasTouch) {
            if (e && e.touches && e.touches.length > 1) {
                mouseTracker.onContainerTouchMove(e);
            }
            return;
        } else {
          mouseTracker.onContainerMouseMove(e);
        }
      };

      click = function (e) {
        if (hasTouch) {
            mouseTracker.onContainerMouseMove(e);
        }
        mouseTracker.onContainerClick(e);
      };

      container.onmousemove = container.ontouchstart = container.ontouchmove = mouseMove;
      container.onclick = click;
    });
    if (window.Highcharts.StockChart) {
        var orgHighchartsRangeSelectorPrototypeRender = Highcharts.RangeSelector.prototype.render;
        Highcharts.RangeSelector.prototype.render = function (min, max) {
            orgHighchartsRangeSelectorPrototypeRender.apply(this, [min, max]);
            var leftPosition = 20,
                topPosition = this.chart.plotTop - 38,
                space = 2;
            this.zoomText.attr({
                x: 10,
                y: topPosition + 15
            });
            leftPosition += this.zoomText.getBBox().width;
            for (var i = 0; i < this.buttons.length; i++) {
                this.buttons[i].attr({
                    x: leftPosition,
                    y: topPosition
                });
                leftPosition += this.buttons[i].width + space;
            }
        };
    }
}

// Table detail rows expanding
function initContent(cont) {
    'use strict';

    var actioncontext,
        ch,
        tmp01 = '';
    if (cont) {
        actioncontext = cont;
    } else {
        actioncontext = $(contentholders);
    }
    ch = actioncontext;

    // List clearing

    $('.list02in2col:not(.noclearer)', actioncontext).each(function () { $(this).find('LI.item:not(.clearer)').filter(function (index) { return (index % 2 === 0) && index > 1; }).before('<li class="item clearer" />'); });
    $('.list02in3col:not(.noclearer), DIV.sitemap > UL', actioncontext).each(function () { $(this).find('> LI.item:not(.clearer)').filter(function (index) { return (index % 3 === 0) && index > 2; }).before('<li class="item clearer" />'); });
    $('.list02in4col:not(.noclearer)', actioncontext).each(function () { $(this).find('LI.item:not(.clearer)').filter(function (index) { return (index % 4 === 0) && index > 3; }).before('<li class="item clearer" />'); });

    // Expandable tables

    $('TR.details:not(.init1)', actioncontext).addClass('init1').each(function (a, b) {
        if ($(b).closest('.crmform').length > 0) { return; }
        if (!$(b).is('TR[class*="level"]')) {
            $(b).find('> TD').addClass('container');
        }
        $(b).prevAll('TR:not(.info):first')
            .data('detail_created', true)
            .data('detail_created_manually', true)
            .addClass($(b).hasClass('hidden') ? 'closed' : 'open')
            .find('TD:not(:has(A:not(.help01), :input), .sparkline01, .sparkline02):first').addClass('expandable').end()
            .on('click', 'TD:not(:has(A:not(.help01), :input), .sparkline01, .sparkline02)', function (e) {
                e.preventDefault();
                e.stopPropagation();
                var loader = $('<div class="rowloader01" />'),
                    owner = $(b).prev('TR'),
                    ev1,
                    ev2,
                    t = $(this),
                    r = t.closest('TR');
                if ($(this).closest('TR').is('[data-customevent]')) {
                    ev1 = function (e) {
                        loader.css({
                            left: owner.position().left,
                            top: owner.position().top + parseInt(owner.find('td:first').css('borderTopWidth'), 10),
                            width: owner.width(),
                            height: owner.height() - 1
                        });
                    };
                    ev1();
                    $(window).on('resize rowtoggle', ev1);

                    r.bind('customeventDone', function () {
                        loader.remove();
                        $(window).unbind('resize', ev1);
                        r.unbind('customeventDone').removeAttr('data-customevent');
                        t.click();
                        initContent($(b));
                    });
                    r.trigger($(this).closest('TR').attr('data-customevent'));
                    $(b).closest('table').after(loader);
                } else {
                    if (typeof $(b).attr('data-details') === 'undefined') {
                        if ($(this).closest('TR').find('TD:visible').is('.expandable, .mobile-expandable')) {
                            r.toggleClass('open').toggleClass('closed');
                            $(b).toggleClass('hidden');
                        }
                    } else {
                        ev1 = function (e) {

                            loader.css({
                                left: owner.position().left,
                                top: owner.position().top + parseInt(owner.find('td:first').css('borderTopWidth'), 10),
                                width: owner.width(),
                                height: owner.height() - 1
                            });
                        };
                        ev1();
                        $(window).on('resize rowtoggle', ev1);
                        ev2 = $.ajax({
                            url: $(b).attr('data-details'),
                            success: function (ajaxresponse) {
                                var target = $(b).find('TD:first');
                                loader.remove();
                                $(window).unbind('resize', ev1);
                                target.html(ajaxresponse);
                                initContent(target);
                                $(b).removeAttr('data-details');
                                t.click();
                            },
                            error: function (a, b, c) {
                                loader.remove();
                                $(window).unbind('resize', ev1);
                                if (b !== 'abort') {
                                    tb_show('', '#TB_error?width=300&amp;height=300&amp;autoscale=1', c);
                                }
                                return false;
                            }
                        });
                        loader.click(function (e) {
                            loader.remove();
                            ev2.abort();
                            $(window).unbind('resize', ev1);
                        });
                        $(b).closest('table').after(loader);
                    }
                }
                $(window).trigger('rowtoggle');
                if (ri !== false) {
                    framed();
                }
            });
    });

    $('TR[class*="level"]:not(.init2)', actioncontext).addClass('init2').each(function (a, b) {
        if ($(b).closest('.crmform').length > 0) {
            return;
        }
        var currentlevel = parseInt($(b).attr('class').split(' ')[0].slice(5)[0], 10),
            nextitems = $(b).nextUntil('TR.level' + currentlevel + ', TR.total').filter('TR.level' + (currentlevel + 1));
        if (nextitems.length > 0) {
            $(b).addClass(nextitems.first().hasClass('hidden') ? 'closed' : 'open').find('TD:not(:has(A:not(.help01), :input), .sparkline01, .sparkline02):first').addClass('expandable');
            $(b).click(function () {
                if ($(b).hasClass('open')) {
                    $(b).removeClass('open').nextUntil('TR:regex(class,level[0-' + currentlevel + '])').addClass('hidden').removeClass('open');
                } else {
                    $(b).addClass('open').nextUntil('TR:regex(class,level[0-' + currentlevel + '])').filter('TR.level' + (currentlevel + 1)).removeClass('hidden');
                }
            })
                .find('A').click(function (e) {
                    e.preventDefault();
                    document.location = $(b).attr('href');
                });
        } else {
            $(b).find('TD:first-child:not(.input)').addClass('level');
        }
    });

    $('TR.mobile-clickable[data-url] TD:not(init3)', actioncontext).each(function (a, b) {
        $(b).addClass('init3').click(function (e) {
            if (getMedia() === 'narrow') {
                e.preventDefault();
                document.location.href = $(this).closest('[data-url]').attr('data-url');
            }
        });
    });

    // Draggable table

    if ($('TABLE.draggable').length > 0) {
        $('TABLE.draggable:not(.transmute):not(.init22)', actioncontext).addClass('init22').each(function (a, b) {
            $(b)
                .sortable({
                    items: '> TBODY.sortable',
                    forcePlaceholderSize: true,
                    axis: 'y',
                    helper: function (e, ui) {
                        ui.find('td').each(function() {
                            $(this).width($(this).width());
                        });
                        return ui;
                    },
                    start: function (e, ui) {
                        ui.item.contents().clone(false).appendTo(ui.placeholder);
                    },
                    handle: '.sorthandler'
                })
            ;
        });

    }

    // Sortable tables

    if ($('TABLE.sortable').length > 0) {
        require(['tablesorter'], function () {
            $('TABLE.sortable:not(.init4)', actioncontext).addClass('init4').each(function (a, b) {
                $(b).tablesorter({
                    decimal: ',',
                    debug: false,
                    cssChildRow: 'details',
                    dateFormat: 'dd.mm.yy',
                    cssHeader: 'sortable',
                    textExtraction: function (node) {
                        return $(node).text().replace(' ', '');
                    }
                }).find('TH.sortable').wrapInner('<span class="sorter" />');
            });
        });
    }

    // Table hovers

    if (!isBadIE) {
        $('TABLE:not(.crmform):not(.form):has(TD[colspan],TH[colspan],TD[rowspan],TH[rowspan]):not(.init5)', actioncontext).addClass('init5').each(function (a, b) {
            $(b).tableHover({ cellClass: 'hover' });
        });
    }

    // Transmute tables

    if ($('TABLE.transmute').length > 0) {
        require(['footable'], function () {
            // Tables with inputs

            $('TABLE.transmute:not(.autoexpand,.ignoreinputs):has(INPUT, SELECT):not(.init6)', actioncontext).addClass('init6').each(function (a, b) {
                $(b).footable({
                        delay: 10,
                        calculateWidthOverride: function ($table, info) {
                            info.width = info.viewportWidth;
                            return info;
                        },
                        breakpoints: {
                            phone: 749
                        },
                        addRowToggle: false,
                        classes: {
                            main: 'footable-inputs',
                            loading: 'footable-loading',
                            loaded: 'footable-loaded',
                            toggle: 'footable-toggle',
                            disabled: 'footable-disabled',
                            detail: 'details open',
                            detailCell: 'container form01footable',
                            detailInner: 'form01',
                            detailInnerRow: 'row clear',
                            detailInnerGroup: 'footable-row-detail-group',
                            detailInnerName: 'label',
                            detailInnerValue: 'items',
                            detailShow: 'footable-detail-show'
                        }
                    })
                    .bind('footable_breakpoint', function () {
                        $(this).find('TR:has(TD > INPUT:checked):not(.footable-detail-show)').trigger('footable_toggle_row');
                    })
                    .bind('footable_row_expanded', function (e) {
                        $(e.row).find('INPUT:checkbox, INPUT:radio').prop('checked', true);
                        if ($(e.row).find('INPUT:radio').length > 0) {
                            $(e.row).closest('TABLE').find('TR.footable-detail-show:has(:radio:not(:checked))').trigger('footable_toggle_row');
                        }
                    })
                    .bind('footable_row_collapsed', function (e) {
                        $(e.row).find('INPUT:checkbox, INPUT:radio').prop('checked', false);
                    })
                    .find('INPUT:checkbox, INPUT:radio, INPUT:text').on('click', function () {
                        $(this).closest('TD').trigger('click');
                        if ( $(this).find('INPUT:text') ) {
                            $(this).trigger("focus");
                        }
                    }).end()
                    .sortable({
                        items: '> TBODY.sortable',
                        forcePlaceholderSize: true,
                        axis: 'y',
                        helper: function (e, ui) {
                            ui.find('td').each(function() {
                                $(this).width($(this).width());
                            });
                            return ui;
                        },
                        sort: function(event, ui) {
                            var $target = $(event.target);
                            if (!/html|body/i.test($target.offsetParent()[0].tagName)) {
                                var top = event.pageY - $target.offsetParent().offset().top - (ui.helper.outerHeight(true) / 2);
                                ui.helper.css({'top' : top + 'px'});
                            }
                        },
                        start: function (e, ui) {
                            ui.item.contents().clone(false).appendTo(ui.placeholder);
                        }
                    });
            });

            // Tables without inputs

            $('TABLE.transmute:not(.autoexpand):not(:has(INPUT, SELECT)):not(.init7), TABLE.transmute.ignoreinputs:not(.init7)', actioncontext).addClass('init7').each(function (a, b){
                $(b).footable({
                    delay: 10,
                    calculateWidthOverride: function ($table, info) {
                        info.width = info.viewportWidth;
                        return info;
                    },
                    breakpoints: {
                        phone: 749
                    },
                    addRowToggle: false,
                    classes: {
                        main: 'footable',
                        loading: 'footable-loading',
                        loaded: 'footable-loaded',
                        toggle: 'footable-toggle',
                        disabled: 'footable-disabled',
                        detail: 'details open',
                        detailCell: 'container form01footable',
                        detailInner: 'detailcols',
                        detailInnerRow: 'detailcol clear',
                        detailInnerGroup: 'footable-row-detail-group',
                        detailInnerName: 'label',
                        detailInnerValue: 'items',
                        detailShow: 'open'
                    }
                });
            });

            // Autoexpanding tables

            $('TABLE.transmute.autoexpand:not(.init8)', actioncontext).addClass('init8').each(function (a, b) {
                $(b).footable({
                        delay: 10,
                        calculateWidthOverride: function ($table, info) {
                            info.width = info.viewportWidth;
                            return info;
                        },
                        breakpoints: {
                            phone: 749
                        },
                        addRowToggle: false,
                        classes: {
                            main: 'footable-autoexpand',
                            loading: 'footable-loading',
                            loaded: 'footable-loaded',
                            toggle: 'footable-toggle',
                            disabled: 'footable-disabled',
                            detail: 'details open',
                            detailCell: 'container form01footable',
                            detailInner: 'form01',
                            detailInnerRow: 'row clear',
                            detailInnerGroup: 'footable-row-detail-group',
                            detailInnerName: 'label',
                            detailInnerValue: 'items',
                            detailShow: 'footable-detail-show'
                        }
                    })
                    .bind('footable_breakpoint', function () {
                        $(this).trigger('footable_expand_all');
                    })
                    .bind('footable_row_collapsed', function () {
                        $(this).trigger('footable_expand_all');
                    })
                    .trigger('footable_expand_all');
            });
        });
    }

    // Checkable tables highlight
    $('TABLE.checkhighlight', actioncontext).each(function(a, b){
        $(b).on('change', 'INPUT[type="checkbox"]', function () {
            if ($(this).is(':checked')) {
                $(this).closest('TR').addClass('highlight');
            } else {
                $(this).closest('TR').removeClass('highlight');
            }
        });
        $(b).find('INPUT[type="checkbox"]').trigger('change');
    });

    // Datepicker

    if ($('INPUT.pickdate').length > 0) {
        require(['jquery.extensions.datepicker'], function () {
            $('INPUT.pickdate:not(.init9)').addClass('init9', actioncontext).each(function (a, b) {
                $(b).DatePicker({
                    current: $(b).val(),
                    date: $(b).val(),
                    format: 'd.m.Y',
                    calendars: 1,
                    eventName: '',
                    mode: 'single',
                    position: 'bottom',
                    setmargin: '2px 0 0 0',
                    onShow: function () {
                        if (isNaN(Date.parse($(b).DatePickerParseDate($(b).val().trim())))) {
                            $(b).DatePickerSetDate($('#' + $(b).data('datepickerId')).data('datepicker').current);
                        } else {
                            $(b).DatePickerSetDate($(b).val());
                            $('#' + $(b).data('datepickerId')).data('datepicker').current = $(b).DatePickerGetDate();
                        }
                    },
                    onBeforeShow: function () {
                        if (isNaN(Date.parse($(b).DatePickerParseDate($(b).val().trim())))) {
                            $(b).DatePickerSetDate($('#' + $(b).data('datepickerId')).data('datepicker').current);
                        } else {
                            $(b).DatePickerSetDate($(b).val());
                            $('#' + $(b).data('datepickerId')).data('datepicker').current = $(b).DatePickerGetDate();
                        }
                    },
                    onChange: function (formated) {
                        $($(this).data('datepicker').el).val(formated).DatePickerHide();
                        $($(this).data('datepicker').el).change().blur();
                    },
                    start: 0
                });
                $(b).bind('keydown keyup keypress', function () {
                    if (isNaN(Date.parse($(b).DatePickerParseDate($(b).val().trim())))) {
                        $(b).DatePickerSetDate($('#' + $(b).data('datepickerId')).data('datepicker').current);
                    } else {
                        $(b).DatePickerSetDate($(b).val());
                        $('#' + $(b).data('datepickerId')).data('datepicker').current = $(b).DatePickerGetDate();
                        $(b).DatePickerSetDate($(b).val());
                    }
                });
                if ($(this).closest('.pickdatewrapper').length === 0) {
                    $(this).wrap('<span class="pickdatewrapper"></span>');
                    var tmp01 = $('<a href="#" tabindex="-1"><img src="/ipank/resp/img/ico_calendar.png" alt="' + locales.opencalendar + '" title="' + locales.opencalendar + '" /></a>');
                    tmp01.click(function (e) {
                        e.preventDefault();
                        var t = $(this).closest('SPAN').find('INPUT.pickdate');
                        t.DatePickerShow();
                    });
                    $(this).after(tmp01);
                }
            });
        });
    }

    // Forms

    $('.form01 .row:not(.init10)', actioncontext).addClass('init10').each(function (a, b) {
        $(b)
            .on('focus', ':input:not(.search)', function () { $(this).closest('.row').addClass('focus'); })
            .on('blur', ':input:not(.search)', function () { $(this).closest('.row').removeClass('focus'); });
    });

    // Expansion blocks and tabs

    $('DL.toggle_slider DT A:not(.init11)', actioncontext).addClass('init11').each(function (a, b) {
        $(b).click(function (e) {
            e.preventDefault();
            $(this).toggleClass('open').closest('DT').nextUntil('DT').slideToggle(200);
        });
    });

    $('.tab-content .tab-header:not(.init17)', actioncontext).addClass('init17').bind('open', function () {
        $(this).closest('.tab-content').toggleClass('tab-content-mobile-open');
        $(window).resize();
        $(document).trigger('respondUpdate');
    });

    // Tooltips

    $('.showtooltip:not(.init12)', actioncontext).addClass('init12').tooltip();
    $('.showtooltip:not(.init12b)', $('.header03')).addClass('init12b').tooltip();

    // Multiple option buttons

    $('UL.actions01 LI.export:has(UL) UL:not(.init13)', actioncontext).addClass('init13').click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        $('BODY').click();
        var items = $(this).contents().clone(true),
            drop = $('<ul id="drop01"></ul>'),
            t = $(this);
        drop
            .click(function (e) {
                e.stopPropagation();
            })
            .append(items)
            .appendTo('BODY')
            .css({
                top: t.offset().top + t.outerHeight(),
                left: t.offset().left + t.outerWidth() - drop.outerWidth()
            });
        $('BODY').bind('click.drop', function () {
            drop.remove();
            $('BODY').unbind('click.drop');
            $(window).unbind('resize.drop');
        });
        $(window).bind('resize.drop', function () {
            drop.css({
                top: t.offset().top + t.outerHeight(),
                left: t.offset().left + t.outerWidth() - drop.outerWidth()
            });
        });
    });

    // Checkboxes list with option to hide/show unchecked items

    $('UL.checkboxes:has(LI.showall):not(.init14)', actioncontext).addClass('init14').each(function (a, b) {
        var $el = $(b);
        $('LI.showall SPAN.no', $el).text($el.find('INPUT[type=checkbox]:checked').length);
        if ($('SPAN.no:visible', $el).length > 0) {
            $el.find('INPUT[type=checkbox]:not(:checked)').closest('LI').addClass('hidden');
        }
        $('LI.showall A', $el).click(function () {
            $('LI.showall SPAN, LI:has(INPUT[type=checkbox]:not(:checked))', $el).toggleClass('hidden');
            return false;
        });
        $('INPUT[type=checkbox]', $el).on('click', function () {
            $('LI.showall SPAN.no', $el).text($el.find('INPUT[type=checkbox]:checked').length);
        });
    });

	// Tabs

    actioncontext.find("UL.tabs01:not(.init15), DIV.tabs01 UL:first:not(.init15)").addClass('init15').each(function (a, b) {
        var exp = $('<li class="exp"><a href="#" class="main"><span>' + locales.more + '</span></a></li>');
        if ($(b).find('> LI:not(.exp)').length > 3) {
            if ($(b).find('> LI.exp').length === 0) {
                $(b).append(exp);
            }
        }
        if($(b).hasClass('tabs02mobile')) {
            $('A', b).each(function () {
                $($(this).attr('href').substring($(this).attr('href').indexOf('#'))).addClass('enablemobile');
            });
        }
        if ($(b).find('> LI:not(.exp) A[href^="#"]').length !== 0 && !$(b).hasClass('tabs02mobile')) {
            $(b).removeClass('tabs01mobile').addClass('mobile-hide');
        }
    });

	fitTabs();
    window.setTimeout(fitTabs, 500); // Since there is no font loader

    // Fix ios keyboard opening issues with fixed elements

    if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i)) {
        $('#box00:not(.init16)')
            .addClass('init16')
            .on('focus', 'input, textarea, select', function() { $('#box00').addClass('keyboardopen'); })
            .on('blur', 'input, textarea, select', function() { $('#box00').removeClass('keyboardopen'); });
    }

    // AD sliders

    if ($('#front01:not(.init18)').length > 0) {
        $('#front01:not(.init18)').addClass('init18').each(function (a, b) {
            if ($('DIV.slide', b).length > 1) {
                $(b).after('<ul class="dots" id="front01slidedots"><li class="next"><a href="#" id="slidenext02"><span><span>►</span></span></a></li></ul><a href="#" id="slideprev"></a><a href="#" id="slidenext"></a><a href="#" id="slideclose"></a>');
                $('#slideclose').bind('click', function () {
                    if ($(b).attr('data-closeur') !== 'undefined') {
                        $.ajax({ url: $(b).attr('data-closeur') });
                    }
                    $("#box00").removeClass("hasbanner");
                    return false;
                });
                $('#slideprev').bind('click', function () {
                    if ($('DIV.slide:animated', b).length === 0) {
                        if ($('#front01slidedots A.active').closest('LI').prevAll('LI:not(.next)').length > 0) {
                            $('#front01slidedots A.active').closest('LI').prev('LI:not(.next)').find('A').trigger('click');
                        } else {
                            $('#front01slidedots LI:not(.next):last A').trigger('click');
                        }
                    }
                    return false;
                });
                $('#slidenext').bind('click', function () {
                    if ($('DIV.slide:animated', b).length === 0) {
                        if ($('#front01slidedots A.active').closest('LI').nextAll('LI:not(.next)').length > 0) {
                            $('#front01slidedots A.active').closest('LI').next('LI:not(.next)').find('A').trigger('click');
                        } else {
                            $('#front01slidedots LI:not(.next):first A').trigger('click');
                        }
                    }
                    return false;
                });
                $('#slidenext02').bind('click', function () {
                    if ($('DIV.slide:animated', b).length === 0) {
                        if ($('#front01slidedots A.active').closest('LI').nextAll('LI:not(.next)').length > 0) {
                            $('#front01slidedots A.active').closest('LI').next('LI:not(.next)').find('A').trigger('click');
                        } else {
                            $('#front01slidedots LI:not(.next):first A').trigger('click');
                        }
                    }
                    return false;
                });
                $('#slidenext').click();
                require(['swipe'], function () {
                    $('#header02 DIV.b').swipe({
                        swipeLeft: function (event, direction, distance, duration, fingerCount) {
                            $('#slidenext').trigger('click');
                        },
                        swipeRight: function (event, direction, distance, duration, fingerCount) {
                            $('#slideprev').trigger('click');
                        }
                    });
                });
                $('DIV.slide', b).each(function (a) { tmp01 += '<li><a href="#"><span><span>' + (a + 1) + '</span></span></a></li>'; });
                $('#front01slidedots').prepend(tmp01);
                $('#front01slidedots LI:not(.next) A:first').addClass('active');
                $('#front01slidedots LI:not(.next) A').click(function () {
                    if (!$(this).hasClass('active') && $('DIV.slide:animated', b).length === 0) {
                        $(this).closest('UL').find('A.active').removeClass('active');
                        $(this).addClass('active');
                        var tmp02 = $('DIV.slide:not(.hidden)', b);
                        $(tmp02).css({ zIndex: '1' });
                        $('DIV.slide:eq(' + $(this).parents('LI').prevAll('LI:not(.next)').length + ')', b)
                            .removeClass('hidden')
                            .css({ zIndex: '2', opacity: 0, position: 'absolute' })
                            .animate({ opacity: 1 }, { duration: 200, complete: function () {
                                $(this).css('position', 'static');
                                $(tmp02).addClass('hidden').css({ zIndex: '-1' });
                            }});
                    }
                    return false;
                });
            }
        });
    }

    // Thickbox links
    tb_init('a.thickbox, area.thickbox, input.thickbox', actioncontext);
    
    // Nested sortable    
    $('.nestedsortable').sortable({
        axis: 'y',
        helper: function (e, ui) {
            ui.find('td').each(function () {
                $(this).width($(this).width());
            });
            return ui;
        },
        sort: function (event, ui) {
            var $target = $(event.target);
            if (!/html|body/i.test($target.offsetParent()[0].tagName)) {
                var top = event.pageY - $target.offsetParent().offset().top - (ui.helper.outerHeight(true) / 2);
                ui.helper.css({
                    'top': top + 'px'
                });
            }
        },
        start: function (e, ui) {
            ui.item.contents().clone(false).appendTo(ui.placeholder);
        }
    });
}

function initFrame () {
    'use strict';

     var html = $('HTML:first'),
         activetab,
         linkedtables = [],
         ch = $(contentholders);

    var responsiveCookie = $.IbCookie('responsive');
    // Responsive overrides

    if (responsiveCookie)
    	$.IbCookie('responsive', responsiveCookie); // Refresh cookie to have not duplicated in dev/test environments

    if (!responsiveCookie) {
        $.IbCookie('responsive', 'default');
        $('META[name="viewport"]').attr('content', 'initial-scale=1.0, maximum-scale=1.0, width=device-width, user-scalable=no');
        $('HTML:first').addClass('responsive');
    } else if (responsiveCookie === 'desktop' || parseUri(document.location.href).queryKey.responsive === "false") {
        $('META[name="viewport"]').attr('content', 'initial-scale=' + ($(window).width() / 1024) + ', minimum-scale=0.1, maximum-scale=10.0, width=1024, user-scalable=yes');
        $('HTML:first').addClass('nonresponsive');
        $('LINK[type="text/css"][media*=screen]').each(function (a, b) {
            'use strict';
            var max = $(b).attr('media').match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/) && parseFloat(RegExp.$1);
            $(b).data('media', $(b).attr('media')).attr('media', 'screen');
            if (max !== null && max < 1000) {
                $(b).attr('disabled', 'disabled').attr('media', 'not all');
            }
        });
        respond.update();
    } else {

        $('META[name="viewport"]').attr('content', 'initial-scale=1.0, maximum-scale=1.0, width=device-width, user-scalable=no');
    }

    // Feature tagging

    if (getMedia() === 'medium' || getMedia() === 'wide') {
        html.addClass('isdesktop');
    } else {
        html.addClass('ismobile');
    }

    if (parseUri(document.location.href).queryKey.responsive === "false") {
        html.addClass('nonresponsive-forced');
    } else {
        html.removeClass('nonresponsive-forced');
    }

    // Menus

    $(window).bind('orientationchange.menu01 resize.menu01', function () {
        if (getMedia() === 'wide' || $.IbCookie('responsive') === 'desktop') {
            fitMenu();
        }
        $('.ui-autocomplete-input').autocomplete('close');
    });

    $('#menu01 UL.menu00drop').on('click', 'A', function (e) {
        if (getMedia() === 'medium' || getMedia() === 'narrow') {
            e.preventDefault();
            e.stopPropagation();
            if ($('#menu01 UL.menu00open').length === 0) {
                var tmp = $(this).closest('UL').clone(false);
                tmp.removeAttr('class').addClass('menu00open').insertAfter($(this).closest('UL'));
            } else {
                $('#menu01 UL.menu00open').remove();
            }
        }
    });
    try {
        if (window.parent.$(window).width() >= 1000 || $.IbCookie('responsive') === 'desktop') { fitMenu(); }
    } catch (e) {}

    $('#menu01 UL.menu01').on('click mouseenter', 'LI > A.hasdrop, P > SPAN, P > A.hasdrop', function (e) {
        e.preventDefault();
        e.stopPropagation();
        if ((getMedia() === 'narrow' || getMedia() === 'medium') && e.type === 'mouseenter') { return; }
        var t = $(this);
        if (getMedia() === 'wide' || $.IbCookie('responsive') === 'desktop') {
            // Make dropdown menus
            if (t.closest('LI').is(':not(.home)')) {
                window.clearTimeout(droptimer);
                if ((e.type === 'mouseenter' && !isTouchDevice()) || (e.type === 'click' && isTouchDevice())) {
                    if (t.closest('UL.menu01').hasClass('open')) {
                        showMenu(t, e);
                    } else {
                        if (e.type === 'click') {
                            showMenu(t, e);
                        } else {
                            droptimer = window.setTimeout(function () {
                                showMenu(t, e);
                            }, 500);
                        }
                    }
                } else if (!isTouchDevice() && e.type === 'click') {
                    if (!t.closest('UL.menu01').hasClass('open')) {
                        window.clearTimeout(droptimer);
                        showMenu(t, e);
                    }
                }
            } else {
                return;
            }
        } else {
            t.closest('LI, .set').toggleClass('mob-open');
            setMobMenuSize();
        }
    });

    if (!isTouchDevice()) {
        $('#menu01 UL.menu01').on('mouseleave', function (e) {
            window.clearTimeout(droptimer);
            droptimer = window.setTimeout('hideMenu()', 250);
        });
    }

    $('P.menulink SPAN:first').bind("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        $('#box00').click();
        showMobMenu();
        window.scrollTo(0, 0);
        return false;
    });

    // Tabs and expanders

    ch.on('click', function (e) {
        var target = $(e.target).parents().andSelf(),
            t = $(),
            pos = 0;

        if (target.is('UL.tabs01 LI A, DIV.tabs01 UL:first LI A')) {
            t = target.filter('UL.tabs01 LI A, DIV.tabs01 UL:first LI A');
            if (t.closest('LI.exp').length === 0) {
                if (t.attr('href').indexOf('#') !== -1) {
                    if ($(t.attr('href').substring(t.attr('href').indexOf('#'))).length !== 0) {
                        e.preventDefault();
                        t.closest('UL').find('A').each(function () {
                            $(this).removeClass('active');
                            $($(this).attr('href').substring($(this).attr('href').indexOf('#'))).addClass('tab-hidden');
                        });
                        $(t.attr('href').substring(t.attr('href').indexOf('#'))).removeClass('tab-hidden');
                        t.addClass('active');
                        if (t.attr('rel')) {
                            document.location.hash = t.attr('rel');
                        }
                    } else {
                        document.location.href = t.attr('href');
                    }
                } else {
                    document.location.href = t.attr('href');
                }
                $(window).resize();
                $(document).trigger('respondUpdate');
            }
        }
        if (target.is('.tab-content .tab-header')) {
            t = target.filter('.tab-content .tab-header');
            e.preventDefault();
            t.closest('.tab-content').toggleClass('tab-content-mobile-open');
            $(window).resize();
            $(document).trigger('respondUpdate');
        }
        if (target.is('DIV.box01.expander .mainheading')) {
            t = target.filter('DIV.box01.expander .mainheading');
            e.preventDefault();
            t.closest('DIV.expander').toggleClass('expander-open');
            $(window).resize();
            $(document).trigger('respondUpdate');
        }
        if (target.is('DIV.block01.block01-expandable .mainheading, .col02 DIV.block01 .mainheading')) {
            t = target.filter('DIV.block01.block01-expandable .mainheading, .col02 DIV.block01 .mainheading');
            e.preventDefault();
            t.closest('DIV.block01').toggleClass('open');
            $(window).resize();
            $(document).trigger('respondUpdate');
        }
        if (target.is('UL.tabs01 LI.exp A, DIV.tabs01 LI.exp A')) {
            t = target.filter('UL.tabs01 LI.exp A, DIV.tabs01 LI.exp A');
            e.preventDefault();
            e.stopPropagation();
            var drop = $('<div class="select01drop singlelevel" id="tabs01drop"><span class="body"><span class="body-c"><ul></ul></span></span></div>'),
                holder = drop.find('UL');
            if (!t.closest('LI').hasClass('open')) {
                ch.trigger('click.tabs01');
                t.closest('LI').addClass('open');
                t.closest('UL').find('> LI:not(.exp).cantfit').each(function (a, b) {
                    $(b).clone(false).bind('click', function (e) {
                        e.preventDefault();
                        e.stopPropagation();
                        $(b).find('A').trigger('click');
                    }).appendTo(holder);
                });
                drop.data('t', t.closest('UL'));
                t.after(drop);
                ch.on('click.tabs01', function (e) {
                    ch.unbind('click.tabs01');
                    if ($('#tabs01drop').length > 0) {
                        $('#tabs01drop').data('t').find('.open').removeClass('open');
                        $('#tabs01drop').remove();
                    }
                });
            } else {
                ch.trigger('click.tabs01');
            }
        }
        if (target.is('DIV.groups01 DIV.heading .b')) {
            t = target.filter('DIV.groups01 DIV.heading .b');
            e.preventDefault();
            if (t.attr('data-rel')) {
                if (document.location.hash === '#' + t.attr('data-rel')) {
                    var st = parseInt($(window).scrollTop(), 10);
                    document.location.hash = '';
                    $(window).scrollTop(st);
                } else {
                    document.location.hash = t.attr('data-rel');
                }
            }
            if (t.closest('DIV.group').is(':not(.disabled)')) {
                t.closest('DIV.group').toggleClass('open mobile-open');
            }
            if ($('html.web').length > 0 && t.closest('DIV.group').hasClass('open')) {
                if (getMedia() === 'wide') {
                    pos = t.offset().top;
                    pos -= $('.menu01a').outerHeight();
                    pos -= $('.header03a').outerHeight();
                    window.setTimeout(function () {
                        $("html, body").animate({ scrollTop: pos - 80 }, { queue: false, duration: 500 });
                    }, 1);
                }
            }
            $(document).trigger('respondUpdate');
        }
        if (target.is('DIV.groupset .heading A')) {
            t = target.filter('DIV.groupset .heading A');
            e.preventDefault();
            if (t.attr('data-rel')) {
                if (document.location.hash === '#' + t.attr('data-rel')) {
                    var st = parseInt($(window).scrollTop(), 10);
                    document.location.hash = '';
                    $(window).scrollTop(parseInt($(window).scrollTop(), 10));
                } else {
                    document.location.hash = t.attr('data-rel');
                }
            }
            if (t.closest('DIV.expandable-group').is(':not(.disabled)')) {
                t.closest('DIV.expandable-group').toggleClass('expandable-group-open expandable-group-closed');
            }
            $(document).trigger('respondUpdate');
        }
    });

    ch.on('open', 'UL.tabs01 A, DIV.tabs01 A', function (e) {
        $(this).closest('UL').find('A').each(function () {
            $(this).removeClass('active');
            $($(this).attr('href').substring($(this).attr('href').indexOf('#'))).addClass('tab-hidden');
        });
        $($(this).attr('href').substring($(this).attr('href').indexOf('#'))).removeClass('tab-hidden');
        $(this).addClass('active');
        $(window).resize();
        $(document).trigger('respondUpdate');
    });

    $(window).bind('orientationchange.tabs01 resize.tabs01', function () {
        ch.trigger('click.tabs01');
        fitTabs();
    });
    ch.on('open', 'DIV.groupset .heading A', function () {
        if ($(this).closest('DIV.group').is(':not(.disabled)')) {
            $(this).closest('DIV.group').addClass('open mobile-open');
        }
        if ($(this).closest('DIV.expandable-group').is(':not(.disabled)')) {
            $(this).closest('DIV.expandable-group').addClass('expandable-group-open expandable-group-closed');
        }
        $(document).trigger('respondUpdate');
    });

    // Hashlinks for tabs
    // If hash is available then try top open relevant position

    if (document.location.hash !== '') {
        if ((getMedia() === 'medium' || getMedia() === 'wide') || $.IbCookie('responsive') === 'desktop') {
            activetab = $('[rel="' + document.location.hash.substr(1) + '"],[data-rel="' + document.location.hash.substr(1) + '"]:not(.tab-header)');
            if (activetab.length > 0) {
                if (activetab.is(':hidden')) {
                    $('A[href="#' + activetab.parents().filter(function (a, b) { return $(b).is(':hidden'); }).last().attr('id') + '"]').trigger('open');
                    activetab.trigger('open');
                } else {
                    activetab.trigger('open');
                }
                $(window).scrollTop(activetab.offset().top);
            }
        } else {
            activetab = $('[data-rel="' + document.location.hash.substr(1) + '"]');
            if (activetab.length > 0) {
                if (activetab.is(':hidden')) {
                    activetab.parents().filter(function (a, b) { return $(b).is(':visible'); }).first().find('.tab-header').trigger('open');
                    activetab.trigger('open');
                } else {
                    activetab.trigger('open');
                }
                $(window).scrollTop(activetab.offset().top - activetab.outerHeight() - 20);
            }
        }
    }

    // History navigation without scrolling

    $(window).bind('hashchange.tabs', function () {
        if (document.location.hash !== '') {
            var activetab = $('[rel="' + document.location.hash.substr(1) + '"],[data-rel="' + document.location.hash.substr(1) + '"]:not(.tab-header)');
            if (activetab.length > 0) {
                if (activetab.is(':hidden')) {
                    $('A[href="#' + activetab.parents().filter(function (a, b) { return $(b).is(':hidden'); }).last().attr('id') + '"]').trigger('open');
                    activetab.trigger('open');
                    $(window).scrollTop(activetab.offset().top);
                } else {
                    activetab.filter(function () { return $(this).closest('DIV.heading').length === 0; }).trigger('open');
                }
            }
        }
    });

    // Header select field

    var profilesdrop = $('<div class="select01drop" id="profile01drop"><span class="body"><span class="body-c"></span></span></div>');

    profilesdrop.click(function (e) { e.stopPropagation(); });

    $('#profile01:has(A.main)').closest('.inner, .header03a').append(profilesdrop);

    $('#profile01 A.main').click(function (e) {
        e.preventDefault();
        e.stopPropagation();
        hideMenu();
        if ($(this).hasClass('open')) {
            e.stopPropagation();
            $('BODY').trigger('click').unbind('.userdrop');
            $(window).unbind('resize.userdrop');
        } else {
            $('BODY').trigger('click');
            $('BODY').unbind('.userdrop');
            $(window).unbind('resize.userdrop');
            $(this).addClass('open');
            $('#profile01drop').css({
                left: $('#profile01').offset().left - $(window).scrollLeft() + 'px',
                top: $('#profile01').offset().top - parseInt($('body').css('margin-top'), 10) - $(window).scrollTop() + $('#profile01').outerHeight() - $('.seb-maintenance-message').outerHeight() - $('#header01').outerHeight() + 'px',
                width: $('#profile01').outerWidth() + 'px'
            }).find('SPAN.body-c').html($('#profile01 UL.drop').clone());
            $('#profile01drop').attr('class', 'select01drop');
            if ($('#profile01 UL.drop UL').length === 0) {
                $('#profile01drop').addClass('singlelevel');
            }
            if ($('#profile01drop UL.drop').outerHeight() > 500) {
                $('#profile01drop UL.drop').addClass('scrollable');
            }
            $('BODY').bind('click.userdrop', function () {
                $('BODY').unbind('.userdrop');
                $(window).unbind('resize.userdrop');
                $('#profile01 A.open').removeClass('open');
                $('#profile01drop').css({
                    left: '-1000px',
                    top: '-1000px',
                    width: ''
                });
            });
            $(window).bind('resize.userdrop', function () {
                $('#profile01drop').css({
                    left: $('#profile01').offset().left + 'px',
                    top: $('#profile01').offset().top + $('#profile01').outerHeight() + 'px',
                    width: $('#profile01').outerWidth() + 'px'
                });
            });
        }
        if (getMedia() === 'medium' || getMedia() === 'narrow') {
            setMobMenuSize();
        }
    });

    // Search autocomplete
    $('#searchid01').autocomplete({
        source: "data/sleep.php?q=search01.php&time=1",
        //source: "data/search01.php",
        minLength: 1,
        position: { offset: "0 3" },
        //select: function (event, ui) { log( ui.item ? "Selected: " + ui.item.value + " aka " + ui.item.id : "Nothing selected, input was " + this.value ); },
        close: function () {
            if (getMedia() === 'narrow') {
                $(this).autocomplete('option', 'appendTo', '#menu01');
            } else {
                $(this).autocomplete('option', 'appendTo', '');
            }
        },
        open: function () {
            if (getMedia() === 'narrow') {
                $(this).autocomplete('option', 'appendTo', '#menu01');
            } else {
                $(this).autocomplete('option', 'appendTo', '');
            }
        }
    }).autocomplete('widget').addClass('headerautocomplete');

    // Listing details

    ch.on('click', 'UL.list02 A.expand, DIV.row A.expand', function (e) {
        e.preventDefault();
        $(this).toggleClass('open');
        var $r =  $(this).closest('.row');
        if ($r.find('.moredetails').length > 0) {
            $r.find('.moredetails').toggleClass('hidden');
        } else {
            $r.next('.moredetails').toggleClass('hidden');
        }
		$(document).trigger('respondUpdate');
    });

    // Button focus and blur

    ch
        .on('focus', 'UL.actions01 INPUT', function (e) {
            $(this).closest('LI').children().first().addClass('focus');
        })
        .on('blur', 'UL.actions01 INPUT', function (e) {
            $(this).closest('LI').children().first().removeClass('focus');
        });

    // Hide show cards

    var card = $('.hide-cards a');
    card.on('click', function (e) {
        e.preventDefault();
        if ($(this).hasClass('open')) {
            $(this).removeClass('open');
            $(this).text('hide cards');
            $('.card-row').removeClass('hidden');
        } else {
            $(this).addClass('open');
            $(this).text('show cards');
            $('.card-row').addClass('hidden');
        }
    });

    // Collapse link accounts branches

    var moreBranchesBtn = $('.show-branches');
    moreBranchesBtn.on('click', function (e) {
        e.preventDefault();
        $(this).closest('.row').find('.collapse').slideDown(300);        
        $(this).closest('.h3tools').hide();
    });

    // Toggle link account search box on mobile

    var toggleSearchBox = $('.la-search-box__toggle');
    toggleSearchBox.on('click', function (e) {
        e.preventDefault();
        $('.la-search-box').slideToggle(300);        
        $(this).toggleClass('open');
    });

    // PROTOTYPE ONLY

    $('[data-include]').each(function (a, b) {
        $.ajax({
            url: $(b).attr('data-include'),
            success: function (d) {
                $(b).append(d);
                fitMenu(true);
                $(document).trigger('respondUpdate');
                if ($('UL.menu01').find($('A[href="' + parseUri(document.location).file + '"]')).length > 0) {
                    $('UL.menu01').find('.active').removeClass('active');
                    $('UL.menu01').find($('A[href="' + parseUri(document.location).file + '"]')).first().addClass('active').parentsUntil('UL.menu01', 'LI, A, DIV.set').addClass('active mob-open');
                }
            }
        });
    });

    // Header dropdowns

    $('.header03').on('click', '[data-dropdown]', function (e) {
        if (getMedia() === 'wide') {
            e.preventDefault();
            var t = $(this),
                dropholder = $('<div class="dropholder"><div class="wrap"><span class="arrow"></span><div class="drop"><div class="loading02"><p>' + locales.simpleloader + '</p></div></div></div></div>'),
                scrollpos = $('BODY').scrollTop() > $('HTML').scrollTop() ? $('BODY').scrollTop() : $('HTML').scrollTop(),
                ev2,
                droppos = 0;
            if (t.hasClass('active')) {
                dropRemove();
            } else {
                dropRemove();
                $('BODY').addClass('dropopen');
                $('DIV.header03').detach().prependTo('BODY');
                $('#box01').scrollTop(scrollpos);

                ev2 = $.ajax({
                    url: t.attr('data-dropdown'),
                    success: function (html) {
                        dropholder.find('.drop').empty().append(html);

                        if (html.substr(html.length-1) == '$' && html.indexOf('id="loginpage"') === -1) {
                            //session key change on page
                            var sesskeystart = html.lastIndexOf('$',html.length-2),
                                newsesskey = html.substring(sesskeystart+1,html.length-1),
                                html = html.substring(0,sesskeystart),
                                links=$('a[href*="sesskey="],a[onclick*="sesskey="]'),
                                forms=$('form[action*="sesskey="]'),
                                imgs=$('img[src*="sesskey="]'),
                                img,
                                src,
                                form,
                                href,
                                action,
                                link,
                                i = links.length,
                                oldsesskey=document.forms.sessionData.sesskey.value;
                            while(i) {
                                //change in links, in hrefs and in click
                                i--;
                                link=$(links[i]);
                                href=link.attr('href').replace(oldsesskey,newsesskey);
                                link.attr('href',href);
                            }
                            i = forms.length;
                            while(i) {
                                //change in form actions
                                i--;
                                form=$(forms[i]);
                                action=form.attr('action').replace(oldsesskey,newsesskey);
                                form.attr('action',action);
                            }
                            i = imgs.length;
                            while(i) {
                                //change in image sources, probably irrelevant
                                i--;
                                img=$(imgs[i]);
                                src=img.attr('src').replace(oldsesskey,newsesskey);
                                img.attr('src',src);
                            }
                            $('input[value="'+oldsesskey+'"]').val(newsesskey);
                            //change in input fields
                            //usearch.initParams();
                            usearch.sesskey=newsesskey; //change in seach
                            if (document.sessionData.sesskey) //change in sessionData form
                                document.sessionData.sesskey.value=newsesskey;
                            else
                                document.sessionData[0].sesskey.value=newsesskey;
                            if (document.sessionData.unetsesskey) //change in sessionData form, propbably irrelevant
                                document.sessionData.unetsesskey.value=newsesskey;
                            else
                                document.sessionData[0].unetsesskey.value=newsesskey;
                            //updateSesskeyInVariables(window,oldsesskey,newsesskey);
                            $('#searchid001').setOptions({'url':usearch.makeSearchURL("sact=getsuggestion")}); //change in search
                        }
                    },
                    error: function (a, b, c) {
                        dropRemove();
                        if (b !== 'abort') {
                            tb_show('', '#TB_error?width=300&amp;height=300&amp;autoscale=1', c);
                        }
                        return false;
                    }
                });

                dropholder.data('ev', ev2).click(function (e) {
                    e.preventDefault();
                    dropRemove();
                    ev2.abort();
                });
                dropholder.find('DIV.drop').click(function (e) {
                    e.stopPropagation();
                });
                dropholder.appendTo('BODY');
                dropholder.data('scrollpos', scrollpos);
                droppos = $('.header03a').outerWidth() - (($('.header03a').outerWidth() - $('.header03a').width()) / 2) - (t.offset().left - $('.header03a').offset().left) - ($('.dropholder .drop').outerWidth() / 2) - (t.outerWidth() / 2);
                if (droppos < 0) {
                    droppos = 0;
                }
                $('.dropholder .drop').css('marginRight', droppos);
                $('.dropholder .arrow').css('marginRight', $('.header03a').outerWidth() - (($('.header03a').outerWidth() - $('.header03a').width()) / 2) - (t.offset().left - $('.header03a').offset().left) - ($('.dropholder .arrow').outerWidth() / 2) - (t.outerWidth() / 2));
                t.addClass('active');
            }
        } else {
            dropRemove();
        }
    });

    // Linked tables

    $('TABLE[data-linked]').each(function (a, b) {
        if (linkedtables.indexOf($(b).attr('data-linked')) === -1) {
            linkedtables.push($(b).attr('data-linked'));
        }
    });

    $(window).on('resize.linkedtables respondUpdate.linkedtables', function () {
        $.each(linkedtables, function (a, b) {
            var cols = $();
            cols.tables = 0;
            $('TABLE[data-linked="' + b + '"]').each(function (c, d) {
                $.each($(d).find('TR:has(TH):first TH'), function (e, f) {
                    cols.push(f);
                    if (cols.tables > 0) {
                        $(this).css('minWidth', $(cols[e]).width());
                    }
                });
                cols.tables = cols.tables + 1;
            });
        });
    });

    $(window).trigger('resize.linkedtables');

    // Responsive iframes

    if (window.self !== window.top) {
        // Frame
        ri = true;

		ch.on('click', function () { framed(); });

        mainWindowProxy = new Porthole.WindowProxy('./proxy.html');
        mainWindowProxy.addEventListener(function(e) {
            if (e.data.action === 'proxyready') {
	            mainWindowProxy.post({ 'action': 'embedframe' });
            }
            if (e.data.action === 'embedframeResponse') {
                responsiveparent = e.data.isresponsive;
                // store original media for later use and default to visible
                $('LINK[rel="stylesheet"][media!="print"]:not([media="all"]:not([data-media])):not([data-media]), LINK[rel="alternate stylesheet"][media!="print"]:not([media="all"]:not([data-media])):not([data-media])').each(function (a, b) {
                    $(b).attr('data-media', $(b).attr('media')).attr('media','all').attr('disabled','disabled');
                });
                if ($.IbCookie('responsive') === 'desktop' || e.data.isresponsive === 'false') {
                    // responsive disabled
                    $('LINK[data-media]').each(function (a, b) {
                        var m = $(this).attr('data-media'),
                            max = m.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/) && parseFloat(RegExp.$1) + (RegExp.$2 || ""),
                            min = m.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/) && parseFloat(RegExp.$1) + (RegExp.$2 || "");
                        if (max !== null) {
                            if (parseInt(max, 10) > 749 && min === null) {
                                $(b).removeAttr('disabled').attr('media', 'all').attr('rel', 'stylesheet');
                            } else {
                                $(b).attr('disabled', 'disabled').attr('media', 'all').attr('rel', 'alternate stylesheet');
                            }
                        } else {
                            $(b).removeAttr('disabled').attr('media', 'all').attr('rel', 'stylesheet');
                        }
                    });
                } else {
                    // responsive enabled
                    $('LINK[data-media]').each(function (a, b) {
                        var m = $(this).attr('data-media'),
                            min = m.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/) && parseFloat(RegExp.$1) + (RegExp.$2 || ""),
                            max = m.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/) && parseFloat(RegExp.$1) + (RegExp.$2 || ""),
                            w = e.data.width;

                        min = min === null ? null : parseInt(min, 10);
                        max = max === null ? null : parseInt(max, 10);

                        if ((min !== null && min > w) || (max !== null && max < w)) {
                            // disable
                            $(b).attr('rel', 'alternate stylesheet').attr('disabled', 'disabled').attr('title','rnd'+Date.now);
                        } else {
                            // enable
                            $(b).attr('rel', 'stylesheet').removeAttr('disabled').removeAttr('title');
                        }
                    });
                }
				window.setTimeout(function () {
					$(document).trigger('respondUpdate');
					mainWindowProxy.post({
						'action': 'setframeheightResponse',
						'height': $('body').height()
					});
				}, 1);
            }
            if (e.data.action === 'setframeheight') {
				window.setTimeout(function () {
					mainWindowProxy.post({
						'action': 'setframeheightResponse',
						'height': $('body').height()
					});
				}, 1);
            }
        });
        mainWindowProxy.post({ 'action': 'embedframe' });
		framed();
    } else {
        // Main window
        addIframeProxy();
		$(window).bind('resize.responsiveiframeouter', function () {
			$('iframe[name].proxyinit').each(function (a, b) {
				$(b).data('windowProxy').post({
                    'action': 'embedframeResponse',
                    'isresponsive': parseUri(window.location.href).queryKey.responsive ? 'false' : 'true',
                    'width': $(window).width(),
                    'currentHeight': $(b).height(),
                    'name': $(b).attr('name')
                });
			});
		});
    }

    // Workarounds for respond.js

    $(document).bind('respondUpdate', function () {
        'use strict';

        // Special selects
        $('SELECT.dynselect01.initdone:visible').each(function (a, b) {
            var drop = $('#' + $(b).attr('id') + 'drop');
            $(b).closest('SPAN.dynselect01').css('width', '');
            $(b).closest('SPAN.dynselect01')
                .css('width', $(b).outerWidth() > drop.outerWidth() ? $(b).outerWidth() : drop.outerWidth());
        });
        $('SELECT.dynselect01').filter(function () {
            if ($(this).hasClass('initdone')) {
                return false;
            } else {
                return !!$(this).is(':visible');
            }
        }).each(function (a, b) {
            var drop = $('#' + $(b).attr('id') + 'drop');
            if ($(b).val() === '' && drop.find('UL.checkboxes INPUT').length > 0) {
                $(b).find('OPTION').text(drop.find('UL.checkboxes INPUT:checked').length + ' ' + locales.itemsSelected);
            }
            $(b)
                .focus(function (e) {
                    e.preventDefault();
                    e.stopPropagation();
                    $(this).blur();
                })
                .wrap('<span class="dynselect01" />')
                .addClass('initdone');
            $(b).closest('SPAN.dynselect01')
                .css('width', $(b).outerWidth() > drop.outerWidth() ? $(b).outerWidth() : drop.outerWidth())
                .append('<span class="overlay" />').click(function () {
                    var t = $(this),
                        dropcontents = drop.find('UL:first').detach();
                    if ((getMedia() === 'medium' || getMedia() === 'wide') || $.IbCookie('responsive') === 'desktop') {
                        if (t.hasClass('open')) {
                            $('BODY').trigger('click').unbind('.userdrop');
                            $(window).unbind('resize.dynselect');
                        } else {
                            $('BODY').trigger('click');
                            $('BODY').unbind('.userdrop');
                            $(window).unbind('resize.dynselect');
                            t.addClass('open');
                            $('#profile01drop').detach().insertAfter(t);
                            $('#profile01drop').css({
                                left: t.position().left + 'px',
                                top: t.position().top + t.outerHeight() + 'px',
                                width: t.outerWidth() + 'px'
                            }).find('SPAN.body-c').html(dropcontents);
                            if ($('#profile01drop UL.drop').outerHeight() > 500) {
                                $('#profile01drop UL.drop').addClass('scrollable');
                            }
                            $('BODY').bind('click.userdrop', function () {
                                $('BODY').unbind('.userdrop');
                                $(window).unbind('.dynselect');
                                t.removeClass('open');
                                $('#profile01drop').css({
                                    left: '-1000px',
                                    top: '-1000px',
                                    width: ''
                                });
                                dropcontents.detach().appendTo(drop);
                                $('#profile01drop').detach().appendTo('BODY');
                            });
                            $(window).bind('resize.dynselect', function () {

                                $('#profile01drop').css({
                                    left: t.position().left + 'px',
                                    top: t.position().top + t.outerHeight() + 'px',
                                    width: t.outerWidth() + 'px'
                                });
                            });
                        }
                    }
                    return false;
                });
            if ($(b).outerWidth() < drop.outerWidth()) {
                $(b).css('width', drop.outerWidth());
            }
        });

        $('.form01:not(.initdone)').addClass('initdone').each(function (a, b) {
            if ($(b).find(':input, .slider01').length === 0) {
                $(b).addClass('readonly');
            }
        });
        // Multiselects
        window.setTimeout(function () {
          if ($('SELECT.multiselect').length > 0) {
            require(['bootstrap.multiselect'], function () {
                $('SELECT.multiselect').filter(function () {
                    if ($(this).hasClass('initdone')) {
                        return false;
                    } else {
                        return !!$(this).is(':visible');
                    }
                }).each(function (a, b) {
                    var options = {
                            numberDisplayed: $(b).attr('data-showitems') !== 'undefined' ? $(b).attr('data-showitems') : 1,
                            buttonContainer: '<div class="fakeselect ' + $(b).attr('class') +'"name="multiselect" />',
                            includeSelectAllOption: $(b).attr('data-selectall') === 'true' ? true : false,
                            buttonWidth: false,
                            enableCaseInsensitiveFiltering: $(b).attr('data-search') === 'enabled' ? true : false,
                            filterBehavior: 'text',
                            cssChildRow: 'details',
                            selectAllText: locales.selectAllText,
                            filterPlaceholder: locales.filterPlaceholder,
                            nonSelectedText: locales.nonSelectedText,
                            nSelectedText: locales.nSelectedText,
                            maxHeight: 300
                        },
                        showValues = function (sel) {
                            var selected = $(sel).find('OPTION:selected[value!="' + $(b).data('multiselect').options.selectAllValue + '"]');
                            if (selected.length > 0) {
                                valblock.removeClass('hidden').empty();
                                $.each(selected, function (c, d){
                                    var item = $('<li><div>' + $(d).val() + '</div></li>'),
                                        rem = $('<a href="#"></a>');
                                    rem.click(function (e) {
                                        e.preventDefault();
                                        $(b).multiselect('deselect', $(d).val());
                                        showValues(sel);
                                    });
                                    item.find('div').append(rem);
                                    valblock.append(item);
                                });
                            } else {
                                valblock.addClass('hidden').empty();
                            }
                        },
                        valblock = $('<ul class="valblock hidden"></ul>');
                    $(b).multiselect(options);
                    if($(b).attr('data-showvalues') === 'true' && $(b).attr('multiple') === 'multiple') {
                        $(b).data('valblock', valblock);
                        $(b).multiselect('setOptions', $.extend({}, options, {
                            onChange: function () {
                                showValues($(b));
                            }
                        })).multiselect('rebuild');
                        $(b).data('multiselect').$container.after(valblock);
                        showValues($(b));
                    }
                    $(b).addClass('initdone');
                });
            });
          }
        }, 1000);
        // Init iframes

        if ($('IFRAME:first').outerHeight() === 0 || !$('IFRAME:first').is(':visible')) {
            top.postMessage('1', '*');
        }

        // Highcharts

        if (window.Highcharts) {
            $('.highcharts-container').each(function (a, b) {
                $(b).parent().highcharts().reflow();
            });
        }

        // Reinit tables

        $('.footable').trigger('footable_resize');

        // Sticky headers

        if ($('.fixedtable').length > 0) {
            require(['stickykit'], function () {
                $('.fixedtable').filter(function () {
                    if ($(this).hasClass('initdone')) {
                        return false;
                    }
                    return !!$(this).is(':visible');
                }).each(function (a, b) {
                    $(b).addClass('initdone').wrap('<div class="tabletools"></div>').parent().prepend('<div class="clone"></div>');
                    var orig = $(b).find('> thead:first'),
                        origTable = $(b),
                        clone = orig.clone(false),
                        header = $('<table></table>'),
                        offset = $('.header03').length > 0 ? parseInt($('#header02 .a').offset().top, 10) : 0;

                    if ($('DIV.menu01a').offset().left > 0 && $('DIV.menu01').css('position') === 'fixed') {
                        offset += 54;
                    }

                    clone.on('blur click dblclick hover', '*', function (e) {
                        e.stopPropagation();
                        $($(e.target).getPath(header), orig).trigger(e.type);
                    });
                    clone.find('TH, TD').each(function (c, d) {
                        $(d).data('ref', $($(d).getPath(header), origTable));
                    });
                    header.append(clone);
                    $(b).parent().find('.clone').append(header).stick_in_parent({
                        offset_top: offset
                    });
                });
                $(window).on('resize.stickyheaders', function() {
                    $('.tabletools > .clone th').each(function () {
                        var ref = $(this).data('ref');
                        if (ref.is(':visible')) {
                            $(this).css({
                                minWidth: ref.outerWidth(),
                                display: ''
                            });
                        } else {
                            $(this).css({
                                width: '',
                                display: 'none'
                            });
                        }
                    });
                });
                $(window).resize();
            });
        }

        // Sticky menu

        if ($('.fixedmenu').length > 0) {
            require(['stickykit'], function () {
                $('.fixedmenu').filter(function () {
                    if ($(this).hasClass('initdone')) {
                        return false;
                    }
                    return !!$(this).is(':visible');
                }).each(function (a, b) {
                    $(b).addClass('initdone').stick_in_parent({
                        parent: $('#content01')
                    });
                });
            });
        }

    });

    // Try to set highcharts options

    if (window.Highcharts) {
        Highcharts.setOptions(highchartoptions);
    }

    // Scrolltop

    $(window).on('scroll.scrolltop resize.scrolltop init.scrolltop', function () {
        if ($(window).height() > $(window).scrollTop()) {
            $('.scrolltop').removeClass('visible');
        } else {
            $('.scrolltop').addClass('visible');
        }
    });
    $('.scrolltop').click(function (e) {
        e.preventDefault();
        $("html, body").animate({ scrollTop: 0 }, { queue: false, duration: 500 });
    });
    $(window).trigger('init.scrolltop');

    // Mobile call to action

    $(window).on('scroll.mobilecta resize.mobilecta init.mobilecta', function () {
        if ($(window).height() > $(window).scrollTop()) {
            $('.mobilecta').removeClass('visible');
        } else {
            $('.mobilecta').addClass('visible');
        }
    });
    $('.mobilecta .close').click(function (e) {
        e.preventDefault();
        $('.mobilecta').remove();
        $(window).off('scroll.mobilecta resize.mobilecta init.mobilecta');
    });
    $(window).trigger('init.mobilecta');

    // Cookie message

    if ($('.cookiemessage').length > 0) {
        require(['jquery.cookie', 'jquery.ibcookie'], function () {
            if ($.IbCookie('cookiemessage') == 'accepted') {
                $('.cookiemessage').addClass('hidden');
            } else {
                $('.cookiemessage').removeClass('hidden');
                $('.cookiemessage .button').click(function (e) {
                    e.preventDefault();
                    $('.cookiemessage').addClass('hidden');
                    $.IbCookie('cookiemessage', 'accepted', {expires: 365});
                });
            }
        });
    }

    // Init content base extensions

    $(document).trigger('respondUpdate');
}

// Thickbox

function tb_init(domChunk, context) {
	'use strict';
	var actioncontext;
    if (context) {
        actioncontext = context;
    } else {
        actioncontext = $(contentholders);
    }
	$(domChunk, actioncontext).click(function () {
		var t = this.title || this.name || $(this).data('title') || null,
			a = this.href || this.alt,
			g = this.rel || false;
        if (typeof HTMLElement === "object" ? this instanceof HTMLElement : this && typeof this === "object" && this !== null && this.nodeType === 1 && typeof this.nodeName==="string") {
            tb_prevfocus = this;
        }
		tb_show(t, a, g);
		return false;
	});
}

function tb_show(caption, url, imageGroup, callback) {
	tb_scrollpos = $(window).scrollTop();
    if (tb_isopen) {
	    tb_remove();
    } else {
        tb_isopen =  true;
    }
	try {
		window["ajaxTimeoutCallback"] = null;
		if (typeof (callback) === "function"){ window["ajaxTimeoutCallback"] = callback; }
		if (document.getElementById("TB_overlay") === null) {
			$("BODY").append("<div id='TB_overlay'></div><div id='TB_window' class='TB_window_hidden'></div>");
		}
		$("#TB_overlay").click(tb_remove).css({ height: '10000px' });
		$("#TB_overlay").addClass("TB_overlayBG");
		if (caption === null) {
			caption = "";
		}
		//$("body").append("<div id='TB_load'></div>"); //add loader to the page
		var baseURL;
		if (url.indexOf("?") !== -1) {
			//ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
		} else {
			baseURL = url;
		}
		var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
		var urlType = baseURL.toLowerCase().match(urlString);
		// Create template
		var template = '';
		template += "<div id='TB_container1'>";
		template += "<div id='TB_main'><div class='TB_header' id='TB_header'><div class='a'><div class='logo'></div></div></div><div class='main-b'><div id='TB_body' class='clear'>";
		if (typeof (locales) != 'undefined' && locales.simpleloader) {
			template += '<div id="TB_loader3" class="loader03 center"><span>' + locales.simpleloader + '</span></div>';
		} else {
			template += '<div id="TB_loader3" class="loader03 center"><span>...</span></div>';
		}
		template += "</div></div></div>";
		template += "</div>";
		$("#TB_container1").remove();
		$("#TB_window").append(template);
		tb_timer1 = window.setTimeout('tb_preloader()', 1000);
		if (urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp') {
			//code to show images
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if (imageGroup) {
				TB_PrevHTML = "<a href='#' id='TB_prev'></a>";
				TB_NextHTML = "<a href='#' id='TB_next'></a>";
				TB_TempArray = $("a[rel=" + imageGroup + "]").get();
				for (TB_Counter = 0;
					 ((TB_Counter < TB_TempArray.length) && (TB_NextURL === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
					if (!(TB_TempArray[TB_Counter].href == url)) {
						if (!TB_FoundURL) {
							TB_PrevCaption = TB_TempArray[TB_Counter].title;
							TB_PrevURL = TB_TempArray[TB_Counter].href;
						} else {
							TB_NextCaption = TB_TempArray[TB_Counter].title;
							TB_NextURL = TB_TempArray[TB_Counter].href;
						}
					} else {
						TB_FoundURL = true;
						TB_imageCount = "<span id='TB_imgcount'>" + (TB_Counter + 1) + " / " + (TB_TempArray.length) + "</span>";
					}
				}
			}
			imgPreloader = new Image();
			imgPreloader.onload = function () {
				imgPreloader.onload = null;
				// Resizing large images - orginal by Christian Montoya edited by me.
				var pagesize = tb_getPageSize();
				var x = pagesize[0] - 70;
				var y = pagesize[1] - 70;
				var imageWidth = imgPreloader.width;
				var imageHeight = imgPreloader.height;
				if (imageWidth > x) {
					imageHeight = imageHeight * (x / imageWidth);
					imageWidth = x;
					if (imageHeight > y) {
						imageWidth = imageWidth * (y / imageHeight);
						imageHeight = y;
					}
				} else if (imageHeight > y) {
					imageWidth = imageWidth * (y / imageHeight);
					imageHeight = y;
					if (imageWidth > x) {
						imageHeight = imageHeight * (x / imageWidth);
						imageWidth = x;
					}
				}
				// End Resizing
				TB_WIDTH = imageWidth;
				TB_HEIGHT = imageHeight;
				// Fixing small images - original by me :)
				var placeholderInject = '';
				var x2 = 300;
				var y2 = 250;
				var z = '';
				if (imageWidth < x2) {
					TB_WIDTH = x2;
					z += ' padding-left: ' + (x2 - imageWidth) / 2 + 'px;';
					z += ' padding-right: ' + (x2 - imageWidth) / 2 + 'px;';
				}
				if (imageHeight < y2) {
					TB_HEIGHT = y2;
					z += ' padding-top: ' + (y2 - imageHeight) / 2 + 'px;';
					z += ' padding-bottom: ' + (y2 - imageHeight) / 2 + 'px;';
				}
				placeholderInject = ' style="' + z + '"';
				var createwindow = '';
				createwindow += "<div class='clear' id='TB_ajaxWindowTitle'>";
				createwindow += "<a href='#' id='TB_closeWindowButton'>" + locales.tbclose + "</a>";
				createwindow += TB_PrevHTML;
				createwindow += TB_imageCount;
				createwindow += TB_NextHTML;
				createwindow += "</div>";
				createwindow += "<div id='TB_container2'><div id='TB_content_placeholder'><span " + placeholderInject + "><a href='#' id='TB_content_placeholder_prev'></a><a href='#' id='TB_content_placeholder_next'></a><img id='TB_Image' src='" + url + "' width='" + imageWidth + "' height='" + imageHeight + "' alt=''/></a></div></div>";
				if (caption !== "") {
					createwindow += "<div id='TB_caption'><p>" + caption + "</p></div>";
				}
				$("#TB_body").append(createwindow);
				$("#TB_closeWindowButton").click(function () {
					tb_remove();
					return false;
				});
				if (!(TB_PrevURL === "")) {
					function goPrev() {
						if ($(document).unbind("click", goPrev)) {
							$(document).unbind("click", goPrev);
						}
						$("#TB_window").remove();
						$("body").append("<div id='TB_window'></div>");
						tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
						return false;
					}

					$("#TB_content_placeholder_prev, #TB_prev").click(function () {
						goPrev();
						return false;
					});
				} else {
					$("#TB_content_placeholder_prev, #TB_prev").addClass('TB_disabled').click(function () {
						return false;
					});
				}
				if (!(TB_NextURL === "")) {
					function goNext() {
						$("#TB_window").remove();
						$("body").append("<div id='TB_window'></div>");
						tb_show(TB_NextCaption, TB_NextURL, imageGroup);
						return false;
					}
					$("#TB_content_placeholder_next, #TB_next").click(function () {
						goNext();
						return false;
					});
				} else {
					$("#TB_content_placeholder_next, #TB_next").addClass('TB_disabled').click(function () {
						return false;
					});
				}
				document.onkeydown = function (e) {
					if (e == null) { // ie
						keycode = event.keyCode;
					} else { // mozilla
						keycode = e.which;
					}
					if (keycode == 27) { // close
						tb_remove();
					} else if (keycode == 39) { // display previous image
						if (!(TB_NextHTML == "")) {
							document.onkeydown = "";
							goNext();
						}
					} else if (keycode == 37) { // display next image
						if (!(TB_PrevURL == "")) {
							document.onkeydown = "";
							goPrev();
						}
					}
				};
				$("#TB_load").remove();
				$("#TB_ImageOff").click(tb_remove);
                tb_display();
			};
			imgPreloader.src = url;
		} else {
			//code to show html
			var queryString = url.replace(/^[^\?]+\??/, '');
			var params = tb_parseQuery(queryString);
			TB_WIDTH = (params.width * 1) || 630;
			TB_HEIGHT = (params.height * 1) || 440;
			ajaxContentW = TB_WIDTH;
			ajaxContentH = TB_HEIGHT;
			if (url.indexOf('TB_iframe') != -1) {
				// iframe
				urlNoQuery = url.split('#TB_');
				$("#TB_iframeContent").empty().remove();
				if (params.modal == "true") {
					$("#TB_overlay").unbind();
				}
				$('#TB_content_placeholder').remove();
				$('#TB_body').append("<div id='TB_content_placeholder' class='hidden'><iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' style='width:" + (ajaxContentW) + "px;height:" + (ajaxContentH) + "px;' scrolling='auto'></iframe></div>");
			} else if (url.indexOf('TB_error') != -1) {
				if (params.modal == "true") {
					$("#TB_overlay").unbind();
				}
				$('#TB_content_placeholder').remove();
				$('#TB_body').append("<div id='TB_content_placeholder' class='hidden'><div id='TB_error' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px'><p>" + imageGroup + "</p><ul class='actions01 clear'><li><a href='#' class='btn main'><span>OK</span></a></li></ul></div></div>");
				$('#TB_error A').click(function () {
					return tb_remove();
				});
				$('#TB_overlay')[0].className = 'TB_overlayClear';
				$('#TB_window')[0].className = 'TB_window_error';
			} else {
				// inline
				if ($("#TB_window").hasClass('TB_window_visible') != true) {
					if (params.modal == "true") {
						$("#TB_overlay").unbind();
					}
					$('#TB_content_placeholder').remove();
					$('#TB_body').append("<div id='TB_content_placeholder' class='hidden'><div id='TB_ajaxContent_holder'><div id='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px'></div></div></div>");
				} else {
					//this means the window is already up, we are just loading new content via ajax
					$("#TB_ajaxContent")[0].style.width = ajaxContentW + "px";
					$("#TB_ajaxContent")[0].style.height = ajaxContentH + "px";
					$("#TB_ajaxContent")[0].scrollTop = 0;
					$("#TB_ajaxWindowTitle").html(caption);
				}
			}
			if (url.indexOf('TB_inline') != -1) {
				$('#TB_content_container').contents().unwrap();
				$("#TB_ajaxContent").append($('#' + params.inlineId).children());
				$("#TB_window").bind('tb_unload', function () {
					$('#' + params.inlineId).append($("#TB_ajaxContent").children()); // move elements back when you're finished
				});
				if (url.indexOf('autoscale') != -1) {
					$('#TB_ajaxContent').data('autoscale', params.autoscale);
				}
				tb_display();
			} else if (url.indexOf('TB_error') != -1) {
				$('#TB_content_container').contents().unwrap();
				if (url.indexOf('autoscale') != -1) {
					$('#TB_error').data('autoscale', params.autoscale);
				}
				tb_display();
			} else if (url.indexOf('TB_iframe') != -1) {
				if (url.indexOf('autoscale') != -1) {
					$('#TB_iframeContent').data('autoscale', params.autoscale);
				}
				$('#TB_iframeContent').load(tb_display);
			} else {
				$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()), function () {
					$("#TB_load").remove();
					tb_init("#TB_ajaxContent A.thickbox");
				});
				tb_display();
			}
		}
		if (!params.modal && url.indexOf('TB_error') == -1) {
			$('#TB_header DIV.a').append('<a href="#" class="close"><span>' + locales.tbclose + '</span></a>');
			$("#TB_header DIV.a A.close").click(function (e) {
				e.preventDefault();
				e.stopPropagation();
				tb_remove();
			});
			document.onkeyup = function (e) {
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if (keycode == 27) { // close
					tb_remove();
				}
			};
		}
        addIframeProxy();
        window.setTimeout(function () {
          document.getElementById('TB_window').scrollIntoView({
            block: 'center',
            inline: 'center'
          });
        }, 1000);
	} catch (e) {}
}

function tb_preloader() {
	'use strict';
	$("#TB_window").removeClass('TB_window_hidden').addClass('TB_window_visible');
	//$("#TB_window").css({ width: '10000px' });
	var tb_tmp01w = $('#TB_window').outerWidth() - $('#TB_body').outerWidth() + 200;
	$("#TB_window").css({
		marginLeft: '-' + parseInt((tb_tmp01w / 2), 10) + 'px',
		top: $(window).scrollTop() + (tb_getPageSize()[1] / 2) - ($("#TB_window").outerHeight() / 2) + 'px',
		width: tb_tmp01w + 'px'
	});
}

function tb_scale() {
	// handle height of the window
	$("#TB_window").removeClass('TB_window_hidden').addClass('TB_window_visible');
	$("#TB_content_placeholder").removeClass('hidden');
	$("#TB_loader3").addClass('hidden');
    if ($('#TB_iframeContent').length > 0 && ($('#TB_iframeContent').data('autoscale') == 1 || $('#TB_iframeContent').data('autoscale') == 2)) {
        var $contents = $('#TB_iframeContent').contents();
        $contents.find('HTML').css({
            overflowX: 'hidden',
            overflowY: 'auto'
        });
        TB_HEIGHT2 = $contents.find('BODY').outerHeight() + 2;
        TB_WIDTH2 = TB_WIDTH;
        $('#TB_main DIV.main-b').css({
            marginRight: '20px'
        });
        $('#TB_iframeContent').css('width', TB_WIDTH2 + 'px');
        $contents.find('#TB_content_container').css('width', TB_WIDTH);
        
        //by default EITE-9578
        if ($('#TB_iframeContent').css('height') == '0px') {
            $('#TB_iframeContent').css('height', (TB_HEIGHT2 - 2)  + 'px' );
        }
        //$('#TB_iframeContent').css('height', TB_HEIGHT2);
    } else if ($('#TB_ajaxContent').length > 0 && $('#TB_ajaxContent').data('autoscale') == 1) {
        // autoscale 1 - content resize changes window height, div
        TB_HEIGHT2 = $('#TB_content_container').outerHeight() + 2;
        TB_WIDTH2 = TB_WIDTH;
        $('#TB_main DIV.main-b').css({
            marginRight: '20px'
        });
        $('#TB_ajaxContent').css('width', TB_WIDTH2 + 'px').find('#TB_content_container').css('width', TB_WIDTH);
        $('#TB_ajaxContent').css('height', TB_HEIGHT2);
    } else if ($('#TB_ajaxContent').length > 0 && $('#TB_ajaxContent').data('autoscale') == 2) {
        // autoscale 2 - content does not resize window height, div
        TB_HEIGHT2 = TB_HEIGHT + 2;
        if ($('#TB_content_container').outerHeight() < TB_HEIGHT) {
            TB_WIDTH2 = TB_WIDTH;
            $('#TB_main DIV.main-b').css({
                marginRight: '20px'
            });
        } else {
            TB_WIDTH2 = TB_WIDTH + 30;
            $('#TB_main DIV.main-b').css({
                marginRight: '10px'
            });
        }
        $('#TB_ajaxContent').css('width', TB_WIDTH2 + 'px').find('#TB_content_container').css('width', TB_WIDTH);
        $('#TB_ajaxContent').css('height', TB_HEIGHT2);
    } else if ($('#TB_error').length > 0 && $('#TB_error').data('autoscale') == 1) {
        // autoscale 1 - content resize changes window height, div
        TB_HEIGHT2 = $('#TB_content_container').outerHeight() + 2;
        TB_WIDTH2 = TB_WIDTH;
        $('#TB_main DIV.main-b').css({
            marginRight: '20px'
        });
        $('#TB_error').css('width', TB_WIDTH2 + 'px').find('#TB_content_container').css('width', TB_WIDTH);
        $('#TB_error').css('height', TB_HEIGHT2);
    } else {
        // no autoscale - fixed everything
        if ($('#TB_iframeContent').length > 0) {
            $('#TB_iframeContent').contents().find('HTML').css({
                overflow: 'hidden'
            });
// not tested EITE-9578           
//            if ($('#TB_iframeContent').css('height') == '0px') {
//                $('#TB_iframeContent').css('height', TB_HEIGHT  + 'px' );
//            }
        }
        if ($('#TB_ajaxContent').length > 0) {
            $('#TB_ajaxContent').css({
                overflow: 'hidden'
            });
        }
        TB_WIDTH2 = TB_WIDTH;
        TB_HEIGHT2 = TB_HEIGHT + 2;
    }
    $('#TB_content_placeholder').css({
        width: TB_WIDTH2 + 'px',
        height: TB_HEIGHT2 + 'px'
    });
    $("#TB_window").css({
        width: TB_WIDTH2 + 40
    });
    var tb_tmp01w = $('#TB_window').outerWidth() - $('#TB_body').outerWidth() + TB_WIDTH2;
    $("#TB_window").css({
        marginLeft: '-' + parseInt((tb_tmp01w / 2), 10) + 'px',
        width: tb_tmp01w + 'px',
        left: '50%'
    });
	$("#TB_window").removeClass('TB_window_hidden').addClass('TB_window_visible');
}

function tb_display() {

    // display the window
	window.clearTimeout(tb_timer1);
	window.clearTimeout(tb_timer2);

	// Bind scaling events
	if ($('#TB_iframeContent').data('autoscale')) {
		var $contents = $('#TB_iframeContent').contents();
//maybe increase 1 -> 10 ms EITE-9578		
//		$contents.find('BODY').bind('mouseup click', function () { tb_timer2 = window.setTimeout('tb_scale()', 10); });

		$contents.find('BODY').bind('mouseup click', function () { tb_timer2 = window.setTimeout('tb_scale()', 1); });
		$contents.find('BODY').wrapInner('<div id="TB_content_container" class="longtext"></div>');
	}
	if ($('#TB_ajaxContent').data('autoscale')) {
		$('#TB_ajaxContent').bind('mouseup click', function () { tb_timer2 = window.setTimeout('tb_scale()', 1); });
		if ($('#TB_ajaxContent #TB_content_container').length == 0) { $('#TB_ajaxContent').wrapInner('<div id="TB_content_container" class="longtext"></div>'); }
	}
	if ($('#TB_error').data('autoscale')) {
		$('#TB_error').bind('mouseup click', function () { tb_timer2 = window.setTimeout('tb_scale()', 1); });
		if ($('#TB_error #TB_content_container').length == 0) { $('#TB_error').wrapInner('<div id="TB_content_container" class="longtext"></div>'); }
	}
	$("#TB_load").remove();
	tb_scale();
	tb_setTop();
    window.setTimeout(function () {
        $(window).scrollTop(tb_scrollpos);
        if($('#TB_iframeContent').length > 0) {
			$('#TB_iframeContent')[0].contentWindow.document.body.focus();
			//$($('#TB_iframeContent')[0].contentWindow.document.body).find('> :first').attr('tabindex', '1').css('outline', 'none');
			//$($('#TB_iframeContent')[0].contentWindow.document.body).find('[tabindex], INPUT, SELECT, TEXTAREA, BUTTON, A[href]').first().focus().blur().focus();
		}
	}, 1);
}

function tb_setTop() {
	'use strict';
	var desiredtop;
    if ($('#TB_window').outerHeight() - $('#TB_body').outerHeight() + $("#TB_window").outerHeight() > tb_getPageSize()[1]) {
        desiredtop = tb_scrollpos + 10;
	} else {
        desiredtop = tb_scrollpos + 10 + (tb_getPageSize()[1] / 2) - ($("#TB_window").outerHeight() / 2);
	}
    $("#TB_window").css({
		top: (desiredtop > 10 ? desiredtop : 10) + 'px'
	});
}

function tb_remove() {
	'use strict';
	window.clearTimeout(tb_timer1);
	window.clearTimeout(tb_timer2);
	$("#TB_ImageOff").unbind("click");
	$('#TB_window, #TB_overlay, #TB_HideSelect').trigger("tb_unload").unbind().remove();
	$("#TB_load").remove();
	document.onkeydown = "";
	document.onkeyup = "";
	$(window).unbind('thickbox');
    $('INPUT, SELECT, TEXTAREA, BUTTON').focus();
    if (tb_prevfocus !== false) {
        $(tb_prevfocus).focus();
        tb_prevfocus = false;
    }
    tb_isopen = false;
    $(window).scrollTop(tb_scrollpos);
	return false;
}

function tb_parseQuery(query) {
	var Params = {};
	if (!query) {
		return Params;
	} // return empty object
	var Pairs = query.split(/[;&]/);
	for (var i = 0; i < Pairs.length; i++) {
		var KeyVal = Pairs[i].split('=');
		if (!KeyVal || KeyVal.length != 2) {
			continue;
		}
		var key = unescape(KeyVal[0]);
		var val = unescape(KeyVal[1]);
		val = val.replace(/\+/g, ' ');
		Params[key] = val;
	}
	return Params;
}

function tb_getPageSize() {
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w, h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
	'use strict';
	var userAgent = navigator.userAgent.toLowerCase();
	if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
		return true;
	}
}

function addIframeProxy() {
    $('iframe[name]:not(.proxyinit)').addClass('proxyinit').each(function (a, b) {
        var wp = new Porthole.WindowProxy('./proxy.html', $(b).attr('name'));
        wp.addEventListener(function(e){
            // e.origin: Protocol and domain origin of the message
            // e.data: Message itself
            // e.source: Window proxy object, useful to post a response

            if (e.data.action === 'embedframe' && e.source.targetWindowName === $(b).attr('name')) {
                $(b).data('windowProxy').post({
                    'action': 'embedframeResponse',
                    'isresponsive': parseUri(window.location.href).queryKey.responsive ? 'false' : 'true',
                    'width': $(window).width(),
                    'currentHeight': $(b).height(),
                    'name': $(b).attr('name')
                });
            }
            if (e.data.action === 'setframeheightResponse' && e.source.targetWindowName === $(b).attr('name')) {
                if ($(b).height() !== parseInt(e.data.height, 10)) {
                    $(b).css('height', e.data.height);
                    $(b).data('windowProxy').post({
                        'action': 'setframeheight',
                        'currentHeight': $(b).height()
                    });
                }
            }
        });
        windowProxies.push(wp);
        windowProxies = jQuery.grep(windowProxies, function (item) {
            return $('[name="' + item.targetWindowName + '"]').length !== 0;
        });
        $(b).data('windowProxy', wp);
    });
}

jQuery.fn.getPath = function (ref) {
    if (this.length != 1) throw 'Requires one element.';
    var path, node = this;
    while (node.length) {
        var realNode = node[0], name = realNode.localName;
        if (!name) break;
        name = name.toLowerCase();
        if (realNode.id) {
            return name + '#' + realNode.id + (path ? '>' + path : '');
        } else if (realNode.className) {
            name += '.' + realNode.className.split(/\s+/).join('.');
        }
        var parent = node.parent(), siblings = parent.children(name);
        if (ref && $(parent).is(ref)) {
            return path;
        }
        if (siblings.length > 1) name += ':eq(' + siblings.index(node) + ')';
        path = name + (path ? '>' + path : '');
        node = parent;
    }
    return path;
};