/**
 * global variables
 * 
 */
	var base_url = location.href.substring(0,location.href.lastIndexOf('/')+1);	
	var menuItems = ['intro', 'features', 'threesixty', 'images', 'video', 'about', 'buy'];
	var startScreen = 0;
	var fadingDuration = 500;
	var mainContainerOffsetLeft = 200;
	var threeSixtyImageWidth = (526/360);
	var threeSixtyContainerOffsetLeft = 378;
	var threeSixtyContainerOffsetLeft = 1760;
	var threeSixtySectorImageHeight = 340;
	var threeSixtyImagesPerSector = 10;
	var threeSixtySectors = 12;
	var threeSixtyDegreesPerFrame = ( 360 / threeSixtySectors ) / threeSixtyImagesPerSector;
	var threeSixtySectorImageTotalHeight = threeSixtyImagesPerSector * threeSixtySectorImageHeight;
	var threeSixtyCurrentSector = 1;
	var threeSixtyRotate = true;
	
	var threeSixtyAutoRotateVal = 0;
	var threeSixtyAutoRotateInterval = 100;
	var threeSixtyAutoRotateDirection = 'right';
	var threeSixtyAutoRotateOn = false;

	var threeSixtyAutoRotator = null; // ref to interval obj
	var lang = 'en';
	var overlayApi = null;
	var debug = false;
	var preload = []; 
	var flashVersion = null;
	var introAnimationDelay = 3500;
	var scroll = null; /* a reference to scrollable api object */
	var intro0, intro1, intro2, intro3;
	var scrollableEnableMousewheel = false;
	var addPNGFix = true;
	var googleTrack = true;
	var showIntroFlash = true;
	var enableLanguages = false;
	
	/* preload gallery images */
	for(i=0; i<8; i++){
		preload.push(base_url + 'content/'+lang+'/images/thumbs/'+i+'-normal.jpg');
		preload.push(base_url + 'content/'+lang+'/images/thumbs/'+i+'-hover.jpg');
		preload.push(base_url + 'content/'+lang+'/images/thumbs/'+i+'-selected.jpg');
		preload.push(base_url + 'content/'+lang+'/images/bg'+i+'.jpg');
	}

	/* preload features images */
	preload.push(base_url + 'content/'+lang+'/features/bg0.jpg');
	preload.push(base_url + 'content/'+lang+'/features/bg1.jpg');
	preload.push(base_url + 'content/'+lang+'/features/bg2.jpg');
    preload.push(base_url + 'images/dot.gif'); 
    preload.push(base_url + 'images/dot-over.gif'); 
	
	/* preload 360 images */
	for(i=1; i<=threeSixtySectors; i++){
	    preload.push(base_url + 'images/360/360_closed_q'+i+'.jpg'); 
	    preload.push(base_url + 'images/360/360_open_q'+i+'.jpg');
	}
    
	/* preload intro animation images */
	for(i=0; i<4; i++){
		preload.push(base_url + 'content/'+lang+'/intro/animation-'+i+'.jpg');
	}

	/* preload menu images */
	for(i=0; i<7; i++){
		preload.push(base_url + 'content/'+lang+'/menu/'+i+'-normal.png');
		preload.push(base_url + 'content/'+lang+'/menu/'+i+'-selected.png');
	}
	
	/* preload buy images*/
	for(i=0; i<12; i++){
		preload.push(base_url + 'content/'+lang+'/buy/hover/'+i+'.jpg');
	}
    
/**
 * execute if dom is ready
 */
	$(document).ready(function(){
		
		/* set some vars */
		mainContainerOffsetLeft = $('#center > div.content').offset().left;
		threeSixtyContainerOffsetLeft = $('div.item.360degree').find('.container.closed').offset().left - threeSixtyContainerOffsetLeft;
		flashVersion = 	deconcept.SWFObjectUtil.getPlayerVersion().major;
		
		/* set language menu */
		$('div.language.buttons a.'+lang).click().addClass('active');

		
		$.preloadImages(preload, false, function(){
			init({start:startScreen});	
			});
		fix();
	});

	

	
/**
 * add behaviours to the site 
 * 
 * @param options
 * @return void
 */
