//FIX IMAGES-It is first, because it needs to be done fast
$(document).ready( function() {
	if ( !jQuery.browser.msie || (jQuery.browser.msie && jQuery.browser.version != '6.0' ) ) return; 

	//make sure, that all images have width
	$('img').each( function() {
			var width =  $(this).attr('width');			
			if ( width == null || width == '' ) {
				$(this).attr('width', $(this).parent().css('width'));
			}
			else $(this).attr('width', width);
		});
	
	//especially article images must have width less that 471 px. 
	$('.article img').each( function() {
			var width =  $(this).attr('width');
			if ( width > 470 ) {
				$(this).attr('width','470');
			}
		});
});


function clickObject(link, count, time) {
	this.link = link;
	this.time = time;
//	this.addClick = addLinkClick();
}

function hasLink(link, clicks) {
	var state = false;
	for(var i in clicks ) {
		if(clicks[i].link == link){
			state = true;
			continue;
		}
	}
	return state;
}

/**
 * Switches visibility of the 'article/sources' block
 */
$(document).ready(function() {

      	// $("a").click(function(){
	// 	var currentTime = new Date();
	// 	var current_page_id = adsc_key_id;
	// 	var click = new clickObject($(this).attr('href'), currentTime.	getTime());
	// 	if(!click.link.match(/^http:\/\/googleads.*/)) {
	// 		var p13nCookie = $.cookie('netdoktor_personalization');
	// 		var p13nCookieData = [];
	// 		if(p13nCookie){
	// 			p13nCookieData = $.evalJSON(p13nCookie);
	// 			console.log(p13nCookieData);
	// 		}
	// 		p13nCookieData.push(click);
	// 		$.cookie('netdoktor_personalization', $.toJSON(p13nCookieData));
	// 	}
	// });
	
	if ($("#collapsible_src_sw")[0])
	{
		$(".article .article_footer").hide();
	
		$("#collapsible_src_sw").toggle(
			function () {
				this.className = "uncollapsed";
				$(".article .article_footer").show();
				return false;
			},
			function () {
				this.className = "collapsed";
				$(".article .article_footer").hide();
				return false;
			}
		);
	}
});

//------------------------------------------- AUTOCOMPLETE START

function IncludeJavaScript(jsFile)
{
  document.write('<script type="text/javascript" src="'
    + js_text_general_url_static + 'js/' + jsFile + '"></script>'); 
}

IncludeJavaScript('jquery/jquery.bgiframe.min.js');
//IncludeJavaScript('jquery/jquery.dimensions.js');
//IncludeJavaScript('jquery/jquery.ajaxQueue.js');
//IncludeJavaScript('jquery/thickbox-compressed.js');
IncludeJavaScript('jquery/jquery.autocomplete.js');


$().ready(function() 
{
	function findValueCallback(event, data) {
		$('#searchform').submit();
	}
	
	$(":text, textarea").result(findValueCallback).next().click(function() {
		$(this).prev().search();
	});

	$("#searchbox").autocomplete(js_text_general_base_url + "search/suggestions", { minChars:3, selectFirst:false, onFindValue:findValueCallback });
});

//------------------------------------------- AUTOCOMPLETE END

//------------------------------------------- NAVIGATION START

function navi_over(oElement) {

	var oSeperatorLeft = $(oElement).prev();
	var oSeperatorRight = $(oElement).next();

	$(oElement).addClass('show');

	if (oSeperatorLeft && oSeperatorRight) {
		$(oSeperatorLeft).addClass('left_show');
		$(oSeperatorRight).addClass('right_show');
	}

}

function navi_out(oElement) {

	var oSeperatorLeft = $(oElement).prev();
	var oSeperatorRight = $(oElement).next();

	$(oElement).removeClass('show');

	if (oSeperatorLeft && oSeperatorRight) {
		$(oSeperatorLeft).removeClass('left_show');
		$(oSeperatorRight).removeClass('right_show');
	}

}

//------------------------------------------- NAVIGATION END

//------------------------------------------- TABS START


