// JavaScript Document
var flashBreite;
var flashHoehe;
var rand;
var flashSkinHeight;
var flashSkinURL;
var flashPlayerURL;
var flashContainerID;
var flashJQueryDialogID;


function scrollPopUpWindow(popUpID , xPos , yPos , initial){
	if(popUpID == 0 || popUpID == undefined){
		return;
	}
	if(xPos == 0 || xPos == undefined || typeof(xPos) == 'string'){
		xPos = 20;
	}
	if(yPos == 0 || yPos == undefined){
		yPos = 20;
	}
	if(initial){
		animateJQueryDialog(popUpID,xPos,yPos);
	}
	$(window).bind('scroll.jQDialog resize.jQDialog', function(e) {
		animateJQueryDialog(popUpID,xPos,yPos);
	})
}
function animateJQueryDialog(dialog , xPos , yPos) {
	var $dialog = $(dialog).dialog('widget');
	var xPosA = getDialogLeftPosition(dialog,xPos);
	var yPosA = getDialogTopPosition(dialog,yPos);
	$dialog.stop(true,false).animate({
		top: yPosA,
		left: xPosA
	},{
		duration: 500
	});
}
function getDialogLeftPosition(dialog,xPos){
	var $dialog = $(dialog).dialog('widget');
	var leftPos;
	if(xPos == xPos){
		leftPos = parseInt(($(window).width() - $dialog.outerWidth('true'))/2);
		if(leftPos <= 0){
			leftPos = xPos;
		}
	}
	return(leftPos);
}
function getDialogTopPosition(dialog,yPos){
	var $dialog = $(dialog).dialog('widget');
	var topPos;
	if($(document).height() - $dialog.outerHeight('true') - yPos > $(window).scrollTop()){
		topPos = yPos + $(window).scrollTop();
	}	 else {
		topPos = $(document).height() - $dialog.outerHeight('true') - yPos;
	}
	debug('getDialogTopPosition: documentHeight=' + $(document).height() + ' / dialogOuterHeight=' + $dialog.outerHeight('true') + ' / scrollTop=' + $(window).scrollTop() + ' / topPos' + topPos);
	return(topPos);
}

function resizePopUpWindow(popUpID, prozentFromViewport){	
	$(window).bind('resize', function() {
		var viewPortW = $(window).width();
		var viewPortH = $(window).height();
		$(popUpID).dialog( "option", "width", Math.floor(viewPortW * prozentFromViewport ));
		$(popUpID).dialog( "option", "height", Math.floor(viewPortH * prozentFromViewport ));
		xPos = Math.floor(viewPortW * (1 - prozentFromViewport)) / 2;
		yPos = Math.floor(viewPortH * (1 - prozentFromViewport)) / 2;
		$(popUpID).dialog( "option", "position", 'center' );
	});
}

function openJQueryDialog(popUpID, titleName, popUpBreite, popUpHoehe, xPos, yPos, prozentFromViewport, iFrameURL, sitestatCode, resizeAble){
	
	var standardjQWidth = 'auto';
	var standardjQHeight = 'auto';
	var standardxPos = 'center';
	var standardyPos = 10;
	
	if(popUpID == undefined || titleName == undefined){return;}
	if(popUpID.indexOf('#')!= 0){
		popUpID = "#" + popUpID;
	}
	if(popUpBreite == 0 || popUpBreite == undefined){jQWidth = standardjQWidth;} else {jQWidth = popUpBreite;}
	if(popUpHoehe == 0 || popUpHoehe == undefined){jQHeight = standardjQHeight;} else {jQHeight = popUpHoehe;}
	if(xPos == 0 || xPos == undefined){jQxPos = standardxPos;} else {jQxPos = xPos;}
	if(yPos == 0 || yPos == undefined){jQyPos = standardyPos;} else {jQyPos = yPos;}
	if(prozentFromViewport < 1 || prozentFromViewport > 0){
		jQWidth = Math.floor($(window).width() * prozentFromViewport);
		jQHeight = Math.floor($(window).height() * prozentFromViewport);
		resizePopUpWindow(popUpID, prozentFromViewport);
	}
//	if(resizeable == 0 || resizeable == undefined){
	resizeAble = (resizeAble == 0 || resizeAble == undefined) ? true : false;
	
	var $popUpID = $(popUpID);
	var $popUpHTML = $(popUpID).clone();
	var $parent4PopUpID = $popUpID.parent();
	
	$(popUpID).dialog('destroy');
	$popUpID.dialog({
		autoOpen:false,
		modal:true,
		width:jQWidth,
		height:jQHeight,
		position:[jQxPos,jQyPos],
		resizable:false,
		title:titleName,
		closeOnEscape:true,
		close: function(event, ui){
			$(this).remove();
//			$popUpID.dialog('destroy');
			$(window).unbind('scroll.jQDialog resize.jQDialog');
			$popUpHTML.appendTo($parent4PopUpID);
		}
	});
	
	if(iFrameURL != 0 && iFrameURL != undefined){
		$popUpID.dialog({
			open: function(event, ui) {
				$(popUpID).append($("<iframe />").attr("height", "100%").attr("width", "100%").attr("src", iFrameURL));
			},
			beforeClose: function(event, ui) {
				$(popUpID).html('');
			}
		});
		
//		$popUpID.dialog({
//			
//		});
//		$popUpID.bind( 'dialogopen' , function(event, ui) {
//				$popUpID.append($("<iframe />").attr("height", "100%").attr("width", "100%").attr("src", iFrameURL));
//			}
//		);
//		$popUpID.bind( 'dialogbeforeclose' , function(event, ui) {
//				$popUpID.html('');
//				$popUpID.unbind();
//			}
//		);
	}
	
	if(sitestatCode != "" && sitestatCode != null){
		submitSiteStatCode(sitestatCode);
	}
	
	$popUpID.dialog('open');
	scrollPopUpWindow(popUpID, jQxPos, jQyPos);
}