function init(options)
{
	/* Init Scrollables */
	scroll = $("div#scrollable")
	.scrollable({
		size:		1,
		items:		'.items',
		clickable:	false,
		api:		true
	});
	
	scroll.onSeek = function(){
				$('div#menu a').removeClass('active');
				$('div#menu a').eq(this.getPageIndex()).addClass('active');
				if(this.getPageIndex() == 0){
					clearTimeout(intro0);
					clearTimeout(intro1);
					clearTimeout(intro2);
					embedIntro();
				} else {
					killIntro();
				}
				};
	scroll.movePage(options.start);
	
	/* set the menu state manually the first time */
	$('div#menu a').eq(options.start).addClass('active');

	/* activate mousewheel */
	if(scrollableEnableMousewheel){
		$("div#scrollable").mousewheel(); 
	}
	
	/* activate circular */
	$("div#scrollable").circular(); 

	/* load flash and init intro navigation */
	if(options.start == 0){
		embedIntro();
	}
	$('div.item.intro div.menu a').each(function(index){
		$(this).click( function(e){ 
			setPageByName($(this).attr('class')); 
			});
	});
	
	/* init subnavigation (dots) */
	$('div.subnavi a').each(function(index){
		$(this).click(function(){
			$('div.subnavi a').removeClass('active');
			$(this).addClass('active');
			var container = $(this).closest('.item');
			var current = container.css('background-image');
			var newimg = current.replace(/bg[0-9]\.jpg/, 'bg'+index+'.jpg');
			var fader = container.find('.fader');
			fader.css('background-image', newimg);
			fader.fadeIn('slow', function(){
				$('div.subnavi a').closest('.item').css('background-image', newimg); 
				$(this).css('display', 'none'); }
			);
		});
	});
	
	/* init subnavigation for images section*/
	$('div.item.images .links a').each(function(index){
		
		$(this).click(function(){
			
			/* set navigation */
			$('div.item.images .links a').each( function(index){
				$(this).removeClass('active');
			});
			$(this).addClass('active');
			
			/* set big img */
			var big0 = $('div.item.images .image').eq(0);
			var big1 = $('div.item.images .image').eq(1);

			var current = big0.css('background-image');
			var newimg = current.replace(/bg[0-9]*\.jpg/, 'bg'+index+'.jpg');
			big1.css('background-image', newimg).css('display','none').css('z-index', 1);
			big1.fadeIn(fadingDuration, function(){
				$('div.item.images .image').eq(0)
				.css('background-image', $(this).css('background-image'));
				$(this).css('z-index', 0).css('display', 'none');
				});
			 
			
			
		});
	});
	
	/* mark first thumb as selected */
	$('div.item.images .links a').eq(0).click();

	/* video links */
	$('div.item.video a.link1').mouseover(function(e){$(this).css('background-image', 'url('+base_url+'content/'+lang+'/'+'video/hover/1.png)');});
	$('div.item.video a.link2').mouseover(function(e){$(this).css('background-image', 'url('+base_url+'content/'+lang+'/'+'video/hover/2.png)');});
	$('div.item.video a.link1').mouseout(function(e){$(this).css('background-image', 'none');});
	$('div.item.video a.link2').mouseout(function(e){$(this).css('background-image', 'none');});
	
	/* toggle 360 link */
	$('div.item.360degree a').click(function(e){
		var container1 = $('div.item.360degree');
		var container2 = container1.find('.container').eq(0);
		var bg1 = container1.css('background-image');
		var bg2 = container2.css('background-image');
		
		if(bg1.match(/closed/)){
			container1.css('background-image', bg1.replace('closed', 'open'));
			container2.css('background-image', bg2.replace('closed', 'open'));
		} else {
			container1.css('background-image', bg1.replace('open', 'closed'));
			container2.css('background-image', bg2.replace('open', 'closed'));
		}

	});
	

	if(!isMobileDevice()){
		$('div.item.360degree').find('.container').mousemove(function(e){
			if(!threeSixtyAutoRotateOn){
				var params = {};
				params.pageX = e.pageX;
				params.obj = $(this);
				rotate(params);
			}
		});
	} else {
		
	}

	
	$('div.item.360degree .turn.left').eq(0).click(function(e){
		threeSixtyAutoRotateDirection = 'left';
	});
	$('div.item.360degree .turn.right').eq(0).click(function(e){
		threeSixtyAutoRotateDirection = 'right';
	});

	$('div.item.360degree .turn').click(function(e){
		if(!threeSixtyAutoRotateOn){
			threeSixtyAutoRotateOn = true;
			window.clearInterval(threeSixtyAutoRotator);
			threeSixtyAutoRotator = setInterval(autorotate, threeSixtyAutoRotateInterval); 
		} else {
			threeSixtyAutoRotateOn = false;
			window.clearInterval(threeSixtyAutoRotator);
		}
	}).css('cursor', 'pointer');
	
	
		/* Init scrollable navigation */
		var navi = $("div#scrollable").navigator({
			navi:		'#menu',
			naviItem:	'a',
			activeClass:	'current',
			api:		true
		});
		
		$('div#menu a').each(function(index){
			$(this).click(function(){
				track($(this).attr('rel')); 
				navi.seekTo(index+1);
			});
		});

	}