/**
 * Internal note:
 *
 * Puvodni implementace byla udelana obecne a byly na ni postavene nektere widgety. 
 * Pak nekdo udelal novou implementaci, ktera je udelana tak, aby fungovala pro catalog, puvodni byla zakomentovana, 
 * a tak neni divu, ze nektere widgety prestaly fungovat.
  
 * Nechapu, co je na nove fci lepsi nez na tehle, krome toho, 
 * ze nefunguje obecne, a tak treba neni mozne pridat vice jak jeden tab container na jednu stranku.
 * (Osobne to teda nepovazuji za vyhodu, ale uz si nejsem nicim jisty).
 * 
 * Aby opravdu vsechno fungovalo, nechal jsem zde i tu "vylepsenou" implementaci, 
 * ale asi by bylo rozumne to dat do jedne fce, ale tak aby fungovala pro vsechny widgety, co ji vyuzivaji.
 * 
 * Steve
 */
function make_tabs()
{
	var tab_class_name = 'tab-container2';
	$( '.' + tab_class_name + ' .tabs a').click( function() {
									
			var tab_root = $(this).parent();
			while ( ! tab_root.hasClass(tab_class_name) ) {
		  		tab_root = tab_root.parent();
		  	}
		  	
		  	tab_root.find('.tabs .tab').removeClass('active');
		  	tab_root.find('.tabs').removeClass('active');
		  	$(this).parent('.tab').addClass('active');
		  	$(this).parent('.tabs').addClass('active');
		  	
		  	var selector = $(this).attr('name');
		  	
		  	tab_root.find('.content > *').hide();
			tab_root.find('.content .'+selector).show();
			tab_root.find('.content .'+selector).siblings().hide();
			
			return false;
	 });
	$('.' + tab_class_name + ' .tabs a:first').click();
}

$(document).ready(make_tabs);

/**
 * Function makes "tab/catalogue widget" from every div with class '.tab-container'. 
 * @author Steve 
 */
$(document).ready(function() {
	var tab_container = $('.tab-container');
	if (tab_container.length == 0) return true;
	else tab_container = tab_container[0];
	
	if ($(tab_container).hasClass('tab-container-alfa') == true) return true;
	
	$('ul.catalogue .tabs a', tab_container).click( function() {
	//$(tab_container).find('.tab_container .tabs a').click( function() {
		$('ul.catalogue li', tab_container).removeClass('active');
		$(this).parent().addClass('active');
		
		var key = $(this).attr('id').replace('catalogue_link_','')*1;
		
		$('.catalogue_widgets > div').hide();
		$('.catalogue_widgets > div.fragment'+key).show();
		//return false;
	});

	var anchor = document.location.hash.replace('#','');
	if (anchor.length > 0)
	{
		$('a#catalogue_link_'+anchor, tab_container).click();
	}
	else
	{
		//this should have been handled by css
		$('ul.catalogue li.active a', tab_container).click();
	}
});


//------------------------------------------- TABS END

//------------------------------------------- OPENERS START

function make_openers()
{
	$('.opener-content-container').hide();
	$('.opener-content-container:first').show();
	//$('.opener-content-container:first').toggleClass("active");
	
	$('.opener').click( function () {
	
		$(this).toggleClass("active");
		$(this).parent().toggleClass("active");
		
		var opener_root = $(this).parent();
		while ( ! opener_root.hasClass('opener-container') ) {
	  		opener_root = opener_root.parent();
	  	}
	  	
	  	opener_root.find('.opener-content-container').slideToggle('slow');
	  	return false;
	});
}

//------------------------------------------- OPENERS END

//------------------------------------------- ACCORDION START

/**
 * Function make accordions from every div with class 'accordion'.
 * @author Steve 
 */
function make_accordions()
{
	$('.accordion .active .container').show();
	
	$(".accordion_collapse .head .collapse").click(function(){
		if ($(this).parents('li').hasClass('active'))
		{
			//do nothing
		}
		else
		{
			$(this).parents('.accordion').find('.active').removeClass('active').find('.container').slideUp("medium");
			$(this).parents('li').addClass('active').find(".container").slideDown("medium");
		}
	  	return false;
	});	
	
	$(".accordion_lazy .head .collapse").click(function(){
		if ($(this).parents('li').hasClass('active'))
		{
			$(this).parents('li').removeClass('active').find('.container').slideUp("medium");
		}
		else
		{
			$(this).parents('li').addClass('active').find('.container').slideDown("medium");
		}
	  	return false;
	});	
}

//------------------------------------------- ACCORDION END

//------------------------------------------- NEWSLETTER START

/**
 * @author matthes
 */

