var popup;

$(function () {

	if (!($.browser.msie && $.browser.version < 7)) {
	
		initRoundedImages();
		initPromotionArea();
		initTargetBlank();
		initForms();
				
		$('.ctype2').each(function(){
			$(this).find('p:last').addClass('last');
		});
		
        var strategic_hover 	  = false;
		
		$("#strategic a[rel^=strategic]:not(.iframe)").each(function(){
		       
		        var $this     = $(this);
		        var href      = $this.attr('href');
		        var url       = href.replace(/\?.*/,'');

		        $this.mouseenter(
		        		  function () {
		        			  strategic_hover = true;
		        			  	$.fancybox.close();
				                $.fancybox({'padding'       : 0,
				                        	'overlayShow'   : false,
				                        	'titleShow'		: false,
				                    		'href'			: url,
				  	                      	'transitionIn'  : 'none',
				  	                      	'transitionOut' : 'none',
				  	                      	'showCloseButton' : false,
				  	            		 	'speedIn'		:  0,
				  	            		 	'speedOut'		:  0,
				  	            		 	'onComplete'    : function(){ if(!strategic_hover) setTimeout('$.fancybox.close();',300); }
				                });
		        		  });
		        
		        $this.mouseleave(
	        		function () {
	    			  if (strategic_hover) {
	    				  strategic_hover = false;
	    				  $.fancybox.close();
	    			  }
	    		});
	
	    });
		
		$("#strategic a[rel^=strategic]")
			.fancybox({'padding'       : 0,
					   'width'		   : 640,
					   'height'		   : 360,
					   'titleShow'	   : false,       		
				       'transitionIn'  : 'elastic',
				       'transitionOut' : 'elastic',
				       'easingIn'      : 'easeOutBack',
				       'easingOut'     : 'easeInBack',
				       'onComplete'    : function(){ strategic_hover = false; }				       
		});

		$("a[href$='.pdf']").mousedown(function(){
			var $this = $(this);		
			if($this.is("a[href$='.pdf?mo']")) return false;		
			var href = $this.attr('href');
			$this.attr('href', href+'?mo');		
			return true;
		});
		
		$("a[href*='modulbox.de/showcase']").click(function(){
			var $this = $(this);			
			var href = $this.attr('href');	
			$this.removeAttr('target');
			popup=window.open(href,'popup','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,width=920,height=640,top=50,left=50'); 
			popup.focus();
			return false;
		});	
		
		$("a[href*='youtube.com/v/']").fancybox({
					   'padding'       : 0,
					   'width'		   : 640,
					   'height'		   : 360,
					   'titleShow'	   : false,
					   'type'		   :'iframe',
				       'transitionIn'  : 'elastic',
				       'transitionOut' : 'elastic',
				       'easingIn'      : 'easeOutBack',
				       'easingOut'     : 'easeInBack'
		});
	
		$('#layout_18 a').attr('target','_top');
		
		if (get_vars['overlay']  != undefined && get_vars['url'] != undefined) {

			$.fancybox({'padding'      : 0,
					   'width'		   : 670,
					   'height'		   : '85%',
					   'titleShow'	   : false,
					   'type'		   : 'iframe',
				       'transitionIn'  : 'elastic',
				       'transitionOut' : 'elastic',
				       'easingIn'      : 'easeOutBack',
				       'easingOut'     : 'easeInBack',
				       'href'		   : './'+get_vars['url']+'?overlay=1' });
	
		}
	}
});

function equalHeights(obj) {
	         
	obj.each(function(){

		var $this    = $(this);
		var new_h    = $this.css('height').replace(/px/,'')*1;
		var children = $this.children()
		var child    = children.eq(0);

		if (!child.length || child.is('.equal_heights')) return true;

		var padding_top = child.css('paddingTop').replace(/px/,'')*1;
		var padding_bottom = child.css('paddingBottom').replace(/px/,'')*1;
		new_h = new_h - padding_top - padding_bottom;

		children.height(new_h).css('background','red');
		children.addClass('equal_heights');
	});

	setTimeout("initCorners()",1000); 
};