/**
 * fix some 
 * 
 * @return void
 */
	function fix()
	{
		/* fix link blur border */
		$('a').mousedown(function(e){if(this.blur)this.blur();});
		$('a').click(function(e){if(this.blur)this.blur();});
		
		/* remove 360 sectors */
		if(!debug)$('div.sectors').remove();
		
		/* show left/right buttons for iphone */
//		if(isMobileDevice()){
//			$('div.threesixty .turn').show();
//		}
		
		/* fix buy links */
		if($.browser.msie){
			
			// add png support for IE
			if(addPNGFix){
				$('div#menu').supersleight();
			}

			// hide sectors
			$('div.sectors').remove();
			
			if(parseInt($.browser.version) == 6){
				$('div.item.buy div.buttons.left').eq(0).css({'left':'52px'});
				$('div.social.buttons').eq(0).css('right', '200px');
			}
		}
	}

/**
 * init overlay(s) for video display
 * 
 */
	$(function() { 
		 
	    // if the function argument is given to overlay, 
	    // it is assumed to be the onBeforeLoad event listener 
	    overlayApi = $("a[rel=#overlay]").overlay({ 
	 
	        expose: 		'black', 
	        api:			true,
	        closeOnEsc:		true,
	        close:			null,
	    	onClose: 		function(){ $("#overlay .contentWrap").html(''); },
	    	onLoad:	function(){
	    		// fix iphone
	    		if(isMobileDevice()){
	    			$('#overlay').next().width($(document).width());
	    			$('#overlay').next().height($(document).height());
	    		}
	 
	    	},
	        onBeforeLoad: function() { 
	    		
	    		$('#overlay').show();
	    		
	            // grab wrapper element inside content 
	            var wrap = this.getContent().find(".contentWrap"); 
	            
	            // load the page specified in the trigger 
	            // wrap.load(this.getTrigger().attr("href")); 
	            wrap.html(video4All(this.getTrigger().attr("href").replace('#', '')));
	            
	            // activate video close button if video already started playing
	            $('#v_i_d_e_o')[0].addEventListener('play', function(){
	            	$('#overlay div.header img.close').css('visibility', 'visible');
	            	}, true);
	            
	            if(addPNGFix){
	            	wrap.supersleight({shim: base_url + 'js/x.gif'});
	            }


	        } 
	 
	    }); 
	});

	function video4All(which)
	{
		var player = base_url + 'video/player.swf';
		var path = base_url + 'video/'+which  ;
		var html = '';
			html += '<div class="header">';
			html += '<img src="'+base_url+'video/'+which+'-header.png" class="headline"/>';
			html += '<img src="'+base_url+'video/close.png" class="close" ';
			html += '	onClick="javascript:$(\'#overlay\').hide().next().hide(); $(\'#overlay .contentWrap\').html(\'\')"';
			html +=	' 	style="cursor: pointer; visibility:hidden"/>';
			html += '</div>';
			html += '<video width="640" height="360" poster="'+path+'.jpg" controls autoplay id="v_i_d_e_o">';
			html += '<source src="'+path+'.mp4" type="video/mp4"></source>';
			html += '<source src="'+path+'.ogv" type="video/ogg"></source>';
			html += '<object width="640" height="384" type="application/x-shockwave-flash" ';
			html += 'data="' + player + '?autostart=true&amp;image=' + path + '.jpg&amp;file=' + path + '.flv">';
			html += '<param name="movie" value="'+player+'?autostart=true&amp;image='+path+'.jpg&amp;file='+path+'.flv" />';
			html += '<img src="'+path+'.jpg" width="640" height="360" alt=""';
			html += 'title="No video playback capabilities, please download the video below" />';
			html += '</object>';
			html += '</video>';
		return html;
	}	
