/* border-radius plugin */

	(function($){
		$.fn.borderRadius = function(radius){
			return this.each(function(e){
				$(this).css({
					'border-radius': radius,
					'-moz-border-radius': radius,
					'-webkit-border-radius': radius
				});
			});
		};
	})(jQuery);

/*-- Iframe popup --*/

	(function($){
		$.fn.IframePopup = function(options){
		    // Settings
			var IP_Settings = {
				margin: 20, // Margin from the iframe popup
				width: 700, // Default popup width
				height: 500, // Default popup height
				borderradius: '10px'  // Popup border-radius
			};
			var IP_Settings = $.extend(IP_Settings, options);
      
			// Create iframe popup
			createIframePopup();
			
            // Open iframe popup
            $(this).click(function(){
              // Get popup size from rel attribut
              var popupHeight = this.rel.split(',')[1];
              var popupWidth = this.rel.split(',')[0];
              if(popupWidth == null || popupHeight == null){
                popupWidth = IP_Settings.width;
                popupHeight = IP_Settings.height;
              }
          
              // IE6 Fallback
              if($.browser.msie && $.browser.version=="6.0")
              {
                  popupWindow(this, popupHeight, popupWidth);
              }
              else
              {
              	// Hide scrollbar and fadein overlay
              	$('body, html').css('overflow', 'hidden');
              	$('.ip_overlay').css({'display':'block', 'opacity':0}).fadeTo('slow', 0.8);
              	// Set tabindex="-1" to content
              	$('a, input, textarea, select, button').not('.close').each(function(){
              		$(this).addClass('tabindex').attr('tabindex', '-1');
              	});
              	// Set popup size
              	var NormalCSS = {
              		'bottom': 'auto',
              		'height': popupHeight+'px',
              		'left': '50%',
              		'margin-left' : Math.floor(-(popupWidth)/2)+'px',
              		'margin-top': Math.floor(-(popupHeight)/2)+$(window).scrollTop()+'px',
              		'max-height': popupHeight+'px',
              		'top': '50%',
              		'width' : popupWidth+'px'
              	};
              	var FlexibleCSS = {
              		'bottom': IP_Settings.margin+'px',
              		'height': 'auto',
              		'margin-top': 0,
              		'top': IP_Settings.margin+'px'
              	};
              	// Normal iframe popup size
              	$(ip_popup).css(NormalCSS).borderRadius(IP_Settings.borderradius).show();
              	// Flexible iframe popup size
              	$(window).resize(function(){
              		($(this).height() <= ($(ip_popup).height()+2*IP_Settings.margin)) ? $(ip_popup).css(FlexibleCSS) : $(ip_popup).css(NormalCSS);
              	});
              	($(window).height() <= ($(ip_popup).height()+2*IP_Settings.margin)) ? $(ip_popup).css(FlexibleCSS) : $(ip_popup).css(NormalCSS);
              	// Insert iframe title
              	$(ip_title).html(this.title);
              	// Insert iframe content
              	$(ip_popup).addClass('ip_loading');
              	$(ip_iframe).attr('src', this);	
              	// Preloader
              	$(ip_iframe).css('visibility', 'hidden');
              	$(ip_iframe).load(function(){
              		$(ip_popup).removeClass('ip_loading');
              		$(ip_iframe).css('visibility', 'visible');
              	});
                }
                return false;	
    	    });
	   $(document).bind('keydown', keyDown);

			// Popup window (IE6 Fallback)
      function popupWindow(url, h, w){
        i=Math.round(Math.random*100);
        var winl = (screen.width-w)/2;
        var wint = (screen.height-h)/2;       
        lvobj=window.open(url,'w'+i,'height='+h+',width='+w+',scrollbars=yes,top='+wint+',left='+winl)
        lvobj.focus();
      }

      // Close popup
			function closeIframePopup(){
				$('body').css('overflow', bodyOverflow);
				$('html').css('overflow', htmlOverflow);
				$('.ip_popup').hide();
				$('.ip_overlay').fadeOut('slow');
				$(window).unbind('resize');
				// Remove tabindex="-1"
				$('.tabindex').each(function() {
					$(this).removeClass('tabindex').removeAttr('tabindex');
				});
			}
	
			// Keyboard events
			function keyDown(event){
				var code = event.keyCode;
				return ($.inArray(code, [27,88,67]) >= 0) ? closeIframePopup() : true;
			}

			// Create iframe popup
			function createIframePopup(){
				//alert("1");
        $('body').append(
					ip_overlay = $('<div>').attr({ 'class': 'ip_overlay' }).hide().click(closeIframePopup),
					ip_popup = $('<div class>').attr({ 'class': 'ip_popup' }).append(
						ip_close = $('<a>').attr({ 'class': 'close', href: '#', title: close+' [ESC]' }).text(close).click(closeIframePopup),
						ip_title = $('<h2>').attr({ 'class': 'title' }),

						$('<div>').attr({ 'class': 'ip_content' }).append(
							ip_iframe = $('<iframe>').attr({ 'src': '', 'frameborder': '0' })
						)
						
					
					).hide()
				);
				//alert("2");
				$([
					bodyOverflow = $('body').css('overflow'),
					htmlOverflow = $('html').css('overflow')
				])
			//alert("3");
      }
		};
	})(jQuery);


