var _isFullGallery = false;


function positionMainNavi() {
	//alert("w/i/o: " + $(window).width() + "/" + $(window).innerWidth() + "/" + $(window).outerWidth());
	$('.submainnav').each(function(idx, elem){
		mnLeft = $(this).parent().offset().left;
		$(this).css('left', (0 - mnLeft) + 'px').css('width', $(window).width() + 'px');
		$(this).find('.overview').css('left', ($('#mainnav').offset().left + 30) + 'px');
	});
}






function slideImage(idx, dir) {
	$('#layer-image div.gallery-item').stop(true, true);
	var cIdx = $('#layer-image div.current').index();
	var nIdx = (idx != null) ? idx : cIdx + dir;
	if ( cIdx != nIdx ) {
		
		// calculate indices and get according jq elements 
		pagerElem = $('.gallery-pager a');
		if (nIdx >= pagerElem.length) nIdx = 0;
		if (nIdx < 0) nIdx = pagerElem.length - 1;
		if (!dir) dir = nIdx - cIdx;
		var spd = 800;
		var easng = "easeInOutQuint"; // -> http://jqueryui.com/demos/effect/easing.html
		nextElem = $('#layer-image div.gallery-item').eq(nIdx);
		curElem = $('#layer-image div.current');
		
		// mark the active pager dot
		$('.gallery-pager a').removeClass('current').eq(nIdx).addClass('current');
		$('.gallery-thumb').removeClass('current').eq(nIdx).addClass('current');

		// slide in next element
		lf = (dir > 0) ? $(window).width() : 0 - nextElem.width();
		moveDist = Math.abs(lf - parseInt(curElem.css('left')));
		nextElem.css('left', lf + 'px').css('z-index', 51).addClass('next').animate({
			left: curElem.css('left')
		}, spd, easng, function(){
			$(this).addClass('current').removeClass('next');
		});

		// slide out current element
		lf = (dir > 0) ? '-=' + moveDist : '+=' + moveDist;
		curElem.css('z-index', 50).animate({
			left: lf
		}, spd, easng, function(){
			$(this).removeClass('current');
		});
		
	} else {
		// nothing happens - alert('this image is already current');
	}
}


/*
 * calculate image scaling dimensions and sides according to available space with fixed height
 */
function setImageFix(regWidth, regHeight, fixHeight) {
	var limitRatio = regWidth / regHeight;
	var contentW = $(window).width();

	h = fixHeight;
	w = h * limitRatio;

	$('#layer-image').css('height', h + 'px');
	$('#gallery-infobox').css('height', h + 'px').css('top', (0 - h) + 'px');

	l = Math.round((contentW - w) / 2);
	$('#layer-image div.gallery-item').css('height', h + 'px').css('width', w + 'px').css('left', l + 'px'); // position the image
	tl = 0;
	if (l < 0) tl = Math.abs(l);
	$('#layer-image div.gallery-item a').css('left', tl + 'px'); // position the text

	positionMainNavi();
}



/*
 * calculate image scaling dimensions and sides according to available space
 */