/**
 * preloadImages function
 * 
 * @return void
 */
	(function($) {
		  var cache = [];
		  // Arguments are image paths relative to the current page.
		  $.preloadImages = function(images, showLoading, callback) {
		    var args_len = images.length;
		    for (var i = args_len; i--;) {
		    	
			  // show loading bar while loading images
		      if(showLoading){
		    	  $('#loading').show();
		      }
		      
		      var cacheImage = document.createElement('img');
		      cacheImage.src = images[i];
		      if(debug)console.log("add "+images[i]+" to cache.");
		      cache.push(cacheImage);
		    }
		    
		    setTimeout("$('#loading').hide();", 1000);
		    setTimeout(callback, 1000);
		    
		  }
		})(jQuery);
	
	
	
	
/** 
 * helper for 360 view 
 * 
 * @return void
 */
	function reset360()
	{
		var container = $('div.item.360degree').find('.container.closed');
		var newimg = container.css('background-image').replace(/q(.*)\.jpg/, 'q1.jpg');
		if(debug)console.log(newimg);
		container.css('background-image', newimg);
		container.css('background-position', '0px 0px');
	};

/** 
 * embed the intro swf
 * 
 * @return void
 */
	function embedIntro()
	{	
		if(flashVersion >= 8 && showIntroFlash){
			var html = '';
			html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%">';
			html += '<param name="movie" value="content/en/intro/loader.swf?moviePath=content/en/intro/20100422_temp01.swf" />';
			html += '<param name="loop" value="false" />';
			html += '<param name="bgcolor" value="000000" />';
			html += '<!--[if !IE]>-->';
			html += '<object type="application/x-shockwave-flash" data="content/en/intro/loader.swf?moviePath=content/en/intro/20100422_temp01.swf" width="100%" height="100%">';
			html += '<param name="loop" value="false" />';
			html += '<!--<![endif]-->';
			html += '<!-- alternate content --> ';
			html += '<!--[if !IE]>-->';
			html += '</object>';
			html += '<!--<![endif]-->';
			html += '</object>';
			$('div#flashintro').html(html).show();
		} else {
			killIntro();
			startIntroAnimation();
		}
	}

/**
 * init the animation within the intro page
 * 
 * @return void
 */
	function startIntroAnimation()
	{
		var images = [];
		for(i=0; i<5; i++){
			images.push(base_url + 'content/'+lang+'/intro/animation-'+i+'.jpg');
		}
	
		$.preloadImages(images, false, function(){
			if(debug){
				console.log('loaded images for intro animation');
			}
			
			
		/* init with img 0 and clear timeouts */
		var img = base_url + 'content/'+lang+'/intro/animation-0.jpg';
		$('div#animation_fader').css('background-image', 'url('+img+')');
		$('div#animation').css('background-image', 'url('+img+')');
		$('div#animation div.menu').css('display', 'none');
	
		/* now start the animation */
		var time = 0;
		var img = images[1];
		var delay = introAnimationDelay; 
		
		intro0 = setTimeout("animateIntro('"+img+"');", delay);
		img = images[2];
		delay += introAnimationDelay;
		intro1 = setTimeout("animateIntro('"+img+"');", delay);
		img = images[3];
		delay += introAnimationDelay;
		intro2 = setTimeout("animateIntro('"+img+"');", delay);
		img = images[4];
		delay += introAnimationDelay;
		intro3 = setTimeout("animateIntro('"+img+"');$('#animation .menu').eq(0).fadeIn('slow');", delay);
		});
	}

