// Copyright 2011 Ph. Schellworth
// all rights reserved
// www.schellworth.de
// v3.0.6


var hash = window.location.hash;
var path = window.location.pathname;

// work scrollShrink
var mainContainer = 'div.bottombar';
var shrinkElement = '.workright'; // element that will be animated
var hiddenHeight = 150; // the min-height the content should be visible
var scrollToLinks = '.scrollTo a';

$(document).ready(function(){


//search menu customs
	$("#cntnt01moduleform_1 input:submit").hide();
	$("#cntnt01searchinput").css({
		'width' : '0px',
		'border' : '1px solid transparent',
		'cursor' : 'pointer',
		'backgroundColor' : 'transparent',
		'width' : '1px',
	});
	$("#cntnt01searchinput").click(function () {
		$(this).css({
			'border' : '1px solid #7E7E7E',
			'cursor' : 'text',
		}).animate({
			'width' : '150px',
		},400, 'swing');
		$("#cntnt01searchinput").css({
     		'backgroundColor' : 'white',
     	}); 
	});

// News 		 
	// initialize scrollable  jQueryTools
	$("div.scrollable").scrollable({ 
		size: 1,
		speed: 500,
		vertical: true,
		//circular: true,
	}).navigator({
		indexed: true,
	}).autoscroll({
		interval: 9000,
		autoplay: true,
		autopause: true,
	});     
		 
// news rein- rausfahren
	$("#news").hide();		
	$("#newsbutton").click(function() {					
		// um den hintergrund beim zu- aufklappen mit zu animieren, position bestimmen
		var current_pos = $("#background-layer2").css("backgroundPosition");
 		if (current_pos) { var arr_current_pos = current_pos.split(" "); }
		
		if ( $("#news").is(":hidden") ) {
			$("#news").animate({
				height: "show"
			}, 800, 'easeOutBounce');
			var pos_x = parseFloat(arr_current_pos[1]);
 			pos_x= (pos_x + 150);
 			$("#background-layer1").animate({backgroundPosition: '('+arr_current_pos[0]+' '+pos_x+')'}, 800, 'easeOutBounce');
			$("#background-layer2").animate({backgroundPosition: '('+arr_current_pos[0]+' '+pos_x+')'}, 800, 'easeOutBounce');
			$("div.scrollable").scrollable().play();
		} else {
			$("div.scrollable").scrollable().stop();
			$("#news").animate({ 
				height: "hide" 
			}, 500);
			var pos_x = parseFloat(arr_current_pos[1]);
 			pos_x= (pos_x - 150);
			$("#background-layer1").animate({backgroundPosition: '('+arr_current_pos[0]+' '+pos_x+')'}, 500, 'swing');
			$("#background-layer2").animate({backgroundPosition: '('+arr_current_pos[0]+' '+pos_x+')'}, 500, 'swing');
		}
	});

	$("#newsbutton").mouseover(function() {
		if ( $("#news").is(":hidden") ) {
			$("#header").animate({
				marginTop: "0px"
			},300, 'easeInOutBounce', function(){
				$("#header").animate({
					marginTop: "-4px"
				},300, 'swing');
			});
		}
	});


	
	
// hintergrund auf die richtige position fahren	
// bei neuen menüeinträgen hinzufügen, sonst ist news offen.
	
	if ( $("#Dienstleistungen").hasClass("active" ) ) {
		$("#background-layer1").animate({backgroundPosition: '(4px -71px)'}, 500, 'swing');
		$("#background-layer2").animate({backgroundPosition: '(0px -75px)'}, 500, 'swing');
	} else if ( $("#Werke").hasClass("active" ) ) {
		$("#background-layer1").animate({backgroundPosition: '(-61px -167px)'}, 500, 'swing');
		$("#background-layer2").animate({backgroundPosition: '(-60px -161px)'}, 500, 'swing');
	} else if ( $("#Profil").hasClass("active" ) ) {
		$("#background-layer1").animate({backgroundPosition: '(213px -431px)'}, 500, 'swing');
		$("#background-layer2").animate({backgroundPosition: '(210px -430px)'}, 500, 'swing');
	} else if ( $("#Kontakt").hasClass("active" ) ) {
		$("#background-layer1").animate({backgroundPosition: '(-89px -338px)'}, 500, 'swing');
		$("#background-layer2").animate({backgroundPosition: '(-90px -337px)'}, 500, 'swing');
	} else if ( path=='/' ) { //home
		$("#background-layer1").animate({backgroundPosition: '(0px -57px)'}, 500, 'swing');
		$("#background-layer2").animate({backgroundPosition: '(0px -55px)'}, 500, 'swing');
	}else {
		$("#background-layer1").animate({backgroundPosition: '(0px -33px)'}, 500, 'swing');
		$("#background-layer2").animate({backgroundPosition: '(0px -30px)'}, 500, 'swing');
	};


// links manipulation
	//var external_re = new RegExp( "^http?:\/\/(?!" + location.hostname + ").*$" );
	$("a:focus").css({'-moz-outline-style': 'none'});
	var external_re = new RegExp( "^http?:\/\/(?!www.schellworth.de).*$" );
	
	$('a').each(function(){
		// Open external links in a new window/tab
		if (external_re.test(this.href)) {
			if (!this.target) this.target = '_blank';
		}
		// link hover morph	
		var oldColor = jQuery(this).css("color");
		$(this).hover( function() {
			$(this)
			  	.css('color',oldColor)
			  	.animate({'color': 'black'}, 400, 'swing');
		  	},
		  	function() {
				$(this)
			  		.animate({'color': oldColor}, 400, 'swing');
			}
		);
		// Smooth scroll
		$(this).click(function() {
			var top_re = new RegExp("\/#top$");
			if (top_re.test(this.href)) {
				var Offset = $("#top").offset().top;
				$('html,body').animate( { scrollTop: '' + Offset + 'px' }, 2000, 'easeOutExpo');
				//return false;
			}	
		});	
	});

// init fancxbox
	$("a[rel]").live("mouseover", function() {
				$("a[rel]").fancybox({
					padding: 0,
					titleShow: false,
					overlayOpacity: 0.7,
					overlayColor: 'black',
				});
	});


	$(window).load(function(){
		$("#main").css({
			backgroundColor: 'transparent',
		},1000);
		aniLinks(".homeLinks a");	
	});

// Home
if (path=='/') {
	
	$("#news").animate({ height: "show"	}, 500, 'swing');
	new FlickrStream({containerId : 'homeFlickr', statusId : 'homeFlickrStatus', perPage : '35',}).fetch(function() { this.start(); });

	// SkillCloud
	// Thanks Shawn for the great 3D engine 
	// http://www.devirtuoso.com/2009/09/making-a-3d-engine-in-jquery/
	$("#cloudItems").addClass("cloudItems");
	$("#cloudBack").addClass("cloudBack");
	$("#cloudItems").click(function() { window.location = "/services/" });
	var Cube = function (size){
	
	if (size === undefined){
		size = 10;
	}
	
	this.pointsArray = [
		this.make3DPoint(-size,-size,-size),
		this.make3DPoint(size,-size,-size),
		this.make3DPoint(size,-size,size),
		this.make3DPoint(-size,-size,size),
		this.make3DPoint(-size,size,-size),
		this.make3DPoint(size,size,-size),
		this.make3DPoint(size,size,size),
		this.make3DPoint(-size,size,size),
		this.make3DPoint(0,size,-size),
		this.make3DPoint(size,size,0),
		this.make3DPoint(0,size,size),
		this.make3DPoint(-size,size,0),
		this.make3DPoint(0,-size,-size),
		this.make3DPoint(size,-size,0),
		this.make3DPoint(0,-size,size),
		this.make3DPoint(-size,-size,0),
		this.make3DPoint(-size,0,-size),
		this.make3DPoint(size,0,-size),
		this.make3DPoint(size,0,size),
		this.make3DPoint(-size,0,size)
	];
	
	};

	Cube.prototype = new DisplayObject3D();
	
	
	var camera = new Camera3D();
	camera.init(0,0,0,800);
	
	var item = new Object3D($("#cloudItems"));
	
	item.addChild(new Cube(70));
	
	var scene = new Scene3D();
	scene.addToScene(item);
	
	var animateIt = function(){
		axisRotation.y += .01
		axisRotation.x -= .01
		scene.renderCamera(camera);
	};
	
	
	setInterval(animateIt, 20);
			
			

//END HOME
}




// dienstleistung
if (path=='/services/') {

	var anchorMenu = '.anchormenu a';
	var anchorContent = 'div.anchor';
	
	// reset
	$("div.anchor").hide();
	$(".workleft").hide();

	//wenn anchor über uri aufgerufen wird oder page reloaded wird, content anzeigen.
	if ( $(anchorContent).is(":hidden") && hash ) {
		var getIndex = $(anchorMenu).index($("a[href*='" + hash +"']"));
		showContent(getIndex);		
	};

		
	// alle a hrefs von id (#???) sammeln und index erstellen.

	$(anchorMenu).each(
		function( initIndex ) {
			$(this).bind(
				"click",
				// bei jedem click eines a hrefs den entsprechenden index der class (.???) zeigen
				function(){
					if ( $(this).is('.jAactive') ) { 
						return false;
					}
					// reset
					$(anchorContent).animate({
							height: "hide"
					}, 200, 'swing');
					$(anchorMenu).removeClass("jAactive");				
					// show
	     			showContent(initIndex);
				}
			);
		}
	);
}
		
	function showContent(index) {		//shows the selected content
		var Offset = Math.round($('#top').offset().top);
		// wenn noch nicht auf die navigations position gescrollt dann scrollen und einblenden
		$('html,body').animate( { scrollTop: '' + Offset + 'px' }, 500, 'swing', function() {
			var contentIndex = index;
			$(anchorContent + ":eq(" + contentIndex + ")").animate({
				height: "show",
			}, 500, 'swing');
			// highlight the active element 
			$(anchorMenu + ":eq(" + index + ")").addClass("jAactive");
		});
	}
	
//END SERVICES




// work
if (path=='/work/') {

	new FlickrStream({containerId : 'workFlickr', perPage : '53', getNext : '100', fadeDuration : '100',}).fetch(function() { this.start(); });
	
	// loader animation
	$("#middle").after('<div id="loader">loading...</div>');  
	var id =  setInterval(function() {
		$("#loader").append(".");
		$(window).load( function() {
			$("#loader").fadeOut(200, 'swing');
			clearInterval(id);
		});
 	}, 500)
 	 
	// scrollShrink	
	$(window).load(function(){ // webkit, chrom workaround
		initScrollShrink();
	});
	
//END WORK
}



// profil	
if (path=='/about/') {
			
	$(".full").hide();
	$("div.short").before("<div class='left workleft small version toggle'>full version</div>");
	$("div.short").before("<div class='small more'>click to expand</div>");
	
	$(".toggle").click(function(e) {
		// check if an A HREF is clicked inside the div
		if ( e.target.nodeName=='A' ) {
			window.location = e.target.href;
		} else {
			if ( $("div.full").is(":hidden") ) {
				showContentToggle(".short", "2");
				$(".version").html("full version");
				$(".more").html("click to contract");
				history.pushState('', '', '/about/#full');
			} else {
				showContentToggle(".full", "1");
				$(".version").html("short version");
				$(".more").html("click to expand");
				history.pushState('', '', '/about/#short');
			}
		}
		return false;
	});
	
	//wenn anchor über uri aufgerufen wird oder page reloaded wird, content anzeigen.
	if ( path=="/about/" && hash ) {
		(hash=='#full') ? showContentToggle(".short", "2") : showContentToggle(".full", "1");
	};
	
	$("div.more").hide();
	$(".toggle").hover(function() {
		$("div.more").slideDown(300, 'swing');
		}, function(){
			$("div.more").slideUp(300, 'linear');
		});

}

	function showContentToggle(hide, contentIndex) {
			$(hide).animate({
				height: "hide"
			},500, 'swing', function(){
				$("div.paragraph:eq(" + contentIndex + ")").animate({
					height: "show"
				},500, 'swing');			
			});
	}

//END ABOUT



// Contact
if (path=='/contact/') {
	
	$("#kontakt div.card").css({
		'-moz-transform': 'rotate(-2deg)', 
		'-webkit-transform': 'rotate(-2deg)', 
		'-o-transform': 'rotate(-2deg)',
		'-ms-transform': 'rotate(-2deg)',
	});
	$("div.formular").css({
		'-webkit-transform': 'rotate(1deg)',
		'-moz-transform': 'rotate(1deg)',
		'-o-transform': 'rotate(1deg)',
		'-ms-transform': 'rotate(1deg)',	 
	});
	
	$("#bot").hide();
	$("#botInput").click(function() {
		$(this).val('');
		$("#bot").animate({
			height: "show"
		},500, 'swing');	
	});
	
	$(".icons img").each(function() {
		var self=this;
		$(this).mouseover(function() {
			$(this).animate({
				marginTop: '-10px',
			}, 200, 'swing');
		});
		$(this).mouseout(function() {
			$(this).animate({
				marginTop: '0px',
			}, 200, 'swing');
		});
	});

//END CONTACT
}
	


/*function Overlay() {
	$("body").append('<div id="overlay"><div class="contentWrap"></div></div>');
	
	$("#homeFlickr").on("mouseover", "a", function(e) {
		$(this).overlay({
			mask: 'black',
			left: 'center',
			fixed: false,
			target: '#overlay',
		 
		 	onBeforeLoad: function() {
				// grab wrapper element inside content
				var wrap = this.getOverlay().find(".contentWrap");
				wrap.load(this.getTrigger().attr("href"));
			}	
		});
	});
	//return false;
}*/

// End document.ready
});
 
 


