var natureOffice = {
	$s: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
	pagelime: (window.location.href.indexOf("cms.pagelime.com")>-1) || (window.location.href.indexOf("cms.natureoffice.com")>-1),
	elems: { active: '', visible: [ '#feature_link1' ], invisible: [ '#feature_link2', '#feature_link3' ] },
	interval: 0,
	counter: 0,
	start: window.location.pathname=="/de/",
//##########################################
	prep: function(input) {
   		var output = "";
	   	var chr1, chr2, chr3;
	   	var enc1, enc2, enc3, enc4;
	   	var i = 0;
	   	do {
	    	chr1 = input.charCodeAt(i++);
	      	chr2 = input.charCodeAt(i++);
	      	chr3 = input.charCodeAt(i++);
	      	enc1 = chr1 >> 2;
	      	enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
	      	enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
	      	enc4 = chr3 & 63;
	      	if (isNaN(chr2)) {
	      	   enc3 = enc4 = 64;
	      	} else if (isNaN(chr3)) {
	      	   enc4 = 64;
	      	}
	      	output = output + natureOffice.$s.charAt(enc1) + natureOffice.$s.charAt(enc2) + natureOffice.$s.charAt(enc3) + natureOffice.$s.charAt(enc4);
	   	} while (i < input.length);
	   	output = output.replace(/=/g, '');
	   	return output;
	},
	format: function(nStr){
		var d = {'de':'.','deu':'.','us':',','la':'.'};
		var _delim = d[natureOffice.location()];
  		
  		nStr += '';
  		x = nStr.split(_delim);
  		x1 = x[0];
  		x2 = x.length > 1 ? _delim + x[1] : '';
  		var rgx = /(\d+)(\d{3})/;
  		while (rgx.test(x1)) {
  			x1 = x1.replace(rgx, '$1' + _delim + '$2');
  		}
  		return x1 + x2;
	},
	location: function(){
		var l = ''
		if(window.location.pathname.split('/')[1].length==2){
			l = window.location.pathname.split('/')[1];
		}else{
			l = window.location.hostname.split('.')[0];
		}
		l=="deu"?l="de":'';
		
		return l;
	},
	browserUpdate: function(){
		var $buoop = {vs:{i:6}, newwindow: true } 
		var e = document.createElement("script"); 
			e.setAttribute("type", "text/javascript"); 
		 	e.setAttribute("src", "http://browser-update.org/update.js"); 
		 	document.body.appendChild(e);
	},		
	gat: function(){
		var o = {'de':'UA-17706177-1','deu':'UA-17706177-1','us':'UA-17705890-1','la':'UA-18157543-1'};
		var _gaq = _gaq || [ ['_setAccount', o[natureOffice.location()]], ['_trackPageview']];
	
	    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	},
	navigator: function(){
		var loc = '';
		var c = natureOffice.location();
		if ( document.location.host.split('.')[0].length == 2 ){
			loc = window.location.pathname.split('/')[1];
		}else{
			loc = window.location.pathname.split('/')[2];	
		}
		$(".navigation a:not([href^=/"+c+"/"+loc+"])").addClass( 'blind' );
		$(".navigation a[href$="+window.location.pathname+"]").addClass( 'current' );
		$(".navigation .level0").removeClass( 'blind' );
	},
	//########
	teaserFade: function(){
		natureOffice.elems.active = natureOffice.elems.visible.shift();
		$( natureOffice.elems.active ).fadeToggle('slow', 'linear', function(c){
			var d = natureOffice.elems.invisible.shift();
			$( d ).fadeToggle('slow	', 'linear');
			natureOffice.elems.invisible.push( natureOffice.elems.active );
			natureOffice.elems.visible.push(d);
		});
	},
	loadCounter: function(){
		$.getJSON('/inc/couchdb/count.php', function(data) {
			var c = Math.round(data['rows'][0]['value']['sum']/1000);
  			$('#natureoffice_counter').text( natureOffice.format(c) );
		});
	},
	//########
	setupAnim: function(delay){
		natureOffice.delay = delay;
		if( $('#feature_visual').length > 0 ){
			$('#feature_visual a').bind('mouseover', function(){
				window.clearInterval(natureOffice.interval);
			});
			$('#feature_visual a').bind('mouseout', function(){
				natureOffice.interval = window.setInterval('natureOffice.teaserFade()',natureOffice.delay);
			});
			natureOffice.interval = window.setInterval('natureOffice.teaserFade()',natureOffice.delay);
		}
	},
	setupCounter: function(){
		natureOffice.loadCounter();
	},
	//
	specials: function(){
		natureOffice.checkDortmund();
	},
	checkDortmund: function(){
		if(parent.frames.length>0){
			// add Dortmund Home Link...
			$('.navigation a[href="/de/loesungen/klimaneutrales-drucken/index.php"]').after(
				'<a href="/de/loesungen/klimaneutrales-drucken/dortmund/" class="level3">Klimaneutral in Dortmund</a>'
			);
		}
	},
	heightHack: function(){
		if($('.content').height()<$('.navigation').height()){
			$('.content').css('height', $('.navigation').height());
		}else{
			$('.navigation').css('height', $('.content').height());
		}
	}
};
//##########################################
//##########################################