/**
 * helper function for intro container slideshow
 * 
 * @param img path to new image
 * @return void
 */
	function animateIntro(img)
	{
		// set the background image to newimg, then fade in
		var fader = $('div#animation_fader');
		fader.css('background-image', 'url('+img+')');
		fader.fadeIn('slow', function(){ 
				$('div#animation').eq(0).css('background-image', 'url('+img+')'); 
				$(this).css('display', 'none'); 
			});
	}


/**
 * this function is called from within flash
 * when flashintro movie has reached last frame
 * 
 * @return void
 */
	function introFinished()
	{
	  $('div#animation').css('background-image', 'url('+base_url + 'content/'+lang+'/intro/animation-4.jpg'+')');
	  $('div#animation div.menu').show();
	  killIntro();
	}
	
/**
 * removes intro video 
 * 
 * @return
 */
	function killIntro()
	{
		  return $('div#flashintro').hide().html('');
	}

/**
 * helper function to get the page index by name 
 * 
 * @return int
 */
	function getPageIndexByName(name)
	{
		var items = menuItems;
		for(i=0; i<items.length; i++){
			if(items[i] == name){
				return i;
			}
		}
	};

/**
 * helper function to get the page index by name 
 * 
 * @return int
 */
	function getPageNameByIndex(index)
	{
		return menuItems[index];
	};

/**
 * scroll scrollable to a given page 
 * 
 * @param string name
 * @return void
 */
	function setPageByName(name)
	{
		scroll.move(getPageIndexByName(name));
	}
	
	
/**
 * google trackinh
 * 
 * @param section the site section
 * @return void
 */
	function track(section)
	{
		/* google track */
		//pageTracker._trackPageview(section);
	}

	
	
/**
 * add event listeners for mobile devices
 * 
 */
	function initTouch(id){

		var threesixty = document.getElementById(id);

		threesixty.ontouchstart=function(e){
			
		    e.preventDefault();
		    
		    if(e.touches.length==1){
		        
		        var touch=e.touches[0];
		        var boxLeftToTouchLeft = touch.pageX-threesixty.offsetLeft;
		        //$('#debug').html('boxLeftToTouchLeft: '+boxLeftToTouchLeft+'<br>');
		        
		        threesixty.ontouchmove=function(e){
		            
		            e.preventDefault();
		            
		            if(e.touches.length==1){
		                
		                var touch=e.touches[0];
		                var node=touch.target;
		                var touchToLeft=touch.pageX-boxLeftToTouchLeft;
		                var width = $(node).css('width').replace('px', '');
		                var scrollOffset = window.pageXOffset;
		                	scrollOffset = document.body.scrollLeft;
		                var touchX = touch.pageX + scrollOffset;
		                var offsetLeft = $(node).offset().left;
		                var perc = Math.round( (touchX-offsetLeft) / width *100)
		                var degrees = Math.abs(Math.round(perc*3.6)) % 360;
		                degrees = degrees== 0 ? 1 : degrees;

//		                $('#threesixty').html(
//		                        'element width: ' + width + 
//		                        '<br>percent: ' + perc + ' % '+ 
//		                        '<br>scroll offset: ' + scrollOffset + 
//		                        '<br>degrees: ' + degrees + ' ° '+ 
//		                        '<br>touch.pageX: '+touch.pageX + 
//		                        '<br>touchX: '+	touchX + 
//		                        '<br>offset left: '+offsetLeft + 
//		                        '<br>boxLeftToTouchLeft: '+boxLeftToTouchLeft
//		                        ).css('border', '1px solid red');
		                
		        		if(!threeSixtyAutoRotateOn){
		        			var params = {};
		        			params.deg = degrees;
		        			params.obj = $(threesixty);
		        			rotate(params);
		        		}
		                
		                }
		            }
		        }
		    this.ontouchend=function(){
		        boxLeftToTouchLeft=boxTopToTouchTop=null;
		        }
		    }
	}
	$(document).ready(function(){
		if(isMobileDevice()){
			initTouch('threesixty');
		}
	});
	