/*-- DOM -- */

	$(function(){
		// Iframe popup
		if 	($('.popup').length) {
		$('.popup').IframePopup();
		}
	});


/* Location Map */

$(function initLocationMap() {
	$('div.locationmap a.mapicon').each(function(i) {
		var id = this.rel;
		this.mapinfo = $('#mapinfo_' + id);
		this.mapinfo.css({
			display: 'block',
			opacity: 0
		});
		$(this).click(function(event) {
			var id = this.rel;
			// event.preventDefault();
			$('div.locationmap a.mapicon').each(function(i) {
				if(id != this.rel) {
					if(this.mapinfo.css('opacity') > 0) {
						this.mapinfo.stop().animate({
							opacity: 0
						}, 600, "linear", function(){
							$(this).css({'visibility': 'hidden'});
						});
					}
				}
			});
			var maptop = $('img.map').offset().top;
			var mapleft = $('img.map').offset().left;
			if(this.mapinfo.css('opacity') > 0) {
				this.mapinfo.stop().animate({
					opacity: 0
				}, 600, "linear", function(){
					$(this).css({'visibility': 'hidden'});
				});
			}
			else {
				this.mapinfo.css({
					visibility: 'visible',
					top: (event.pageY - maptop + $(this).height()) + 'px',
					left: (event.pageX - mapleft + $(this).width()) + 'px'
				});
				this.mapinfo.stop().animate({
					opacity: 1
				}, 600, "linear", function() {
					$(this).css({'visibility': 'visible'});
				});
			}
		});	
       
       	
	});

    $('.mapinfo .close').click(function() {
        $('.mapinfo').animate({opacity: 0}, 600, "linear", function(){
			$('.mapinfo').css({'visibility': 'hidden'});
		});
    });

});


/* Make Select bigger on mouseover */

$(function() {
	
    $('#rightbar #locations select').hover(function() {
        $(this).css({width: '193px'});
    });
 
    $('#contentbox').hover(function() {
        $('#rightbar #locations select').css({width: '136px'});
    });
    $('#servicenav').hover(function() {
        $('#rightbar #locations select').css({width: '136px'});
    });
    $('#searchbox').hover(function() {
        $('#rightbar #locations select').css({width: '136px'});
    });

});

/* Make no margin on the last p when div class is design_class_2 */

$(function() {

    if( $('.design_class_2').length ) {
        $('.design_class_2 p:last').css('margin', '0px');
        $('.design_class_2 ul').css('margin-bottom', '0px');
    }
    
});

/* Random-News-Startpage */

$(function() {
    if($("#randomnews").length > 0) {
        var newspool = $('.randomnews_item');
        var imagepool = $('.randomnews_image');
        var counter = Math.ceil(Math.random() * newspool.length);

        function swapRandomImages() {
            $("#randomnews").css('backgroundImage', 'url(' + imagepool[counter-1].href + ')');
            $('#currentnews').html(newspool[counter-1].innerHTML);
        }

        /* on start */
        $("#randomnews").hide().fadeIn(800);
        swapRandomImages();

        /* on click back */
        $("#random_back").click(function(event){
            event.preventDefault();
            $("#randomnews").fadeOut(800, function() {
        	    if(counter == 1) {counter = imagepool.length;}
        	    else {counter--;}
        	    swapRandomImages();
                $('#randomnews').fadeIn(800);
            });
        });

        /* on click forward */
        $("#random_forward").click(function(event){
            event.preventDefault();
            $("#randomnews").fadeOut(800, function() {
                if(counter == imagepool.length) {counter = 1;}
                else {counter++;}
        	    swapRandomImages();
        	    $('#randomnews').fadeIn(800)
            });
        });
    }
});