function setup_newsletter() {
	
	$('#inputFieldForm').submit(function() {
		
		url = this.action;
		value = this.elements['email'].value;
		
		$.post(url,
			    {email: value},
			    function(response)
			    {
			    	
			    	response = eval('('+response+')');
			    	
			    	if(response && response.responseCode == 'OK') {
			    		$('#inputFieldSet').hide();
			    	}
			    	$("#inputFieldMessage").html(response.message);
			    	
			    	if(response.responseCode == 'ERR') {
			    		$("#inputFieldMessage").addClass('error');
			    	}
			    	else {
			    		$("#inputFieldMessage").removeClass('error');
			    	}
			    }
			    
			    );
		return false;
	}
	);
}

//------------------------------------------- NEWSLETTER END

//------------------------------------------- TEASER START

function getIdAfterPrefix(text, prefix)
{
	var found = null;
	var classes = text.split(' ');
	var i=0;
	while (i<classes.length && found === null)
	{
		var candidate = $.trim(classes[i]);
		if (candidate.indexOf(prefix)==0)
		{
			candidate = candidate.replace(prefix,'');
			if (!isNaN(candidate)) found = candidate;
		}
		i++;
	}
	return found;
}

function setTeaser(current, next) {
	$('.teaser'+current).hide();
	$('.teaser'+next).show();	
}

function switchTeaserSet(setId) {
	$('.teaserSet').hide();		
	$('.animationTeaser').hide();
	
	$('#teaserSet'+setId+' .animationTeaser:first').show();
	$('#teaserSet'+setId).show();
	
	
	$('.teaser_navi_box tbody').removeClass('active');
	$('#themeTab'+setId).addClass('active');
	return false;
}
/*
function userSwitchTeaserTab(tabId)
{
	switchTeaserSet(tabId);
	alert('user!');
}
*/
function rotateTeaserTab(navi_box)
{
	var ts = $('tbody', navi_box);
	if (ts.length > 1)
	{
		var s = null;
		var i = 0;
		
		var ieFixFilter = [];
		for (i=0; i < ts.length; i++)
		{
			if (ts[i].id.indexOf('themeTab')==0)
			{ ieFixFilter.push(ts[i]); }
		}
		
		ts = ieFixFilter;
		
		for (i=0; i < ts.length; i++)
		{
			if($(ts[i]).hasClass('active')) s = i;
		}
		if (s === null || (s+1)==ts.length) s = 0;
		else (s++);
		
		s = getIdAfterPrefix(ts[s].id,'themeTab');
		
		
		
		if (s!==null) switchTeaserSet(s);
	}
}

$('document').ready(function() {
	$('.animationTeaser').hide();
	$('.animationTeaser:first').show();
	$('.teaserSet').hide();
	$('.teaserSet:first').show();

	$('.teaser_navi_box').each(function(){
		$('a', this).click(function(){
			switchTeaserSet(getIdAfterPrefix(this.name, 'teaserSet'));
			return false;
		});
	});
	
	$('.teaser_navi_box_random').each(function(){
		var as = $('a', this);
		
		if (as.length > 1)
		{
			var s = Math.random();
			if (s == 1) s = 0.99;
			s = s * as.length;
			s = Math.floor(s);
			switchTeaserSet(getIdAfterPrefix(as[s].name, 'teaserSet'));
		}
	});
	
	$('.teaser_navi_box_rotate').each(function(){
		var rotateParameter = getIdAfterPrefix($(this).attr('class'),'teaser_navi_box_rotate_');
		if (rotateParameter === null) return;
		var timerId = setInterval(rotateTeaserTab, rotateParameter * 1000, this);
		$('a', this).click(function(){
			clearInterval(timerId);
			switchTeaserSet(getIdAfterPrefix(this.name, 'teaserSet'));
			return false;
		});
	});
});

//index animation teaser
$('document').ready(function() {
	$('.animation_teaser_rotate').each( function() {
		var widgetId = getIdAfterPrefix($(this).attr('class'), 'animation_teaser_id');
		var speed = getIdAfterPrefix($(this).attr('class'), 'animation_teaser_rotate_speed');
		//var timerId = setInterval("rotateAnimationTeasers("+widgetId+")", speed*1000, widgetId);
		
		var timerId = setInterval( function () {
			var widget_id = widgetId;
			var teaser_id = getIdAfterPrefix($('.animation_teaser_id'+widget_id+' .active').attr('class'), 'teaser');
			teaser_id++;
			$('.widget_parent'+widget_id).removeClass('active');
			$('.widget_parent'+widget_id).hide();
			
			if ( $('.widget_parent'+widget_id+'.teaser'+teaser_id).length == 0 ) teaser_id=1;
			$('.widget_parent'+widget_id+'.teaser'+teaser_id).addClass('active');
			$('.widget_parent'+widget_id+'.teaser'+teaser_id).show();
		}, speed*1000);
		
		$(this).click( function() {
			clearInterval(timerId);
		});
	});
});