jQuery(document).ready(function($){
   	natureOffice.pagelime = (window.location.href.indexOf("cms.pagelime.com")>-1) || (window.location.href.indexOf("cms.natureoffice.com")>-1);
   	natureOffice.navigator();
   	natureOffice.browserUpdate();
   	natureOffice.specials();
   	//natureOffice.gat();
	if( window.isCmsPageEditorPreview ){
		$('<link type="text/css" rel="stylesheet" media="all" href="http://www.natureoffice.com/css/cms.css" />').appendTo('head');
		console.log('CMS');
		//$('#feature_visual').css('height', 'auto');
		//$('#feature_visual a').show();
		natureOffice.tumblr('de');
	}else{
		natureOffice.setupAnim(5000);
		natureOffice.setupCounter();
		if(natureOffice.start){
			natureOffice.tumblr();
			VideoJS.setupAllWhenReady();
		}
	}
	//
   	//$("#natureoffice_tracker").mask("aa-999-999999",{placeholder:" ", completed:function(){  } });
	//
	$('#natureoffice_search').click( function(){
		var loc = natureOffice.location();
		var posy = screen.height/2-400/2;
		var posx = screen.width/2-600/2;
		var hash = natureOffice.prep( $("#natureoffice_tracker").val().toUpperCase() );
		var tracker = window.open('http://api.natureoffice.com/lookup/'+loc+'.php?hash='+hash,'tracker','scrollbars=no,width=600,height=400, screenX=0,screenY=0,top='+posy+',left='+posx);
		if( tracker == null || typeof(tracker)=='undefined' ){
			$.fancybox(
				'<iframe src="http://api.natureoffice.com/lookup/'+loc+'.php?hash='+hash+'" width="600" height="400" style="border:none;">',
				{ width: 600, height: 430, overlayColor: '#000', overlayOpacity: 0.6, hideOnContentClick: false }
			);
		
		}
	});
	//
	$("a.whatsthis").fancybox({ width: 500, height:380, autoDimensions:false, hideOnContentClick: true, overlayColor: '#000', overlayOpacity: 0.6 });
	$("a.iframe").fancybox({ width: 700, height: 430, overlayColor: '#000', overlayOpacity: 0.6, hideOnContentClick: false });
	$("a.inline").fancybox({ overlayColor: '#000', overlayOpacity: 0.6} );
	//
	$("select").uniform();
	$("#chooseyourdestiny").change( function(){
		document.location.href = "http://"+window.location.host+"/"+$(this).val();
	} );
	//
	natureOffice.heightHack();
});

//#########################

natureOffice.tumblr = function(){
	var o = {'de':'natureoffice','deu':'natureoffice','us':'natureofficeusa','la':'natureofficela'};
	var loc = arguments[0] || natureOffice.location();
	var dom = o[loc];
	$.getScript('http://'+dom+'.tumblr.com/api/read/json?type=text&filter=text&num=3', function() {
		$("#tumblr").html('');
		$(tumblr_api_read['posts']).each( function(i,d){
			var teaser = d['regular-body'].split(" ").slice(0, (natureOffice.v4?40:36) ).join(" ")+"… (weiter)";
			var datum = new Date(d['unix-timestamp']*1000).toLocaleDateString();
			$("#tumblr").append('<div class="news"><p class="headline" style="height: 28px;"><a href="'+d['url-with-slug']+'" target="_blank">'+d['regular-title']+'</a></p><p class="date" style="text-align:right;"><a href="'+d['url-with-slug']+'" target="_blank">'+datum+'</a></p><p class="text"><a href="'+d['url-with-slug']+'" target="_blank">'+teaser+'</a></p></div>');
		});
	});
}

