window.isTouch	= ( (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)) );
window.PROJECTS_CALLBACK = [];

jQuery(function($){
	if($('.menublock').length){
		$('.menublock').each(function(){
			if($('ul.menu', this).length){
				var list = $('ul.menu', this),
					h = (list.prev().outerHeight() + 3) + 'px',
					m = list.width(list.width()).hide();

				m.css({'position':'absolute','top':h});

				if(window.isTouch) {
					var pos = $(this).offset(), sel = $('<select></select>').css({'position':'absolute','left':pos.left+'px','top':-pos.top+'px','z-index':'-9999'/*,'visibility':'hidden'*/}).prependTo('body');
					$('li > a', list).each(function(){
						var selected = ($(this).hasClass('current')) ? ' selected' : '';
						sel.append('<option value="'+this.href+'"'+selected+'>'+this.text+'</option>');
					});
					sel.change(function(){window.location.href = this.value;});
					$(this).click(function(){sel.focus();});
/*
					if($('#projects').length) {
						window.PROJECTS_CALLBACK.push(function(){
							sel.css('visibility','visible');
						});
					}
*/
				} else {
					$(this).hover(function(){
						clearTimeout(window.MenuTimer);
						$('.menublock > ul.menu').hide();
						m.show();
					}, function(){
						window.MenuTimer = setTimeout(function(){m.hide();}, 600);
					});
				};

				m.hide();
			}
		});
	};
});

jQuery(function($){
	if($('.download-image').length){
		$('.download-image').hover(function(){
			if(!$('.download-icon', this).length) {
				$('<span class="download-icon"></span>').appendTo(this);
			};

			$('img', this).css('opacity',0.3);
			$('.download-icon', this).show();
		}, function(){
			$('.download-icon', this).hide();
			$('img', this).css('opacity',1);
		});
	};
});

jQuery(function($){
	if($('#map-canvas').length){
		$('#container').css('background','none');
		setMapHeight();
		
		var map = initMap();
		$(window).resize(throttle(function(){
			setMapHeight.apply(setMapHeight, [map]);
		}, 250));
	};
});

jQuery(function($){
	if($('#homepage').length) {
		$('#homepage li').each(function(){
			var top = $('.toppage', this),
				article = $('.article', this),
				footer = $('.footer', this),
				text = {more:'Read more',less:'Hide'};

			var h	= Math.round(top.outerHeight(true)+footer.outerHeight(true)),
				ah	= article.height(),
				at	= article.outerHeight(true),
				th	= Math.round(at+h),
				ch	= Math.round((524-h)-(at-ah));

			if(th != 524) article.height(ch).css('overflow','hidden');
			if(th  > 524) {
				$(this).addClass('collapsible').attr({'collapsed-height':ch,'orig-height':ah});
				article.append('<div class="fade"></div>');
				$('<a href="javascript:void(0)" class="more"></a>').text(text.more).appendTo(footer).click(function(){
					var $this = $(this);
					if(!$(this).hasClass('more-open')) {// expand
						$('#homepage li.collapsible').each(function(){
							if($('.more', this).hasClass('more-open')) {
								$('.article', this).animate({height:$(this).attr('collapsed-height')+'px'}, 'fast', function(){
									$('.more', $(this).parent()).text(text.more).removeClass('more-open');
								});
							}
						});
						article.animate({height:ah+'px'}, 'fast', function(){
							$this.text(text.less).addClass('more-open');
						});
					} else {// collapse
						article.animate({height:ch+'px'}, 'fast', function(){
							$this.text(text.more).removeClass('more-open');
						});
					};
					return false;
				});
			};
		});
	};
});