//------------------------------------------- TEASER END

//------------------------------------------- AJAX START

//what to show while loading the new data
function ajaxLoading(divName)
{
	$(divName).html('<p class="loading">' + js_text_ajax_loading + '</p>');
}


//send the pagination via ajax type
function pagination(url, elementId, formId)
{
	if (formId)
	{
		$.ajax({ 
			type: "GET", 
			url: url,
			data: $("#" + formId).serialize(),
			dataType: "html", 
			success: ajaxLoading("#" + elementId),
			complete: function(requestObject, successType){ 
				$("#" + elementId).html(requestObject.responseText);
			} 
		});
	}
	else
	{
		$.ajax({ 
			type: "GET", 
			url: url,
			dataType: "html", 
			success: ajaxLoading("#" + elementId),
			complete: function(requestObject, successType){ 
				$("#" + elementId).html(requestObject.responseText);
			} 
		});
	}
}

//send the pagination via ajax type
var global_refined;
function search_refine(url, refined)
{
	$.ajax({ 
		type: "GET", 
		url: url,
		dataType: "html", 
		success: ajaxLoading("#ajax_results"),
		complete: function(requestObject, successType){ 
			$("#ajax_results").html(requestObject.responseText);
		} 
	});
	
	$(".span_" + global_refined).hide();
	$(".link_" + global_refined).show();
	global_refined = refined;
	$(".link_" + refined).hide();
	$(".span_" + refined).show();		
}

//------------------------------------------- AJAX END

//------------------------------------------- MOUSE WHEEL MIN STARTS

/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-06-20 16:25:35 -0500 (Wed, 20 Jun 2007) $
 * $Rev: 2125 $
 *
 * Version: 2.2
 */
(function($){$.fn.extend({mousewheel:function(f){if(!f.guid)f.guid=$.event.guid++;if(!$.event._mwCache)$.event._mwCache=[];return this.each(function(){if(this._mwHandlers)return this._mwHandlers.push(f);else this._mwHandlers=[];this._mwHandlers.push(f);var s=this;this._mwHandler=function(e){e=$.event.fix(e||window.event);$.extend(e,this._mwCursorPos||{});var delta=0,returnValue=true;if(e.wheelDelta)delta=e.wheelDelta/120;if(e.detail)delta=-e.detail/3;if(window.opera)delta=-e.wheelDelta;for(var i=0;i<s._mwHandlers.length;i++)if(s._mwHandlers[i])if(s._mwHandlers[i].call(s,e,delta)===false){returnValue=false;e.preventDefault();e.stopPropagation();}return returnValue;};if($.browser.mozilla&&!this._mwFixCursorPos){this._mwFixCursorPos=function(e){this._mwCursorPos={pageX:e.pageX,pageY:e.pageY,clientX:e.clientX,clientY:e.clientY};};$(this).bind('mousemove',this._mwFixCursorPos);}if(this.addEventListener)if($.browser.mozilla)this.addEventListener('DOMMouseScroll',this._mwHandler,false);else this.addEventListener('mousewheel',this._mwHandler,false);else
this.onmousewheel=this._mwHandler;$.event._mwCache.push($(this));});},unmousewheel:function(f){return this.each(function(){if(f&&this._mwHandlers){for(var i=0;i<this._mwHandlers.length;i++)if(this._mwHandlers[i]&&this._mwHandlers[i].guid==f.guid)delete this._mwHandlers[i];}else{if($.browser.mozilla&&!this._mwFixCursorPos)$(this).unbind('mousemove',this._mwFixCursorPos);if(this.addEventListener)if($.browser.mozilla)this.removeEventListener('DOMMouseScroll',this._mwHandler,false);else this.removeEventListener('mousewheel',this._mwHandler,false);else
this.onmousewheel=null;this._mwHandlers=this._mwHandler=this._mwFixCursorPos=this._mwCursorPos=null;}});}});$(window).one('unload',function(){var els=$.event._mwCache||[];for(var i=0;i<els.length;i++)els[i].unmousewheel();});})(jQuery);