function aniLinks(elements) {
	$(elements).each(function(i) {
		var self=this;
		window.setTimeout(function() {
			var oldColor = jQuery(self).css("color");

			$(self).css('color',oldColor).animate({'color': 'black'}, 200, 'swing', function() {
				$(self).animate({'color': oldColor}, 200, 'swing');
			});
		},300*i);
	});
}

// based on http://www.mudaimemo.com/demo/flickr_photo_stream/
function FlickrStream (opts) {
	// start using 
	// new FlickrStream({perPage : '2', containerId = 'flickr_container'}).fetch(function() { this.start(); });
	// @see http://www.flickr.com/services/api/
	opts = opts || {};
	
	this.apiKey = opts.apiKey || 'ede9b5ca8fd00386a7a9dcc73835ca58';
	this.userId = opts.userId || '65906283@N03';
	this.extras = opts.extras || 'date_upload, date_taken, owner_name, icon_server, original_format, last_update, geo, tags, machine_tags, o_dims, views, media, path_alias, url_sq, url_t, url_s, url_m, url_z, url_l, url_o';
	this.page = opts.page || 1;
	this.perPage = opts.perPage || 100;
	this.containerId = opts.containerId || 'flickr_container';
	this.statusId = opts.statusId || 'flickr_status';
	this.getNext = opts.getNext || 100 //interval between next show();
	this.fadeDuration = opts.fadeDuration || 100;
	this.easing = opts.easing || 'swing';
	
	this.queue = [];
	this.pages = '';
	this.params = '';
		
	if (typeof opts.method == 'undefined') {
		opts.method = 'flickr.people.getPublicPhotos';
	}
	
	this.params = $.extend(opts, {
		api_key: this.apiKey,
		user_id: this.userId,
		format: 'json',
		per_page: this.perPage,
		extras: this.extras,
	});
}
FlickrStream.prototype = {
	// per JSON fotos von flicker holen
	fetch: function (callback) {
		var self = this;
		this.url = 'http://api.flickr.com/services/rest/?' + $.param(this.params) + '&page=' + this.page +'&jsoncallback=?';
		
		$('#' + this.statusId).remove();
		$('#' + this.containerId).append('<span id="' + this.statusId + '" class="small">loading...</span>');
		currentPage = this.page
		$.getJSON(this.url, function (obj) {
			if (!obj.photos || !obj.photos.photo) return false;
			pages = obj.photos.pages;
			if (currentPage > obj.photos.pages) return false;
			$(obj.photos.photo).each(function (i, p) {
				self.queue.push(p);
			});
			if ($.isFunction(callback))
				callback.apply(self, arguments);
		});
		this.page++;
		return this;
	},
	
	// queue letztes element anzeigen und aus queue entfernen
	show: function () {
		var
			self = this,
			p = this.queue.shift(),
			currentDisplayed = this.queue.length;
			
			//link = 'http://www.flickr.com/photos/' + p.owner + '/' + p.id + '/',
			photo = 'http://farm' + p.farm + '.static.flickr.com/' + p.server + '/' + p.id + '_' + p.secret + '_s.jpg',
			html = '<a href="' + p.url_l + '" rel="#overlay" title="' + p.title + '" class="photo" style="display:none;">' + '<img src="' + photo + '" title="' + p.title + '" /></a>';

		$('#' + this.containerId).append(html).find('img:last').load(function () {
			//console.log(currentDisplayed);
			$('#' + self.statusId).remove();
			$(this).closest('a').fadeIn(this.fadeDuration, this.easing, function () {
				if ( !currentDisplayed && currentPage < pages ) {
					$('#' + self.containerId).append('<span id="' + self.statusId + '" class="small">more images...</span>');
					$('#' + self.statusId).click(function() {
							// erst mit fetch holen, wenn true, dann mit start anzeigen - wenn mehrere seiten vorhanden.
							self.fetch(function() { 
								self.start();
							});
					});
				}
			});
		});
		if ( this.queue.length < 1 ) {  // alle angezeigt, queue leeren und stop.
			this.queue = [];
			this.stop();
		}
		return this;
	},


	start: function () {
		var self = this;
		this.intervalId = setInterval(function () { self.show(); }, this.getNext); //einzelne bilder anzeigen verzögern
		return this;
	},

	stop: function () {
		var self = this;
		clearInterval(this.intervalId); //stop start:interval
		return this;
	}
};