function setImageAspectRatio(regWidth, regHeight) {
	var limitRatio = regWidth / regHeight;
	var topH = 88;
	var footerH = 32;
	var w, h, l, tl;
	var contentW = $(window).width();
	if (_isFullGallery) {

		//alert("full image mode");
		
		$('#layer-image img').css('width', 'auto');

		var minContentH = 60; // minimum height of visible part of content layer if site is loaded
		var minImgH = 10; // minimum image height
		var availImgH = $(window).height() - topH - minContentH; // remaining height for image
		//alert("standard image scaling - availImgH: " + availImgH);
		if (availImgH > regHeight) availImgH = regHeight;
		if (availImgH < minImgH) availImgH = minImgH;
		
		h = availImgH;
		w = h * limitRatio;
		
		imgW = contentW; // new behaviour
		//imgH = imgW / limitRatio; // new behaviour
		imgH = availImgH - 20;
		cntT = topH + imgH; // new behaviour
		//console.log("cntT: " + cntT + " vs. " + (topH + h)); // new behaviour
		if (cntT < (topH + h)) h = imgH; // new behaviour
		
		$('#layer-bottom').css('top', (topH + h) + 'px');
		$('#layer-image').css('height', h + 'px');
		$('#gallery-infobox').css('height', h + 'px').css('top', (0 - h) + 'px');
		
		var videoTop = Math.round((h-600)/2);
		if(videoTop > 0){
			$('#gallery-video').css('margin-top', videoTop + 'px');
		}
		var videoLeft = Math.round((w-1050)/2);
		if(videoLeft > 0){
			$('#gallery-video').css('margin-left', videoLeft + 'px');
		}
		
		positionFooter();
		
		w = imgW; // new behaviour
		h = imgH; // new behaviour
	} else if (_globalDoctype != 'homepage') { // standard scaling - priority is content visiblility
		var minContentH = 260; // minimum height of visible part of content layer if site is loaded
		var minImgH = 60; // minimum image height
		var availImgH = $(window).height() - topH - minContentH; // remaining height for image
		//alert("standard image scaling - availImgH: " + availImgH);
		if (availImgH > regHeight) availImgH = regHeight;
		if (availImgH < minImgH) availImgH = minImgH;
		
		h = availImgH;
		w = h * limitRatio;
		
		imgW = contentW; // new behaviour
		imgH = imgW / limitRatio; // new behaviour
		cntT = topH + imgH; // new behaviour
		//console.log("cntT: " + cntT + " vs. " + (topH + h)); // new behaviour
		if (cntT < (topH + h)) h = imgH; // new behaviour
		
		$('#layer-bottom').css('top', (topH + h) + 'px');
		$('#layer-image').css('height', h + 'px');
		$('#gallery-infobox').css('height', h + 'px').css('top', (0 - h) + 'px');
		
		positionFooter();
		
		w = imgW; // new behaviour
		h = imgH; // new behaviour
	} else { // homepage scaling - priority for the image is to fill the stage
		var contentH = $(window).height() - topH - footerH;
		var contentRatio = contentW / contentH;
		if (contentRatio < limitRatio) {
			// height wins and will be scaled
			//alert("scaling h");
			h = contentH;
			if (h > regHeight) h = regHeight; // don't scale over 100%
			w = h * limitRatio;
		} else {
			// width wins and will be scaled
			//alert("scaling w");
			w = contentW;
			if (w > regWidth) w = regWidth; // don't scale over 100%
			h = w / limitRatio;
		}
	}
	l = Math.round((contentW - w) / 2);
	$('#layer-image div.gallery-item').css('height', h + 'px').css('width', w + 'px').css('left', l + 'px'); // position the image
	tl = 0;
	if (l < 0) tl = Math.abs(l);
	//alert(l + " :: " + Math.abs(l));
	$('#layer-image div.gallery-item a').css('left', tl + 'px'); // position the text
	
	// this would be the version where each image has its own text -- $('.gallery-item .gallery-infobox').css('left', (tl + contentW - 480) + 'px').css('height', h + 'px'); // TODO: only needed in editmode?
		
	positionMainNavi();
}

function positionFooter() {
	lbOrigH = $('#content-container .solid-filler').height(); // the natural height of layer-bottom
	existFillH = $('#fill-h').height() || 0;
	fillH = $(window).height() - $('#layer-footer').offset().top - $('#layer-footer').height();
	//console.log("fillH: " + fillH + " / existFillH: " + existFillH);
	if (fillH >= 0) {
		var fh = (_isFullGallery) ? 1 : fillH + existFillH;
		$('#fill-h').remove();
		$('#content-container .solid-filler').append('<div id="fill-h" class="row" style="height:' + fh + 'px"></div>');
	} else {
		nfh = existFillH + fillH;
		if (nfh < 0) nfh = 0;
		$('#fill-h').css('height', nfh + 'px');
	}
}


function beforeLayoutChanged() {
	$('#content-container .solid-filler').css('height', 'auto');	
}

function layoutChanged() {
	//alert("layoutChanged :: " + $('#content-container .solid-filler').height() );
	//$('#content-container').css('height', ($('#content-container .solid-filler').height()) + 'px');
	$(window).trigger('resize');
}