//------------------------------------------- MOUSE WHEEL MIN END

//------------------------------------------- DIMENSIONS START

/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-09-11 05:38:31 +0300 (ÐÑ, 11 ÑÐµÐ½ 2007) $
 * $Rev: 3238 $
 *
 * Version: @VERSION
 *
 * Requires: jQuery 1.2+
 */

(function($){
	
$.dimensions = {
	version: '@VERSION'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
	
	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		return this[ name.toLowerCase() ]() + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};
	
	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		options = $.extend({ margin: false }, options || {});
		
		return this[ name.toLowerCase() ]()
				+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
				+ num(this, 'padding' + torl) + num(this, 'padding' + borr)
				+ (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;
		
		return val != undefined ?
		
			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo( 
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :
			
			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});

$.fn.extend({
	position: function() {
		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
		
		if (elem) {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();
			
			// Get correct offsets
			offset       = this.offset();
			parentOffset = offsetParent.offset();
			
			// Subtract element margins
			offset.top  -= num(elem, 'marginTop');
			offset.left -= num(elem, 'marginLeft');
			
			// Add offsetParent borders
			parentOffset.top  += num(offsetParent, 'borderTopWidth');
			parentOffset.left += num(offsetParent, 'borderLeftWidth');
			
			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}
		
		return results;
	},
	
	offsetParent: function() {
		var offsetParent = this[0].offsetParent;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return $(offsetParent);
	}
});

var num = function(el, prop) {
	return parseInt($.css(el.jquery?el[0]:el,prop))||0;
};

})(jQuery);

//------------------------------------------- DIMENSIONS END

//------------------------------------------- COOKIES START

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function loadReferrer()
{
	/*console.log(document.referrer);
	
 	match = new RegExp("q=(.[^&]*)","i").exec(document.referrer);
	var google_search_expression = "";

	if ((match) && (match.length == 2))
	{
		google_search_expression = Url.decode(match[1].replace(/\+/g,' '));
		var blacklist = [ 'www.netdoktor.de','netdoktor.de','net doktor.de','netdoktor de','netdoktor','net doctor',
		'netdoc','internet doktor','net-doktor','doktor net','doktor','netdok','net dok','netdoctor.de',
		'netzdoktor','net.doctor','net-doctor','internet arzt','internetarzt','online arzt',
		'internetapotheke','net.doktor.de','doctor net','doktor online','ärzte online' ]
		var key;
		for (key in blacklist)
		{
			google_search_expression = google_search_expression.replace(new RegExp("(^| )"+blacklist[key]+"( |$)","g"),'');
		}
		google_search_expression = google_search_expression.replace(/^\s+|\s+$/g,"");
		$.cookie('google_search', google_search_expression, { path: '/', domain: 'netdoktor.de'});
	}
	else
	{
		if ($.cookie('google_search'))
		{
			google_search_expression = $.cookie('google_search');
		}
	}
	
	if (google_search_expression)
	{
		$("#searchbox").val(google_search_expression);
	}*/
}

//------------------------------------------- COOKIES END

//------------------------------------------- URL ENCODE / DECODE START

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
}

//------------------------------------------- URL ENCODE / DECODE END

function registerClick()
{
	if (typeof IVW == 'string')
	{
		var src = IVW+"?r="+escape(document.URL)+"&d="+(Math.random()*100000);
		
		$('#ivwImg').attr('src',src);
		
		if(typeof console == 'object')
		{
			console.log(src);
		}
	}
}

//ivw clicks
$(document).ready( function() {
	$('.registerClick').click(function(){
		registerClick();
	});
});

//------------------------------------------- ADDITIONAL CONTENT FACTS
/**
 * Initializes the current page and the new page variables when the 
 * script is evaluated for the first time.
 * 
 * @author icy-ice
 */
if ("undefined" === typeof __facts_pg_curr || "undefined" === typeof __facts_pg_new) {
	var __facts_pg_curr = 1;
	var __facts_pg_new = 1;
}