jQuery(function($){
	if($('#projects').length && typeof PROJECT_GALLERY != 'undefined'){
		//$('#supersized').after('<div id="controls-wrapper"><a id="prevslide"><span>Prev</span></a><a id="nextslide"><span>Next</span></a></div>');
		
		var c = $('.collapsible'),
			t = $('#trigger').css('opacity',.8),
			l =	$('<div class="loader"></div>').height(t.height()).prependTo(t),
			p = $('#controls'),
			s = t.find('span').hide().detach(),
			b = true,
			title = t.find('a').text();

		$('.grid-1, .grid-2',c).css('opacity',.8);
		c.hide();
		t.find('a').text('Loading...');
		
		var GALIMG = [];
		$.each(PROJECT_GALLERY, function(k,v){
			var i = k+1;
			GALIMG.push({'image':v});
			$('#controls').append('<a title="Jump to image '+i+'"><span>'+i+'</span></a>')
		});

		$.preload(PROJECT_GALLERY,
			{
			'onComplete':function(d){
				var p = Math.round((d.loaded/d.total)*100);
				l.stop().animate({'width':p+'%'}, 600, function(){
					if(p >= 100) b = false;
				});
			},
			'onFinish':function(){
				var intervalID = window.setInterval(function(){
					if(!b) {
						clearInterval(intervalID);
						t.addClass('loaded');
						l.remove();
						$.supersized({
							transition_speed		: 400,
							slides 					:  	GALIMG,
							onload					:	function(){
								s.appendTo(t.find('a').text(title));
								t.find('span').show();

								if(window.PROJECTS_CALLBACK.length) {
									for(var i=0;i<window.PROJECTS_CALLBACK.length;i++) {
										if(typeof window.PROJECTS_CALLBACK[i] == 'function'){
											window.PROJECTS_CALLBACK[i]();
										}
									}
								};

								$('a',t).click(function(){
									if(c.is(':visible')){
										projInfo.close();
									} else {
										projInfo.open();
									};
									return false;
								});//.trigger('click');
							}
						});
					}
				}, 500);
				
			}
		});
		
		var projInfo = {
			open: function(){
				if(c.is(':hidden')){
					c.fadeIn();
				};
				$('a span',t).html('&ndash; INFO');
			},
			close: function(){
				if(c.is(':visible')){
					c.fadeOut();
				};
				$('a span',t).text('+ INFO');
			}
		};
		
		$(document.documentElement).keyup(function (event) {
			if(event.keyCode == 38 || event.keyCode == 40){
				switch(event.keyCode){
					case 38: projInfo.open(); break
					case 40: projInfo.close(); break;
				};
			};
		});
	}
});

function initMap() {
	// splits the latlong string into array "lat,long" > {lat,long}
	var LLarray = LL.split(","), thisMap = new google.maps.LatLng(LLarray[0],LLarray[1]), marker, map, zm = 16;
	
	// setup google maps parameters including custom styling
	var styles = [
		{featureType: "all",elementType: "all",stylers: [{ hue: "#d9eeed" },{saturation:-60},]},
		{featureType: "road.local",elementType: "all",stylers: [{ hue: "#d9eeed" },{ lightness: 0 },{saturation:0}]},
		{featureType: "road.arterial",elementType: "all",stylers: [{ hue: "#d9eeed" },{ lightness: -0 },{ saturation: 0}]},
		{featureType: "road.highway",elementType: "all",stylers: [{ hue: "#d9eeed" },{ lightness: -0 },{ saturation: 0}]},
		{featureType: "transit.station",elementType: "all",stylers: [{ hue: "#d9eeed" },{ lightness: -0 },{ saturation: 0}]},
		{featureType: "poi.school",elementType: "all",stylers: [{ visibility: "off" }]},
		{featureType: "poi.medical",elementType: "all",stylers: [{ visibility: "off" }]},
		{featureType: "poi.place_of_worship",elementType: "all",stylers: [{ visibility: "off" }]},
		{featureType: "landscape.natural",elementType: "all",stylers: [{ visibility: "off" }]},
		{featureType: "water",elementType: "all",stylers: [{hue: "#d9eeed" },{ lightness: 20 },{ saturation: 20}]},
		{featureType: "poi.sports_complex",elementType: "all",stylers: [{ visibility: "off" }]},
		{featureType: "transit.station.rail",elementType: "all",stylers: [{ hue: "#d9eeed" },{ saturation: 0}]},
		{featureType: "transit.line",elementType: "all",stylers: [{ hue: "#d9eeed" },{ saturation: 0}]},
		{featureType: "administrative",elementType: "all",stylers: [{ visibility: "off" }]},
		{featureType: "transit.station.airport",elementType: "all",stylers: [{ visibility: "off" }]},
		{featureType: "poi.park",elementType: "all",stylers: [{ hue: "#d9eeed" },{ lightness: 60 },{ saturation: 20}]},
		{featureType: "landscape",elementType: "all",stylers: [{ hue: "#ffffff" },{ lightness: 100 }]},
		{featureType: "landscape.natural",elementType: "all",stylers: [{ visibility: "off" }]},
		{featureType: "landscape.man_made",elementType: "all",stylers: [{ visibility: "off" }]}
	];
	var mapOptions = {
		zoom:zm,
		center:thisMap,
		disableDefaultUI:true,
		//mapTypeControlOptions:{mapTypeIds:['pro',google.maps.MapTypeId.SATELLITE]},
		zoomControl:true,
		zoomControlOptions:{
			style:google.maps.ZoomControlStyle.SMALL,
			position:google.maps.ControlPosition.LEFT_CENTER
		},
		panControl:true,
		panControlOptions:{
			position:google.maps.ControlPosition.LEFT_CENTER
		}
	};
	map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
	var image = '/images/google.png';
	marker = new google.maps.Marker({map:map,draggable:false,animation:google.maps.Animation.DROP,position:thisMap,icon:image});
	var styledMapOptions = {name:"Map"};
	
	var promap = new google.maps.StyledMapType(styles, styledMapOptions);
	map.mapTypes.set('pro', promap);
	map.setMapTypeId('pro');

	return map;
};