function initTargetBlank() {
	var h = window.location.host.toLowerCase();
	$("a[href^='http']:not(a[href^='http://" + h + "']):not(a[href^='http://www." + h + "']), a[href$='.pdf'], .download_list a").attr("target", "_blank");
}

function initPromotionArea() {
	
	var distance  		= 1280; 
	var duration  		= 800;

	var hash	  		= window.location.hash;
	var promotion_area 	= $('#promotion_area');
	var next 	 		= promotion_area.find('.next');	
	var prev 	  		= promotion_area.find('.prev');
	var menu 	  		= promotion_area.find('.menu');
	var stage 			= promotion_area.find('.stage');
	var items    		= stage.find('.item');	
	var total     		= 0;

	var interval        = null;
	var autoplay		= true;
	var autodur 		= parseFloat(CJO_PROMOTION_DURATION);

	stage.scrollTo(0, 0, {axis:'x'});
	
	if (hash == undefined || hash == '' ) {
		current = 1;
		autoplay = true;
	} else {
		current = hash.replace(/#/,'');
	}

	if (autodur == undefined || autodur < 1000) {
		autoplay = false
	}

	items.each(function(i) {
		total 	  = i+1;
		var $this = $(this);
		var title = $this.find('h2').text();
		var css	  = (i == 0) ? 'current' : '';
		menu.append('<a href="#'+total+'" title="'+title+'" class="'+css+'">'+title+'</a>');
		
	});
	
	var menu_items = menu.find('a');
	
	menu_items.click(function(){
		clearInterval(interval);
		var $this = $(this);
		current = $this.attr('href').replace(/#/,'');
		updatePromotionArea();
		return false;
	});
	
	next.click(function(){
		clearInterval(interval);
		var new_current = current+1;
		current = (new_current <= total) ? new_current : 1; 
		updatePromotionArea();
		return false;
	});
	
	prev.click(function(){
		clearInterval(interval);
		var new_current = current-1;
		current = (new_current >= 1) ? new_current : total;
		updatePromotionArea();		
		return false;
	});	
	
	var updatePromotionArea = function() {

		if (!menu_items.eq(current-1).length) current = 1;
		
		var num = current-1;
		var next_num = (num+1 < total) ? num+1 : 0;
		var prev_num = (num-1 >= 0) ? num-1 : total-1;
		
		menu_items.removeClass('current');
		menu_items.eq(num).addClass('current');
		
		next.attr('title', menu_items.eq(next_num).attr('title'));
		prev.attr('title', menu_items.eq(prev_num).attr('title'));

		stage.scrollTo((distance*num)+'px', duration, { axis:'x', easing: 'easeInOutExpo' });
	}
	
	var autoUpdatePromotionArea = function() {
		
		clearInterval(interval);
		
		interval = setInterval(function(){
			var new_current = current+1;
			current = (new_current <= total) ? new_current : 1;
			updatePromotionArea();
		}, autodur);

	}
	
	updatePromotionArea();
	
	if (autoplay) {
		autoUpdatePromotionArea();
	}
}

function initFormLabelToDefault() {
	
	var forms = $('form');
	
		forms.submit(function(){
			$(this)
				.find('input[type=text], textarea')
				.each(function(){
					toggleLabel($(this), 'remove')
				});
		})	
		.find('input[type=text], textarea')
		.each(function(){
			
			var $this = $(this);
			toggleLabel($this, 'add');
			
			$this.blur(function(){
				toggleLabel($this, 'add');
			});
			
			$this.focus(function(){
				toggleLabel($this, 'remove');
			});			
		});
		
		forms
			.find('select')
			.each(function(){
				var $this = $(this);
				var first = $this.children().eq(0);
				
				if (first.text() == '') {
					first.html($this.attr('title'));
				}
				else {
					$this.prepend('<option>'+$this.attr('title')+'</option>');
				}
				
				if ($this.children().eq(0).is(':selected')) {
					$this.addClass('default');
				}
				$this.blur(function(){
					$this.addClass('default');
				});
				
				$this.focus(function(){
					$this.removeClass('default');
				});	
			});
}


function toggleLabel(obj, type){
	var input = $(obj);
	var value = input.val();
	var label = input.attr('title');

	if (type == 'remove' && value == label) {
		input.val('');
	}	
	if (type == 'add' && jQuery.trim(value) == '') {
		input.val(label);
	}	
	
	if (input.val() == label) {
		input.addClass('default');
	}
	else {
		input.removeClass('default');
	}
}

function initNewsletterForms() {
	
	var hash = window.location.hash;
	
	var singin_box  = $('#_newsletter-signin fieldset:first').parentsUntil('.mo_white_box').parent();
	var singout_box = $('#_newsletter-signout fieldset:first').parentsUntil('.mo_white_box').parent();
	
	
	if (hash == '#_newsletter-signout') {
		singin_box.hide();
	}
	else {
		singout_box.hide();
	}
	
	$('#_newsletter-signout a.nl_signin').click(function(){
		singout_box.hide();
		singin_box.show();
		return false;
	});

	$('#_newsletter-signin a.nl_signout').click(function(){
		singin_box.hide();			
		singout_box.show();
		return false;
	});	
}


function initForms() {
	$('form label.qflabel').hide();
	initFormLabelToDefault();
	initNewsletterForms();	
}

function initRoundedImages(){
	
	var img     = $(".rounded img, .mo_white_box img, .mo_green_box img, #strategic .gal_item a img");
	var count   = 0;
	var docurvy = true;
	
	img.one('load', function() {

		var $this  = $(this);	
		var src    = $this.attr('src');
		var width  = $this.width();
		var height = $this.height();

		if ($this.is('.textblock img')) return true;
		
		var container = $this.parentsUntil('.rounded, .mo_white_box, .mo_green_box, #strategic .gal_item');
		if (container.length < 1) container = $this;
		
		var box 	  = container.parent();
		var next 	  = container.next();
		var prev 	  = container.prev();

		box.css({'background-image':    'url('+src+')',
			     'background-repeat':   'no-repeat',
			     'background-position': 'left top'});
	
		if (container == $this) {
			container.css('opacity','0');
		} else {
			container.hide();
		}
		
		var p_width   = box.width();
		var p_height  = box.height();
			
		if (width >= p_width) {
			if (next.length) {
				box.css('padding-top',height+'px');
			}
			else if (prev.length) {
				box.css('padding-bottom',height+'px');
				box.css('background-position', 'left bottom');						
			}
			else {
				box.css('height',height+'px');	
				box.css('background-position', 'center center');						
			}
		}
		else {
		
			if (next.length) {
				box.css('height',height+'px');	
				box.css('padding-left',width+'px');
			}
			else if (prev.length) {
				box.css('height',height+'px');						
				box.css('padding-right',width+'px');
				box.css('background-position', 'right top');						
			}
		}


	})
	.each(function() {
		if (this.complete || 
		   (($.browser.msie && $.browser.version < 9) || $.browser.opera)) {
		  $(this).load();
		  count++;
        } else if ($.browser.webkit && document.readyState != "complete") {
           count++;
       }
       
        if (count == img.length) {
  		  //setTimeout("equalHeights($('.three_cols'))",200);    

		  if (!hasBorderRadius() && docurvy) {
	  		  	initCorners()
				docurvy = false;
			}
        }
	  
	});
}

function initCorners() {
    var settings = {
      tl: { radius: 9 },
      tr: { radius: 9 },
      bl: { radius: 9 },
      br: { radius: 9 },
      antiAlias: true
    }

    curvyCorners(settings, ".rounded, .mo_white_box, .mo_green_box, #strategic .gal_item");
}

function hasBorderRadius() {
	var d = document.createElement("div").style;	
	if (typeof d.borderRadius !== "undefined") return true;
	if (typeof d.WebkitBorderRadius !== "undefined") return true;
	if (typeof d.MozBorderRadius !== "undefined") return true;
	return false;
};


function readGetVars() {
	var query = window.location.search.substring(1);

	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		var pos = parms[i].indexOf('=');
		if (pos > 0) {
			var key = parms[i].substring(0,pos);
			var val = parms[i].substring(pos+1);
			get_vars[key] = val;
		}
	}
} 
var get_vars = new Array();
readGetVars();