/**
 * Returns true if user has iphone or ipod
 * 
 * @return
 */	
	function isMobileDevice()
	{
		var result = navigator.userAgent.match(/iPhone/i) 
					 || 
					 navigator.userAgent.match(/iPod/i)
					 ||
					 navigator.userAgent.match(/android/i);
		 
		return result;
	}

	
/**
 * rotate 
 * 
 * @param params
 * @return
 */
	function rotate(params)
	{
		if(params.obj.css('display') != 'none' && threeSixtyRotate){
			
			var container = params.obj;
			
			if(!params.deg){
				var deg = Math.floor((params.pageX - threeSixtyContainerOffsetLeft) / threeSixtyImageWidth );
			} else {
				var deg = params.deg;
			}
			
			if(deg<=0 || deg>=360){
				reset360();
				return;
			}
			
			var sector = Math.floor(deg/ (360/threeSixtySectors) )+1;
			
			/* only calculate image if sector has changed */
			if(sector != threeSixtyCurrentSector){
				threeSixtyCurrentSector = sector;
				var bgimg = container.css('background-image').replace(/q([0-9]){1,2}\.jpg/, 'q'+sector+'.jpg');
				container.css('background-image', bgimg);
			}
			
			var position = ( Math.floor( deg / threeSixtyDegreesPerFrame )* threeSixtySectorImageHeight ) % threeSixtySectorImageTotalHeight;
			
			if(debug){
				var debugOutput = 
					'degree. ' + deg + '<br>x-position: ' + position+ 
					'<br>sector: ' + sector + '<br>bg-image: ' + bgimg + 
					'<br>frame: ' + Math.floor( deg / threeSixtyDegreesPerFrame ) +
					'<br>1 frame = ' + threeSixtyDegreesPerFrame + ' degrees	';
				console.log(deg + ' : ' + position+ ' : ' + sector + ' : ' + bgimg);
				$('div.threesixty .debug').eq(0).html(debugOutput);
			}
			
			container.css('background-position', '0px -' + position+'px');
		  }
		
	}

	
/**
 * autorotate 
 * 
 * @return
 */	
	function autorotate()
	{
		
		if(threeSixtyAutoRotateDirection == 'left'){
			threeSixtyAutoRotateVal -- ;
		} else {
			threeSixtyAutoRotateVal ++ ;
		}
		var deg = Math.abs(threeSixtyAutoRotateVal % 360);
		deg = (deg==0) ? 1 : deg;
		rotate({
			obj:$('div.item.360degree .container.closed').eq(0),
			deg: deg
		});
	}
	
	
/**
 * Switch language
 */
	var switchLanguageCacheKey = lang;
	function loadLanguage(newLang)
	{
		var switchLanguageCacheKey = newLang;
		var cssImages = getCssImages();
		var inlineImages = getInlineImages();
		var images = $.merge(cssImages, inlineImages);
		
		var newImages = [];
		var newImage;
		$(images).each(function(){
			newImage = this.replace('/'+lang+'/', '/'+newLang+'/') + '?' + switchLanguageCacheKey;
			newImages.push(newImage);
		});
		
		if(debug){
			console.log('preloading ' + newImages.length + ' images..');
		}
			
		$.preloadImages(newImages, true, function(){ setLanguage(newLang); } );
		
	}
	
	function setLanguage(newLang)
	{
		/* change all style images to new language */
		var newImg;
		$(getCssImageRules()).each(function(index){
			if(this.style.backgroundImage.length>0){
				newImg = replaceLanguageUrl(this.style.backgroundImage, newLang);
				this.style.backgroundImage = newImg;
				if(debug){
					console.log('set background: ' + newImg);
				}
			}
			if(this.style.background){
				this.style.background = replaceLanguageUrl(this.style.background, newLang);
				if(debug){
					console.log('set background: ' + this.style.background);
				}
			}
		});
		
		/* change all inline images */
		var imageElements = getInlineImageElements();
		$(imageElements).each(function(){
		    var oldImg = $(this).css('background-image');
		    if(oldImg.length>0 && oldImg.indexOf('/'+lang+'/') != -1){
		        var newImg = replaceLanguageUrl(oldImg, newLang);
		        $(this).css('background-image', newImg);
				if(debug){
					console.log('set inline background: ' + $(this).css('background-image'));
				}

		    }

		});
		
		lang = newLang;
		
		if(debug){
			console.log('switch language to "'+newLang+'"');
		}
	
	}
	
	if(enableLanguages){
		$(document).ready(function(){
			$('div.language.buttons a').each(function(index){
				$(this).click(function(e){
					loadLanguage($(this).attr('rel'));
					$('div.language.buttons a').removeClass('active');
					$(this).addClass('active');
				});
			});
		});
	}	
	