/** 
 * Either registers the click and moves the additional content fact 
 * or reloads the page
 * 
 * @note These two functions it calls were originally in the 
 * onclick event to have the code mode transparent, more effecient  
 * and better maintainable. Lubko argues it's unmaintainable and 
 * illogical to call functions from the onclick event. 
 * Hence we got this wrapper.
 * 
 * @return boolean false
 * 
 * @author icy-ice
 */
function facts_acf_left_onclick() {
	facts_special_register_click(-1);
	moveAdditionalContentFact(-1);
	return false;
}

/** 
 * Either registers the click and moves the additional content fact 
 * or reloads the page
 * 
 * @note These two functions it calls were originally in the 
 * onclick event to have the code mode transparent, more effecient  
 * and better maintainable. Lubko argues it's unmaintainable and 
 * illogical to call functions from the onclick event. 
 * Hence we got this wrapper.
 * 
 * @return boolean false
 * 
 * @author icy-ice 
 */
function facts_acf_right_onclick() {
	facts_special_register_click(1);
	moveAdditionalContentFact(1);
	return false;
}

/**
 * Sets the new facts page and shows the specified additional contect fact
 * 
 * @param  int     page
 * @param  int     fact_id
 * @return boolean false
 * 
 * @author icy-ice
 */
function facts_acf_pagination_item_onclick(page, fact_id) {
	facts_set_page(page);
	showAdditionalContentFact(fact_id);
	loadAdditionalContentFactAnalytics();
	return false;
}

/**
 * Sets the new facts page that facts_special_register_click() checks to perform the reload  
 *
 * @param  int new page
 * @return void
 * 
 * @author icy-ice
 */
function facts_set_page(i) {
	__facts_pg_curr = i;
	__facts_pg_new = i;
}

/**
 * Either registers the click or does something special - reloads the page
 *
 * @desc If the current page is start of the list and you still 
 * try to go more left the page gets reloaded without registering
 * the click. This rule is also applied if the current page is end 
 * of the list and you still try to go right. 
 * The click gets registered via 1px spy and Google analytics.
 * 
 * @param  int -1 or 1 (decrease / increase page number)
 * @return void
 * 
 * @author icy-ice
 */
function facts_special_register_click(i) {
	if ("undefined" === typeof __facts_pg_total)
		__facts_pg_total = $(".acf_pagination .acf_pagination_item").size();
	
	if ((i == -1 && __facts_pg_curr == 1) || (i == 1 && __facts_pg_curr == __facts_pg_total)) {
		location.reload(true);
	} else {
		__facts_pg_new += i;
		__facts_pg_curr = __facts_pg_new;
		registerClick(); // 1px spy
		loadAdditionalContentFactAnalytics(); // Google analytics
	}
}

function loadAdditionalContentFactAnalytics()
{
	if (typeof _gat !== 'undefined')
    {
       var clickTracker = _gat._getTracker("UA-9514872-1");
       clickTracker._initData();
       clickTracker._trackPageview();
    }
}

function showAdditionalContentFact(factItemId)
{
	//remove active class from all elements in pagination
	$("div.acf_pagination div").each(function(i, n)
	{ 
		$("#" + n.id).removeClass('acf_pagination_item_active');
	});
	
	//hide all the content elements
	$("div.acf_center div").each(function(i, n)
	{ 
		$("#" + n.id).css('display', 'none');
	});
	//now everything is hidden and inactive
	
	//and we can make the right ones active
	$("#additional_content_fact_item_" + factItemId).toggle();
	$("#bottom_additional_content_fact_item_" + factItemId).addClass('acf_pagination_item_active');
}

function moveAdditionalContentFact(whereToMove)
{
	var temp = $("div.acf_center div").get();

	if (whereToMove == -1)
	{
		temp.reverse();
	}

	var found = false;
	$(temp).each(function(i, n)
	{ 
		if (found)
		{
			var underscores = n.id.split("_");
			showAdditionalContentFact(underscores[underscores.length - 1]);
			return false;
		}
	
		if ($("#" + n.id).css('display') == "block")
		{
			found = true;
		}
	});
}