/*--- Team ---*/

var employees = new Array();
var morphine = new Array(); //saves Morph references for each image
var originalslogan;
$('domready', function() {
	if($('#team_js_container').length) {

		$('.member_information .member').each(function(i) {
			var member = this;
			var eles = $(member).children();
			employees[i] = new Object();
			eles.each(function(s) {
				var el = this;
				employees[i][el.className.toLowerCase()] = el.innerHTML;
			});
		});

		originalslogan = $('#slogan').find('div')[0].innerHTML;

		var cont = $('#team_js_container');

		var employeesPos = new Array(0, 107, 218, 324, 418);
		$(employees).each(function(i) {
			var el = this;
			var newdiv = document.createElement('div');
			var newimg = document.createElement('img');
			//newdiv.inject(cont, 'top');
			if(cont.find('div').length) {
				$(newdiv).insertBefore(cont.find('div')[0]);
			}
			else {
				$(cont).append(newdiv);
			}
			newdiv.id = 'mapic_'+i;
			newdiv.className = 'mapics ';
			$(newdiv).mouseover(function() {
				teamActivateMe(this);
			});
			$(newdiv).mouseout(function() {
				teamShowAll(this);
			});
			//$(newdiv).click(function() {
			//	document.location.href = this.vita;
			//});
			newdiv.vita = el['vita'];
			newdiv.name = el['name'];
			newdiv.number = i;
			newimg.src = el['imagecloseurl'];
			newimg.alt = el['name'];
			newimg.style.width = el['imageclosewidth'] + 'px';
			newimg.style.height = el['imagecloseheight'] + 'px';
			//newimg.inject(newdiv, 'bottom');
			$(newdiv).append(newimg);
			morphine[i] = $(newdiv);
		});

		showPartnerText(0);
	}
});

function teamActivateMe(div) {
	showPartnerText(div.number + 1);

	document.getElementById('slogan').getElementsByTagName('div')[0].innerHTML = '<span class="name">' + div.name + '</span>';

	$('#team_js_container div').each(function(i) {
		if(div.number == i) {
			morphine[i].stop().animate({
				opacity: 1
			}, 200);
		}
		else {
			morphine[i].stop().animate({
				opacity: 0.5
			}, 200);
		}
	});
}

function teamShowAll(div) {
	showPartnerText(0);

	document.getElementById('slogan').getElementsByTagName('div')[0].innerHTML = originalslogan;

	$('#team_js_container div').each(function(i) {
		morphine[i].stop().animate({
			opacity: 1
		}, 200);
	});
}

function showPartnerText(number) {
	var team_item = document.getElementById('team_item');
	if(team_item) {
		var divs = team_item.getElementsByTagName('div');
		for(i=0; i<divs.length; i++) {
			if(divs[i].parentNode.id == "team_item") {
				$(divs[i]).css('display', 'none');
			}
		}
	}

	var text = $('#ma'+number);
	if(text) {
		//text.css('display', 'block');
	}
}


/* doing business in */

var activeid = "";
$(function() {
    
    if( $('#doing_overview area').length > 0 ) {
    
        var doing_areas = $('.continent');
        
        doing_areas.each(function() {

            this.hovermap = parseInt(this.className.match(/(\d+)/, "")[0])
            
            $(this).click(function() {

                var continent = this;
                doing_areas.each(function() {
                    var currentclass = parseInt(this.className.match(/(\d+)/, "")[0])
                    if(continent.hovermap != currentclass) {
                        $('.continent_items').stop().hide();
                        $('.hover_map').stop().hide();
                        $('h3.continent').stop().removeClass('active');
                        $('#continent_' + continent.hovermap).stop().css({width: '0'});
                        $('#continent_' + continent.hovermap + ' h2').hide();
                    }
                });

                $('#map_' + continent.hovermap).show().css({opacity: '1'});
                $('h3.continent_' + continent.hovermap).addClass('active');
                var currentheadline_x = Number($('h3.continent_' + continent.hovermap).css('top').replace('px', '')) - Number($('h3.continent_' + continent.hovermap).height()) - 1 + 'px';
                var currentheadline_y = Number($('h3.continent_' + continent.hovermap).css('left').replace('px', '')) + Number($('h3.continent_' + continent.hovermap).width()) + 34 + 'px';
                $('#continent_' + continent.hovermap).css({top: currentheadline_x, left: currentheadline_y});
                
                if(this.hovermap == 6565) {
                    $('#continent_' + continent.hovermap).animate({width: '330px'}, 1500);
                }
                else if (this.hovermap == 6588) {
                    $('#continent_' + continent.hovermap).animate({width: '136px'}, 1500);
                }
                else {
                    $('#continent_' + continent.hovermap).animate({width: '170px'}, 1500);
                }
                
                $('#continent_' + continent.hovermap + ' h2').fadeIn(1500);
                activeid = continent.hovermap;
            });
            
            $(this).mouseenter(function() {
                var continent = this;
                if(activeid != continent.hovermap)
                    $('#map_' + continent.hovermap).show().css({opacity: '0.6'});
            });

            $(this).mouseleave(function() {
                var continent = this;
                if(activeid != continent.hovermap)
                    $('#map_' + continent.hovermap).hide();
            });
            
        })
        
        $('.close_continent_items').click(function(event) {

            var currentClickId = $(this).parent().attr('id');
            currentClickId = parseInt(currentClickId.match(/(\d+)/, "")[0]);
        
            $(this).parent().css({display: 'none'});
            $('#map_' + currentClickId).hide();
            $('h3.continent_' + currentClickId).removeClass('active');
            activeid = '';
            return false;
        });
    
    }
  
})