/**
 * Get css styles of the document
 * 
 * @return
 */	
	function getCssRules()
	{
		if($.browser.msie){
			return document.styleSheets[0].imports[0].rules;
		}
		
		var rules = [];
		if (document.styleSheets[0].cssRules){
			rules = document.styleSheets[0].cssRules;
		}
		else if (document.styleSheets[0].rules){
			rules = document.styleSheets[0].rules;
		}
		return rules[0].styleSheet.cssRules;
	}
	
/**
 * filter out rules, that have image definitions
 * 
 * @return
 */	
	
	var cssImgRules = [];
	function getCssImageRules()
	{
		
		if(cssImgRules.length>0){
			return cssImgRules;
		}
		
		$(getCssRules()).each(function(index){
		    if(typeof this.style == 'object'){
		    	
		    	if(this.style.backgroundImage || this.style.background){
		    		if(this.style.cssText.match('/content/')){
		    		cssImgRules.push(this);
		    		}
		    	}
		    }
		});
		return cssImgRules;		
	}
	
/**
 * get all images which are set in the style sheet
 * 
 * @return
 */	
	function getCssImages()
	{
		var images = [];
		var img;
		var rules = getCssImageRules();
		$(rules).each(function(){
	    	if(this.style.backgroundImage){
	    		img = this.style.backgroundImage;
	    	}
	    	else if(this.style.background){
	    		img = this.style.background;
	    	}
	    	
	    	if(img.match(/\/content\//)){
	    		img = img.replace(/(url\("{0,1})/, '').replace(/("{0,1}\))/, '');
	    		images.push(img);
	    	}
		});
		return images;
		
	}
	
/**
 * Get all elements which has inline images defined
 * 
 * @return
 */	
	function getInlineImageElements()
	{
		var elements = [];
		
		$('body a, body div').each(function(index){
			
			/* only inline styles */
			style = $(this).attr('style');
			
			if(style && style.match(/[background|url]/)){
				if(style.match('/content/')){
					elements.push(this);
				}
			}
			
		});
		
		return elements;

	}
	
/**
 * Get the urls of background images, which are set as inline style
 * 
 * @return
 */	
	function getInlineImages()
	{
		var images = [];
		var img, style;
		$(getInlineImageElements()).each(function(index){
			
			    if($(this).css('background-image')){
			    	img = $(this).css('background-image');
			    }
			    
			    if($(this).css('background')){
			    	img = $(this).css('background');
			    }
		    	if(img && img.match(/\/content\//)){
		    		img = img.replace(/(url\("{0,1})/, '').replace(/("{0,1}\))/, '');
		    		images.push(img);
		    	}
		});
		
		return images;

	}
	
	function replaceLanguageUrl(str,newLang)
	{
		var regex = /url\("{0,1}(.*)(\?[a-z]{2}){0,1}"{0,1}\)/;
		var matches = regex.exec(str);
		var url = matches[1].replace('"','');
//		var url = str.replace('/'+lang+'/', '/'+newLang+'/').replace('url(', '').replace(')', '');
		var newUrl = url.replace('/'+lang+'/', '/'+newLang+'/') + '?' + switchLanguageCacheKey;
		return str.replace(url, newUrl);
	}
//$(document).ready(function(){
//
//	$('body').append('<div id="debug">debug:</div>');
//
//	if(typeof console == 'undefined'){
//		var console = {};
//		
//		if(!$('div#debug')){
//			$('body').append('<div id="debug">debug:</div>');
//		}
//		
//		console.log = function(msg){
//			$('div#debug').append(msg);
//		}
//	}	
//});
	