function setMapHeight(map) {
	if($('#map-canvas').length) {
		var m = $('#map-canvas'), h = $(document).height();
		if(m.height() != h) {
			m.height(h);
			if(typeof map == 'object') {
				map.setCenter(map.getCenter(), map.zoom);
			}
		}
	}
};

function throttle(fn, delay) {
	var timer = null;
	return function () {
		var context = this, args = arguments;
		clearTimeout(timer);
		timer = setTimeout(function () {
			fn.apply(context, args);
		}, delay);
	}
};

/*
 * jQuery.Preload
 * @version 1.0.8
 */
(function($){var h=$.preload=function(c,d){if(c.split)c=$(c);d=$.extend({},h.defaults,d);var f=$.map(c,function(a){if(!a)return;if(a.split)return d.base+a+d.ext;var b=a.src||a.href;if(typeof d.placeholder=='string'&&a.src)a.src=d.placeholder;if(b&&d.find)b=b.replace(d.find,d.replace);return b||null}),data={loaded:0,failed:0,next:0,done:0,total:f.length};if(!data.total)return finish();var g=$(Array(d.threshold+1).join('<img/>')).load(handler).error(handler).bind('abort',handler).each(fetch);function handler(e){data.element=this;data.found=e.type=='load';data.image=this.src;data.index=this.index;var a=data.original=c[this.index];data[data.found?'loaded':'failed']++;data.done++;if(d.enforceCache)h.cache.push($('<img/>').attr('src',data.image)[0]);if(d.placeholder&&a.src)a.src=data.found?data.image:d.notFound||a.src;if(d.onComplete)d.onComplete(data);if(data.done<data.total)fetch(0,this);else{if(g&&g.unbind)g.unbind('load').unbind('error').unbind('abort');g=null;finish()}};function fetch(i,a,b){if(a.attachEvent&&data.next&&data.next%h.gap==0&&!b){setTimeout(function(){fetch(i,a,1)},0);return!1}if(data.next==data.total)return!1;a.index=data.next;a.src=f[data.next++];if(d.onRequest){data.index=a.index;data.element=a;data.image=a.src;data.original=c[data.next-1];d.onRequest(data)}};function finish(){if(d.onFinish)d.onFinish(data)}};h.gap=14;h.cache=[];h.defaults={threshold:2,base:'',ext:'',replace:''};$.fn.preload=function(a){h(this,a);return this}})(jQuery);