function sprintf( ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Ash Searle (http://hexmen.com/blog/)
    // + namespaced by: Michael White (http://getsprink.com)
    // +    tweaked by: Jack
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Paulo Ricardo F. Santos
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: sprintf("%01.2f", 123.1);
    // *     returns 1: 123.10
    // *     example 2: sprintf("[%10s]", 'monkey');
    // *     returns 2: '[    monkey]'
    // *     example 3: sprintf("[%'#10s]", 'monkey');
    // *     returns 3: '[####monkey]'
 
    var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
    var a = arguments, i = 0, format = a[i++];
 
    // pad()
    var pad = function(str, len, chr, leftJustify) {
        if (!chr) {chr = ' ';}
        var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
        return leftJustify ? str + padding : padding + str;
    };
 
    // justify()
    var justify = function(value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
        var diff = minWidth - value.length;
        if (diff > 0) {
            if (leftJustify || !zeroPad) {
                value = pad(value, minWidth, customPadChar, leftJustify);
            } else {
                value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
            }
        }
        return value;
    };
 
    // formatBaseX()
    var formatBaseX = function(value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
        // Note: casts negative numbers to positive ones
        var number = value >>> 0;
        prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
        value = prefix + pad(number.toString(base), precision || 0, '0', false);
        return justify(value, prefix, leftJustify, minWidth, zeroPad);
    };
 
    // formatString()
    var formatString = function(value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
        if (precision != null) {
            value = value.slice(0, precision);
        }
        return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
    };
 
    // doFormat()
    var doFormat = function(substring, valueIndex, flags, minWidth, _, precision, type) {
        var number;
        var prefix;
        var method;
        var textTransform;
        var value;
 
        if (substring == '%%') {return '%';}
 
        // parse flags
        var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
        var flagsl = flags.length;
        for (var j = 0; flags && j < flagsl; j++) {
            switch (flags.charAt(j)) {
                case ' ': positivePrefix = ' '; break;
                case '+': positivePrefix = '+'; break;
                case '-': leftJustify = true; break;
                case "'": customPadChar = flags.charAt(j+1); break;
                case '0': zeroPad = true; break;
                case '#': prefixBaseX = true; break;
            }
        }
 
        // parameters may be null, undefined, empty-string or real valued
        // we want to ignore null, undefined and empty-string values
        if (!minWidth) {
            minWidth = 0;
        } else if (minWidth == '*') {
            minWidth = +a[i++];
        } else if (minWidth.charAt(0) == '*') {
            minWidth = +a[minWidth.slice(1, -1)];
        } else {
            minWidth = +minWidth;
        }
 
        // Note: undocumented perl feature:
        if (minWidth < 0) {
            minWidth = -minWidth;
            leftJustify = true;
        }
 
        if (!isFinite(minWidth)) {
            throw new Error('sprintf: (minimum-)width must be finite');
        }
 
        if (!precision) {
            precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
        } else if (precision == '*') {
            precision = +a[i++];
        } else if (precision.charAt(0) == '*') {
            precision = +a[precision.slice(1, -1)];
        } else {
            precision = +precision;
        }
 
        // grab value using valueIndex if required?
        value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
 
        switch (type) {
            case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
            case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
            case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
            case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
            case 'i':
            case 'd':
                number = parseInt(+value, 10);
                prefix = number < 0 ? '-' : positivePrefix;
                value = prefix + pad(String(Math.abs(number)), precision, '0', false);
                return justify(value, prefix, leftJustify, minWidth, zeroPad);
            case 'e':
            case 'E':
            case 'f':
            case 'F':
            case 'g':
            case 'G':
                number = +value;
                prefix = number < 0 ? '-' : positivePrefix;
                method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
                textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
                value = prefix + Math.abs(number)[method](precision);
                return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
            default: return substring;
        }
    };
 
    return format.replace(regex, doFormat);
}


function setup_toolbars()
{
    var resizing = function(e) {
        var frame = $("#tb-toolbar");
        var origHeightFrame = frame.height();
        var origPosYGrip = $("#tb-toolbar-grip").offset().top;
        var origWidthFrame = frame.width();
        var origPosXGrip = $("#tb-toolbar-grip").offset().right;

        var gripHeight = $("#tb-toolbar-grip").height();
        frame.height(origHeightFrame - e.pageY + origPosYGrip);
        frame.width(origWidthFrame - e.pageX + origPosXGrip)
        return false;
    }
    var stopResizing = function(e) {
        $(document).unbind("mouseover", resizing);
    }

    $("#tb-toolbar-grip").mouseup(stopResizing);

    $("#tb-toolbar-grip").mousedown(function(e) {
        e.preventDefault();
        $(document).bind("mouseover", resizing).mouseup(stopResizing);
    });

}