function initScrollShrink() {
	// original größe jedes grids berechnen und speichern
	$(mainContainer).each(
		function( initIndex ) {
			var shrink = $(this).find(shrinkElement);	// element to animate
			$(this).data("pHeight", shrink.outerHeight());  // preserve the original height
			var preservedHeight = $(this).data("pHeight");
			
			// set all shrinkElements to the hiddenHeight
			shrink.css({
				'height' : hiddenHeight	// hide all
			});
		}
	);
	// to get calculated data for each element i.e. after a reload
	resizeScroll(shrinkElement, hiddenHeight);
	
	// init anchor menu
	$(scrollToLinks).each(
		function( initIndex ) {
			$self=$(this);
			$(this).bind(
				"click",
				// bei jedem click eines a hrefs den entsprechenden index der class (.???) zeigen
				function(){								
					// scroll to
					scrollToContent(initIndex, $(this).attr('href'));
					//disable the href
					return false;
				}
			);
		}
	);
	
	// page loaded from external link
	if ( path=="/work/" && hash ) {
		var getIndex = $(scrollToLinks).index($("a[href*='" + hash +"']"));
		scrollToContent(getIndex);		
	};
	
	// if you scroll
	$(window).scroll(function() {			
		resizeScroll(shrinkElement, hiddenHeight);	
	});	
}