function initSlide() {
	//
	// custom high response swiping - TODO: add touch events
	$.swipeStartX = 0;
	$.swipeTarget = null;
	try {
		$('.gallery-item').on('mousedown ontouchstart', function(event){
			$.swipeTarget = event.currentTarget;
			$.swipeStartX = event.pageX;
			$('.gallery-item').on('mouseup touchend', function(event){
				doSlide(event);
			});
		});
		
		$('.gallery-item').on('mousemove ontouchmove', function(event){
			if ($.swipeTarget) {
				diff = event.pageX - $.swipeStartX
				if (Math.abs(diff) > 150) {
					doSlide(event);				
				} else {
					$($.swipeTarget).children('img').css('left', String(diff)+'px');
				} 
			}
		});
	} catch (e) {};
}

function doSlide(event) {
	$($.swipeTarget).children('img').animate({ left: 0 }, 1000, "linear");
	if (event.pageX < $.swipeStartX - 5) { // left
		slideImage(null, 1);
	} else if (event.pageX > $.swipeStartX + 5) { // right
		slideImage(null, -1);
	}
	$.swipeTarget = null;
	$.swipeStartX = 0;
	$('.gallery-item').off('mouseup touchend');
}



/**
 * the spinner thing
 **/
 
// http://fgnass.github.com/spin.js/
//fgnass.github.com/spin.js#v1.2.2
(function(a,b,c){function n(a){var b={x:a.offsetLeft,y:a.offsetTop};while(a=a.offsetParent)b.x+=a.offsetLeft,b.y+=a.offsetTop;return b}function m(a){for(var b=1;b<arguments.length;b++){var d=arguments[b];for(var e in d)a[e]===c&&(a[e]=d[e])}return a}function l(a,b){for(var c in b)a.style[k(a,c)||c]=b[c];return a}function k(a,b){var e=a.style,f,g;if(e[b]!==c)return b;b=b.charAt(0).toUpperCase()+b.slice(1);for(g=0;g<d.length;g++){f=d[g]+b;if(e[f]!==c)return f}}function j(a,b,c,d){var g=["opacity",b,~~(a*100),c,d].join("-"),h=.01+c/d*100,j=Math.max(1-(1-a)/b*(100-h),a),k=f.substring(0,f.indexOf("Animation")).toLowerCase(),l=k&&"-"+k+"-"||"";e[g]||(i.insertRule("@"+l+"keyframes "+g+"{"+"0%{opacity:"+j+"}"+h+"%{opacity:"+a+"}"+(h+.01)+"%{opacity:1}"+(h+b)%100+"%{opacity:"+a+"}"+"100%{opacity:"+j+"}"+"}",0),e[g]=1);return g}function h(a,b,c){c&&!c.parentNode&&h(a,c),a.insertBefore(b,c||null);return a}function g(a,c){var d=b.createElement(a||"div"),e;for(e in c)d[e]=c[e];return d}var d=["webkit","Moz","ms","O"],e={},f,i=function(){var a=g("style");h(b.getElementsByTagName("head")[0],a);return a.sheet||a.styleSheet}(),o=function r(a){if(!this.spin)return new r(a);this.opts=m(a||{},r.defaults,p)},p=o.defaults={lines:12,length:7,width:5,radius:10,color:"#000",speed:1,trail:100,opacity:.25,fps:20},q=o.prototype={spin:function(a){this.stop();var b=this,c=b.el=l(g(),{position:"relative"}),d,e;a&&(e=n(h(a,c,a.firstChild)),d=n(c),l(c,{left:(a.offsetWidth>>1)-d.x+e.x+"px",top:(a.offsetHeight>>1)-d.y+e.y+"px"})),c.setAttribute("aria-role","progressbar"),b.lines(c,b.opts);if(!f){var i=b.opts,j=0,k=i.fps,m=k/i.speed,o=(1-i.opacity)/(m*i.trail/100),p=m/i.lines;(function q(){j++;for(var a=i.lines;a;a--){var d=Math.max(1-(j+a*p)%m*o,i.opacity);b.opacity(c,i.lines-a,d,i)}b.timeout=b.el&&setTimeout(q,~~(1e3/k))})()}return b},stop:function(){var a=this.el;a&&(clearTimeout(this.timeout),a.parentNode&&a.parentNode.removeChild(a),this.el=c);return this}};q.lines=function(a,b){function e(a,d){return l(g(),{position:"absolute",width:b.length+b.width+"px",height:b.width+"px",background:a,boxShadow:d,transformOrigin:"left",transform:"rotate("+~~(360/b.lines*c)+"deg) translate("+b.radius+"px"+",0)",borderRadius:(b.width>>1)+"px"})}var c=0,d;for(;c<b.lines;c++)d=l(g(),{position:"absolute",top:1+~(b.width/2)+"px",transform:"translate3d(0,0,0)",opacity:b.opacity,animation:f&&j(b.opacity,b.trail,c,b.lines)+" "+1/b.speed+"s linear infinite"}),b.shadow&&h(d,l(e("#000","0 0 4px #000"),{top:"2px"})),h(a,h(d,e(b.color,"0 0 1px rgba(0,0,0,.1)")));return a},q.opacity=function(a,b,c){b<a.childNodes.length&&(a.childNodes[b].style.opacity=c)},function(){var a=l(g("group"),{behavior:"url(#default#VML)"}),b;if(!k(a,"transform")&&a.adj){for(b=4;b--;)i.addRule(["group","roundrect","fill","stroke"][b],"behavior:url(#default#VML)");q.lines=function(a,b){function k(a,d,i){h(f,h(l(e(),{rotation:360/b.lines*a+"deg",left:~~d}),h(l(g("roundrect",{arcsize:1}),{width:c,height:b.width,left:b.radius,top:-b.width>>1,filter:i}),g("fill",{color:b.color,opacity:b.opacity}),g("stroke",{opacity:0}))))}function e(){return l(g("group",{coordsize:d+" "+d,coordorigin:-c+" "+ -c}),{width:d,height:d})}var c=b.length+b.width,d=2*c,f=e(),i=~(b.length+b.radius+b.width)+"px",j;if(b.shadow)for(j=1;j<=b.lines;j++)k(j,-2,"progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)");for(j=1;j<=b.lines;j++)k(j);return h(l(a,{margin:i+" 0 0 "+i,zoom:1}),f)},q.opacity=function(a,b,c,d){var e=a.firstChild;d=d.shadow&&d.lines||0,e&&b+d<e.childNodes.length&&(e=e.childNodes[b+d],e=e&&e.firstChild,e=e&&e.firstChild,e&&(e.opacity=c))}}else f=k(a,"animation")}(),a.Spinner=o})(window,document);