$(function() {

    if($('#accordion').length) {
        $('#accordion').accordion({ autoheight: false, header: 'h3.toggler' });
    }

    initDatevGallery('smoothbox');

});

/* scripts for datev */

/* set opacity of any object */
function opacity(obj, value) {
	obj.style.opacity = value;
	obj.style.filter = 'alpha(opacity=' + value*100 + ')';
}

/* fader functions */
var faderQueue = new Array();
var faderInterval;
function fader(options) {
	var obj = options.obj;
	var inout = options.inorout;
	var maxopacity = options.maxopacity;
	var alphastep = options.alphastep;
	var oncomplete = options.oncomplete;

	obj.oncomplete = oncomplete;
	obj.alphastep = alphastep;
	obj.maxopacity = maxopacity;
	if(!obj.currentopacity) {
		if(inout == 'in') {
			obj.currentopacity = 0;
			opacity(obj, 0);
		}
		else {
			obj.currentopacity = maxopacity;
			opacity(obj, maxopacity);
		}
	}
	obj.fade = inout;
	obj.style.display = 'block';

	faderQueue.push(obj);
	if(!faderInterval) {
		faderInterval = window.setInterval('darthFader()', 20);
	}
}

function darthFader() {
	if(faderQueue.length > 0) {
		for(i=0; i<faderQueue.length; i++) {
			var obj = faderQueue[i];

			if(obj.fade == 'in') {
				obj.currentopacity += obj.alphastep;
				opacity(obj, obj.currentopacity);

				if(obj.currentopacity >= obj.maxopacity) {
					if(obj.oncomplete) {
						obj.oncomplete(obj);
					}
					faderQueue.splice(i, 1); // remove object from queue
				}
			}
			else {
				if(obj.currentopacity > obj.alphastep) // don't go less than 0
					obj.currentopacity = 0;
				else
					obj.currentopacity -= obj.alphastep;

				opacity(obj, obj.currentopacity);

				if(obj.currentopacity <= 0 ) {
					obj.style.display = 'none';
					if(obj.oncomplete) {
						obj.oncomplete(obj);
					}
					faderQueue.splice(i, 1); // remove object from queue
				}
			}
		}

		if(faderQueue.length <= 0) {
			window.clearInterval(faderInterval);
			faderInterval = undefined;
		}
	}
}