function setSkinHeight(flashSkURL){
	if (flashSkURL == 'SkinUnderAllNoCaption.swf'){
		var flashSH = 37;
	}
	return(flashSH);
}

function openFlashVideo(buttonID, videoURL, siteStatCode, backgroundImageURL, flashBreite, flashHoehe, flashRand, flashSkinURL, flashSkinHoehe, flashPlayerURL, flashContainerID, flashJQueryDialogID, alternativerNoFlashText){
	
	// Standard Flash Video Preset
	var standardFlashBreite = 800;
	var standardFlashHoehe = 450;
	var standardRand = 40;
	var standardFlashSkinHeight = 37;
	var standardFlashSkinURL = 'SkinUnderAllNoCaption.swf';
	var standardFlashPlayerURL = '/static/bilder/main_page/produktvideos/player/player.swf';
	var standardFlashContainerID = 'flashContainer';
	var standardFlashJQueryDialogID = '#produktExtrasPopUp';
	var standardZugabeJQueryDialog = 28;
	var flashB,flashH,rand,flashSkURL,flashSkinHeight,flashPlURL,flashCoID,flashJQDID;
	
	if(buttonID == undefined || videoURL == undefined || siteStatCode == undefined){return;}
	
	$(flashJQDID).css('display','none');
	
	$('#' + buttonID).click(function(event) {
		event.preventDefault();
		
		if(flashBreite == 0 || flashBreite == undefined){flashB = standardFlashBreite;}else {flashB = flashBreite;}
		if(flashHoehe == 0 || flashHoehe == undefined){flashH = standardFlashHoehe;}else {flashH = flashHoehe;}
		if(flashRand == 0 || flashRand == undefined){rand = standardRand;}else {rand = flashRand;}
		if(flashSkinURL == 0 || flashSkinURL == undefined){flashSkURL = standardFlashSkinURL;}else {flashSkURL = flashSkinURL;}
		if(flashSkinHoehe == 0 || flashSkinHoehe == undefined){flashSkinHeight = setSkinHeight(flashSkURL);}else {flashSkinHeight = flashSkinHoehe;}
		if(flashPlayerURL == 0 || flashPlayerURL == undefined){flashPlURL = standardFlashPlayerURL;}else {flashPlURL = flashPlayerURL;}
		if(flashContainerID == 0 || flashContainerID == undefined){flashCoID = standardFlashContainerID;}else {flashCoID = flashContainerID;}
		if(flashJQueryDialogID == 0 || flashJQueryDialogID == undefined){flashJQDID = standardFlashJQueryDialogID;}else {flashJQDID = flashJQueryDialogID;}	
		
		var titleName = $('#' + buttonID + " strong").text();
		$(buttonID + "> p").attr('title', titleName);
		
		if(alternativerNoFlashText == 0 || alternativerNoFlashText == undefined){alternativerNoFlashText = titleName;}
		
		$(flashJQDID).dialog('destroy');
		if($('#' + flashCoID).html() == null){
			$(flashJQDID).append($("<div />").attr("id", flashCoID));
		}
		
		var flashvars = {};
		flashvars.videoURL = videoURL;
		flashvars.videoX = flashB;
		flashvars.videoY = flashH;
		flashvars.videoSkinURL = flashSkURL;
		flashvars.videoRand = rand;
		var params = {};
		params.scale = "noscale";
		params.allowScriptAccess = "sameDomain";
		params.wmode = "transparent";
		params.base = ".";
		swfobject.embedSWF(flashPlURL, flashCoID, flashB + rand, flashH + rand + flashSkinHeight, "10.0.0.0","/static/Scripts/expressInstall.swf", flashvars, params);
		
		if(backgroundImageURL != undefined || backgroundImageURL != 0){
			$('#' + flashCoID).css({
				'background-image' : 'url(' + backgroundImageURL + ')',
				'background-position' : rand / 2 + "px " + rand / 2 + "px",
				'background-repeat' : 'no-repeat'
			});
		}
		//'<a href="' + href + '" target="_blank">' + alternativerNoFlashText + '</a>'
		var href = $('#' + buttonID + " a").attr('href');
		if(href != undefined){
			
			$('div#' + flashCoID + ':empty').css({'width' : flashB + rand, 'padding-top' : flashH + rand/2, 'padding-bottom' : rand/2})
																			.append('<object data=\"' + href + '\" type=\"audio/x-wav\" height=\"45\" width=\"' + flashB + '\" style=\"display:block;\"><param name=\"src\" value=\"' + href + '\" /><param name=\"autostart\" value=\"true\" /><param name=\"autoplay\" value=\"true\" /><param name=\"bgcolor\" value=\"#FFDC00\" /><p>This content requires the Adobe Flash Player and a browser with JavaScript enabled. <a href=\"http://www.adobe.com/go/getflash/\" target=\"_blank\" title=\"Get Flash\">Get Flash</a></p><p>or <a href=\"' + href + '\" title=\"Download the File\" target=\"_blank\">Download the File</a></p></object>')
		}
		
		openJQueryDialog(flashJQDID, titleName, flashB + rand + standardZugabeJQueryDialog);
		submitSiteStatCode(siteStatCode);
		
//		if (typeof ns_onclick == 'function') {
//			ns_onclick($(this),'',siteStatCode,'clickin');
//			return false;
//		}
	});
}