function scrollToContent(index, setHash) {  //recursive function
	var contentIndex = index;

	// reset highlight
	$(scrollToLinks).removeClass("jAactive");
	
	if (!setHash) setHash = path+hash;
	if (index>=0) {
		var currentScrollTop = $(this).scrollTop();
//console.log(currentScrollTop + " " + parseInt($("div.shrink:eq(" + contentIndex + ")").children(".workright").offset().top));
		var stopOffset = parseInt($(mainContainer+":eq(" + contentIndex + ")").offset().top-currentScrollTop-20);
		var speed = Math.round(Math.abs(stopOffset)/20)

		if (speed <= 1) speed = 1;
//console.log(currentScrollTop + " " + stopOffset + "speed: " + speed);
		if (stopOffset > 0 ) {  
			window.scrollBy(0, +speed);
			setTimeout( "scrollToContent("+index+", '"+setHash+"')", 0);
		} else if (stopOffset == -speed) { // webkit workaround
			$(scrollToLinks+":eq("+index+")").addClass("jAactive"); //highlight
			history.pushState('', '', setHash);
		} 
		else if (stopOffset < 0) {
			window.scrollBy(0, -speed);
			setTimeout( "scrollToContent("+index+", '"+setHash+"')", 0);
		} else {
			$(scrollToLinks+":eq("+index+")").addClass("jAactive"); //highlight
			history.pushState('', '', setHash);
		}
	}
}