/*

You can now create a spinner using any of the variants below:

$("#el").spin(); // Produces default Spinner using the text color of #el.
$("#el").spin("small"); // Produces a 'small' Spinner using the text color of #el.
$("#el").spin("large", "white"); // Produces a 'large' Spinner in white (or any valid CSS color).
$("#el").spin({ ... }); // Produces a Spinner using your custom settings.

$("#el").spin(false); // Kills the spinner.

*/
(function($) {
	$.fn.spin = function(opts, color) {
		var presets = {
			"tiny": { lines: 8, length: 2, width: 2, radius: 3 },
			"small": { lines: 8, length: 4, width: 3, radius: 5 },
			"large": { lines: 10, length: 8, width: 4, radius: 8 }
		};
		if (Spinner) {
			return this.each(function() {
				var $this = $(this),
					data = $this.data();
				
				if (data.spinner) {
					data.spinner.stop();
					delete data.spinner;
				}
				if (opts !== false) {
					if (typeof opts === "string") {
						if (opts in presets) {
							opts = presets[opts];
						} else {
							opts = {};
						}
						if (color) {
							opts.color = color;
						}
					}
					data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
				}
			});
		} else {
			throw "Spinner class not available.";
		}
	};
})(jQuery);

_loadNextImage = function (pic){
	if(pic.attr("class") == 'gallery-image'){
		var next = pic.parent().next().children();
		pic.load( function(){
			_loadNextImage(next)
		});
		
		var src = pic.attr("altsrc");
		pic.attr("src", src);
		$('#gallery-infobox div.scrollbox').append("<div class='gallery-thumb'><img src='" + src + "?maxheight=200' height='100%'></div>");
	}
}


$('#gallery-image-no0').load(function (){
	_loadNextImage($('#gallery-image-no1'));
});
	