function setYouTubeVideo(videoContainerID, youTubeVideoURL, youTubeVideoWidth, youTubeVideoHeight, playerPreset){
	var ytCol1; var	ytCol2; var ytBorder; var ytFS; var ytAP; var ytSS; var ytRel; var ytHD; var paramFS; var ytVURL
	
	// YouTube Player HABA Standard
	standardYTCol1 = "F9B200";
	standardYTCol2 = "F9B200";
	standardYTBorder = 0;
	standardYTFullscreen = 0;
	standardYTAutoplay = 0;
	standardYTshowsearch = 0;
	standardYTRel = 0;
	standardYTHD = 0;
	standardASVersion = 3;
	standardParamFullscreen = "false";	
	
	if(videoContainerID == undefined || youTubeVideoURL == undefined || youTubeVideoWidth == undefined || youTubeVideoHeight == undefined){return;}
	
	if(playerPreset == 0 || playerPreset == undefined){
		ytCol1 = standardYTCol1;
		ytCol2 = standardYTCol2;
		ytBorder = standardYTBorder;
		ytFS = standardYTFullscreen;
		ytAP = standardYTAutoplay;
		ytSS = standardYTshowsearch;
		ytRel = standardYTRel;
		ytHD = standardYTHD;
		ytASV = standardASVersion;
		paramFS = standardParamFullscreen;	
	}
	
	if(youTubeVideoURL.indexOf("http://") > -1){
		ytVURL = youTubeVideoURL;
	} else {
		ytVURL = "http://www.youtube-nocookie.com/v/" + youTubeVideoURL;
	}
	
	var flashvars = {};
		flashvars.color1 = ytCol1;
		flashvars.color2 = ytCol2;
		flashvars.border = ytBorder;
		flashvars.fs = ytFS;
		flashvars.autoplay = ytAP;
		flashvars.showsearch = ytSS;
		flashvars.rel = ytRel;
		flashvars.hd = ytHD;
		flashvars.version = ytASV;
	var params = {};
		params.allowScriptAccess = "sameDomain";
		params.wmode = "transparent";
		params.allowFullScreen = paramFS;
		
	swfobject.embedSWF(ytVURL, videoContainerID, youTubeVideoWidth, youTubeVideoHeight, "10.0.0.0","/static/Scripts/expressInstall.swf", flashvars, params);
}