function resizeScroll(shrinkElement, hiddenHeight) {
	var currentScrollTop = $(this).scrollTop();
	$(".shrink").each(
			function( initIndex ) {
				var elementOffset = parseInt($(this).children(shrinkElement).offset().top);
				var preservedHeight = $(this).data("pHeight");
				var startRise = parseInt(elementOffset-$(window).height()+hiddenHeight+20);
				var startShrink = parseInt($(this).children(shrinkElement).offset().top-currentScrollTop-20);

				$(this).data("startRise", startRise);
				$(this).data("elementOffset", elementOffset);
				$(this).data("startShrink", startShrink);

				//debug
				//$(this).data("currentScrollTop", currentScrollTop);
				//$(this).data("windowHeight", $(window).height());


				
				//console.log(currentScrollTop + " " + $(this).data("startRise"));
				if (currentScrollTop > $(this).data("startRise"))  { 
					//console.log("rise" + $(this).data("startRise")); 
					var riseHeightCurrent = currentScrollTop-$(this).data("startRise")+hiddenHeight; //preserve it, cause if it's hidden .hight() doesn't work
					$(this).children(shrinkElement).css({
							'height' : $(this).data("pHeight") >= riseHeightCurrent ? riseHeightCurrent : $(this).data("pHeight"),
					});
				}
				if ($(this).data("startShrink") < 0) {
					//console.log("shrink" + $(this).data("startShrink"));
					var shrinkHeightCurrent = parseInt($(this).data("elementOffset")-currentScrollTop+$(this).data("pHeight")-20);
					$(this).children(shrinkElement).css({
							'height' : shrinkHeightCurrent >= hiddenHeight ? shrinkHeightCurrent : hiddenHeight,
					});
				}
			}
	);
}



	
	