/* init gallery */
var galleryObjects = new Array();
var activeGalleryObj;
function initDatevGallery(galleryclass) {
	var eles = document.getElementsByTagName('*');
	var container = document.getElementById(galleryclass + '_container');
	if(!container) {
		container = document.createElement('div');
		container.id = galleryclass + '_container';
		container.className = "gallerycontainer";
		if(navigator.appVersion.indexOf('MSIE 6') > -1) {
			container.style.display = 'none';
		}
		opacity(container, 0);
		document.body.appendChild(container);
	}
	var loading = document.getElementById(galleryclass + '_loading');
	if(!loading) {
		loading = document.createElement('div');
		loading.id = galleryclass + '_loading';
		loading.className = "galleryloading";
		document.body.appendChild(loading);
	}
	var content = document.getElementById(galleryclass + '_content');
	if(!content) {
		content = document.createElement('div');
		content.id = galleryclass + '_content';
		content.className = "gallerycontent";
		content.style.top = '50%';
		content.style.left = '50%';
		content.style.width = 800 + 'px';
		content.style.height = 600 + 'px';
		content.style.marginTop = -400 + 'px';
		content.style.marginLeft = -300 + 'px';
		content.style.background = '#fff';
		content.style.display = 'none';
		content.style.overflow = 'hidden';
		opacity(content, 0);
		document.body.appendChild(content);
	}
	for(i=0; i<eles.length; i++) {
		if(eles[i].className.indexOf(galleryclass) > -1) {
			eles[i].number = i;
			eles[i].galleryclass = galleryclass;
			galleryObjects.push(eles[i]);
			eles[i].onclick = function() {
				if(navigator.appVersion.indexOf('MSIE 6') > -1) {
					document.location.href = '#';
				}
				activeGalleryObj = this;
				fader({
					obj: document.getElementById(activeGalleryObj.galleryclass + '_container'), 
					inorout: 'in',
					maxopacity: 0.7,
					alphastep: 0.1,
					oncomplete: function(container) {
						var content = document.getElementById(activeGalleryObj.galleryclass + '_content');
						content.innerHTML = '<a class="closer" href="#"><span>Schließen</span></a>';
						if(activeGalleryObj.className.indexOf('iframe') > -1) {
							var title = activeGalleryObj.title;
							if(title) {
								content.innerHTML += '<div class="title">' + title + '</div>';
							}
							content.innerHTML += '<iframe frameborder="0" src="' + activeGalleryObj.href + '"></iframe>';
							var iframe = content.getElementsByTagName('iframe')[0];
							content.style.display = 'block';
							content.style.width = (iframe .offsetWidth+40) + 'px';
							content.style.height = (iframe.offsetHeight+40) + 'px';
							content.style.marginTop = 0-Math.round((iframe.offsetHeight+40)/2) + 'px';
							content.style.marginLeft = 0-Math.round((iframe .offsetWidth+40)/2) + 'px';
							fader({
								obj: content, 
								inorout: 'in',
								maxopacity: 1,
								alphastep: 0.1,
								oncomplete: function() {
									var closer = document.getElementById(activeGalleryObj.galleryclass + '_content').getElementsByTagName('a')[0];
									closer.onclick = document.getElementById(activeGalleryObj.galleryclass + '_container').onclick;
								}
							});
						}
						else {
							content.innerHTML += '<div class="text"><img src="#" alt="" /></div>';
							var img = content.getElementsByTagName('img')[0];
							if(img) {
								img.onload = function() {
									document.getElementById(activeGalleryObj.galleryclass + '_loading').style.display = 'none';
									var content = document.getElementById(activeGalleryObj.galleryclass + '_content');
									content.style.display = 'block';
									var imgwidth = this.offsetWidth + 40;
									var imgheight = this.offsetHeight + 40;
									content.style.width = imgwidth + 'px';
									content.style.height = imgheight + 'px';
									content.style.marginTop = 0-Math.round(imgheight/2) + 'px';
									content.style.marginLeft = 0-Math.round(imgwidth/2) + 'px';
									content.style.textAlign =  'center';
									fader({
										obj: content, 
										inorout: 'in',
										maxopacity: 1,
										alphastep: 0.1,
										oncomplete: function() {
											var closer = document.getElementById(activeGalleryObj.galleryclass + '_content').getElementsByTagName('a')[0];
											closer.onclick = document.getElementById(activeGalleryObj.galleryclass + '_container').onclick;
										}
									});
								}
								img.src = activeGalleryObj.href;
							}
						}
						container.onclick = function() {
							document.getElementById(activeGalleryObj.galleryclass + '_content').innerHTML = "";
							fader({
								obj: document.getElementById(activeGalleryObj.galleryclass + '_content'), 
								inorout: 'out',
								maxopacity: 1,
								alphastep: 0.1,
								oncomplete: function() {
								}
							});
							fader({
								obj: document.getElementById(activeGalleryObj.galleryclass + '_container'), 
								inorout: 'out',
								maxopacity: 0.7,
								alphastep: 0.1,
								oncomplete: function() {
									document.getElementById(activeGalleryObj.galleryclass + '_container').onclick = function() {};
								}
							});
							document.getElementById(activeGalleryObj.galleryclass + '_loading').style.display = 'none';
						}
						var loading = document.getElementById(activeGalleryObj.galleryclass + '_loading');
						loading.style.display = 'block';
						loading.onclick = container.onclick;
					}
				});
				return false;
			}
		}
	}
}