function submitSiteStatCode(siteStatCode){
	if (typeof ns_onclick == 'function') {
		ns_onclick(this,'',siteStatCode,'clickin');
		return false;
	}
}

function collectLinks(sitestatCode) {	
	var linkArray = new Array();
	
	$('A[name][title][href]').each(function(key, a){
		var linkObject = $(a);
		linkArray[key] = new Object();
		linkArray[key]['ArtNr'] = linkObject.attr('name');
		linkArray[key]['Title'] = linkObject.attr('title');
		linkArray[key]['URL'] = linkObject.attr('href').replace(/&/g,'HABAAND');
		
		$(a).click(function(event) {
			submitSiteStatCode(sitestatCode + '.static_' + linkArray[key]['ArtNr']);
		});
	});
	
	var sJson = $.toJSON(linkArray); 
	sJson = sJson.replace(/\"/g, "%22");
	return sJson;
}

function registerClick4Sitestat(object,code) {
	var isNotURL = /^(\\.|#)/;
	var jQSelector = object;
	if(!isNotURL.test(object)) {
		jQSelector = 'a[href*=\"' + object + '\"]';
	}
	$(function(){
		$(jQSelector).click(function(e){submitSiteStatCode(code)});
	})
}

function allLinks4Sitestat(sitestatCode,boxWithLinks) {
	if (boxWithLinks == undefined) {
		boxWithLinks = '';
	} else {
		boxWithLinks = boxWithLinks + ' ';
	}
	var jQSelector = boxWithLinks + 'a[href]';
	var jQNotSelector = boxWithLinks + 'a[href^="#"]';
	$(jQSelector).not(jQNotSelector).click(function(e){
		var linkObject = $(this);
		var linkCode = 'haba';
		var linkObjectHref = linkObject.attr('href');
		var regExp = /(P_(?:[ST]?\d{6}$)|(?:AK_\d+$))/
		if(regExp.exec(linkObjectHref) != null) {
			linkCode = RegExp.$1.replace(/P_/ , '');
		} else if(linkObject.attr('name') != '' && linkObject.attr('name') != undefined) {				
			linkCode = linkObject.attr('name');
		} else if(linkObjectHref != '' && linkObjectHref != undefined && linkObjectHref.indexOf('videos/') >= 0) {
			var lastSlash = linkObjectHref.lastIndexOf('/')+1;
			//Testing e.preventDefault();
			//console.log(linkObjectHref + '_' + lastSlash + '_' + linkObjectHref.length + '_' + linkObjectHref.substring(lastSlash));
			linkCode = linkObjectHref.substring(lastSlash);
		}
		console.log(sitestatCode + '.' + linkCode);
		submitSiteStatCode(sitestatCode + '.' + linkCode);
	});
}

function debug(log_txt,optText) {
    if (window.console != undefined) {
			if(optText == undefined) optText='';
      console.log(optText + ' ' + log_txt);
    }
}

function getIMGWidth(imgSRC){
	var width = 0;		
	var $img = $('<img>')
		.load(function(e) {
			var $tempDiv = $('<div id="tempDIV4jQueryPictureSize">').css({'position':'absolute', 'left':'-30000px'}).append($(this));
			$('body').append($tempDiv);
			width = this.offsetWidth;
			$('#tempDIV4jQueryPictureSize').remove();
	
			return(width);   
    })
		.attr('src',imgSRC);

//	try{
//		var $tempDiv = $('<div>').css({'position':'absolute', 'left':'-30000px', 'width':'1px', 'overflow':'hidden'}).append(img);
//		$('body').append($tempDiv);
//		width = $tempDiv.children('img').width();
//		$tempDiv.remove();
//	} catch (error) {
//		width = 0;
//	}
//	if(width == 0){
//		getIMGWidth(img)
//	} else {
//		return(width);
//	}
}
function getDialogWidthValue(dialogID){	
	var $dialogF = $(dialogID).dialog('widget');
	var $dialogContent = $dialogF.children('.ui-dialog-content');
	var cssParameter = new Array('padding-left','padding-right','margin-left','margin-right','border-left-width','border-right-width');
	var jQueryContainer = new Array($dialogContent);
	var width = 0;
	for(var i=0; i < jQueryContainer.length; i++) {
		for(var e=0; e < cssParameter.length; e++){
			width = width + parseInt(jQueryContainer[i].css(cssParameter[e]))
		};
	}
	return(width);
}
function getStandardDialogContentOuterBoxValues(){
	$('body').append('<div id="StandardDialogContentOuterBoxValues">');
	var $contentBox = $('#StandardDialogContentOuterBoxValues');
	$contentBox.dialog({ autoOpen: false });
	var cssParameter = new Array('padding','border','margin');
	var dialogValues = new Array();
	var width = 0;
	for(var e=0; e < cssParameter.length; e++){
		var css = cssParameter[e];
		debug(css + ':' + $contentBox.css(css + '-top'));
		dialogValues[css] = new Array();
		if(css != 'border'){
			dialogValues[css][0] = $contentBox.css(css + '-top');
			dialogValues[css][1] = $contentBox.css(css + '-right');
			dialogValues[css][2] = $contentBox.css(css + '-bottom');
			dialogValues[css][3] = $contentBox.css(css + '-bottom');
		} else {
			dialogValues[css][0] = $contentBox.css(css + '-top-width');
			dialogValues[css][1] = $contentBox.css(css + '-right-width');
			dialogValues[css][2] = $contentBox.css(css + '-bottom-width');
			dialogValues[css][3] = $contentBox.css(css + '-bottom-width');
		}
		//width = width + parseInt(jQueryContainer[i].css(cssParameter[e]))
	};
	$contentBox.dialog('destroy');
	$contentBox.remove();
	debug(dialogValues['border'][0]);
	//return(width);
}

(function($){
	//cache needed for overagressive garbage collectors.
	var cache = [];
	//images can either be an array of paths to images or a  single image. 
	$.preloadImages = function(images, callback , serverPath){    
		//convert to array if needed so rest of script works
		if (!(images instanceof Array)) {
				images = [images];
		}
		// convert lokalPath to Root Relative Path
		var regEx = /^\/static.*\/$/;
		if(serverPath == undefined || serverPath == 0 || serverPath.match(regEx)){
			for (var i=0 ; i < images.length ; i++){
				images[i]  = serverPath + images[i];
				debug(images[i],'Server Path:');
			}
		}
		
		var imagesLength = images.length;
		var loadedCounter = 0;
		
		for (var i = imagesLength; i--;) {
			var cacheImage = document.createElement('img');
			//set the onload method before the src is called otherwise will fail to be called in IE
			cacheImage.onload = function(){
					debug('onLoad');
					loadedCounter++;
					if (loadedCounter >= imagesLength) {
							if ($.isFunction(callback)) {
									callback();
							}
							debug('IMG loaded!');
					}
			}
			cacheImage.src = images[i];
			cache.push(cacheImage);
		}
  }
})(jQuery);

function getIDasString(format) {
	var $wrapper = $('.jsGetID');
	var srcID = $wrapper.attr('id');
	var idString = '#' + srcID;
	var yearString = srcID.substring(srcID.indexOf('_')+1);
	var langString = $wrapper.attr('lang');
	switch (format) {
		case 'id':
			return(idString);
		case 'year':
			return(yearString);
		case 'lang':
			return(langString);
	}
	return('');
}
function getUserLang() {
	return($('div.habaBG2').attr('lang'));
}

(function( $ ) {
	
	var $preloadWrapper;
	var $this;
			
	var methods = {
		init : function( options ) { 

			// Create some defaults, extending them with any options that were provided
			// size: String Values: small,middle,big
			// show: Boolean
			var settings = $.extend( {
				'size' : 'small',
				'position' : 'center',
				'show' : true
			}, options);
			
			return this.each(function() { 
			
				$this = $(this);
				
				$preloadWrapper = $('<div class="preloadAnimationWrapper center">').addClass(settings.size).append('<div>');	
				
				if(typeof settings.show  == 'boolean' && settings.show) {
					methods.show();
				};

    	});
			 
		},
		show : function( ) {
			$this.css('position','relative');
			$this.prepend($preloadWrapper);
		},
		hide : function( ) { 
			$preloadWrapper.remove();
		},
		update : function( content ) { 
			// !!! 
		}
	};
	
	$.fn.preloadAnimation = function( method ) {	
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.preloadAnimation' );
		}
	};
})(jQuery);

function setCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function deleteCookie(name) {
    setCookie(name,"",-1);
}

//	$('a.textLinkMitBild').append($('<span>').addClass('after').text('<strong>Hallo Alex</strong>'));
