// -- Non-Blocking Google Analytics --------------------------------------------
var ga=function(A){var E,G,C,B;E={yahoo:{merge:function(I,H){return YAHOO.lang.merge(I,H);},getScript:function(H,I){YAHOO.util.Get.script(H,{onSuccess:I});}},jquery:{merge:function(I,H){return jQuery.extend({},I,H);},getScript:function(H,I){jQuery.getScript(H,I);}}};if(typeof A!="undefined"){A=A;}else{if(typeof YAHOO!="undefined"){A=E.yahoo;}else{if(typeof jQuery!="undefined"){A=E.jquery;}}}G={url:{http:"http://www.google-analytics.com/ga.js",https:"https://ssl.google-analytics.com/ga.js"}};C=null;B=false;function F(){var H,I;H=(document.location.protocol=="https:");I=(H&&C.url.https)?(C.url.https||C.url):(C.url.http||C.url);A.getScript(I,function(){C.tracker=_gat._getTracker(C.id);B=true;while(C.queue.length>0){D.track(C.queue.shift());}});}var D={config:function(H){H=A.merge(G,(H||{}));if(!C&&H.id){C=H;C.queue=[];F();}return this;},track:function(H){if(B){if(H){C.tracker._trackPageview(H);}else{C.tracker._trackPageview();}}else{if(C){C.queue.push(H||null);}}return this;}};return D;}();

// -- Browser Detection --------------------------------------------------------
(function($){$.browserTest=function(a,z){var u='unknown',x='X',m=function(r,h){for(var i=0;i<h.length;i=i+1){r=r.replace(h[i][0],h[i][1]);}return r;},c=function(i,a,b,c){var r={name:m((a.exec(i)||[u,u])[1],b)};r[r.name]=true;r.version=(c.exec(i)||[x,x,x,x])[3];if(r.name.match(/safari/)&&r.version>400){r.version='2.0';}if(r.name==='presto'){r.version=($.browser.version>9.27)?'futhark':'linear_b';}r.versionNumber=parseFloat(r.version,10)||0;r.versionX=(r.version!==x)?(r.version+'').substr(0,1):x;r.className=r.name+r.versionX;return r;};a=(a.match(/Opera|Navigator|Minefield|KHTML|Chrome/)?m(a,[[/(Firefox|MSIE|KHTML,\slike\sGecko|Konqueror)/,''],['Chrome Safari','Chrome'],['KHTML','Konqueror'],['Minefield','Firefox'],['Navigator','Netscape']]):a).toLowerCase();$.browser=$.extend((!z)?$.browser:{},c(a,/(camino|chrome|firefox|netscape|konqueror|lynx|msie|opera|safari)/,[],/(camino|chrome|firefox|netscape|netscape6|opera|version|konqueror|lynx|msie|safari)(\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/));$.layout=c(a,/(gecko|konqueror|msie|opera|webkit)/,[['konqueror','khtml'],['msie','trident'],['opera','presto']],/(applewebkit|rv|konqueror|msie)(\:|\/|\s)([a-z0-9\.]*?)(\;|\)|\s)/);$.os={name:(/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase())||[u])[0].replace('sunos','solaris')};if(!z){$('html').addClass([$.os.name,$.browser.name,$.browser.className,$.layout.name,$.layout.className].join(' '));}};$.browserTest(navigator.userAgent);})(jQuery);

// -- Background Position Plugin -----------------------------------------------
// http://plugins.jquery.com/project/backgroundPosition-Effect
(function($){
	
	if(!document.defaultView || !document.defaultView.getComputedStyle){
		var oldCurCSS = jQuery.curCSS;
		jQuery.curCSS = function(elem, name, force){
			if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
				return oldCurCSS.apply(this, arguments);
			}
			var style = elem.style;
			if ( !force && style && style[ name ] ){
				return style[ name ];
			}
			return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
		};
	}
})(jQuery);

(function($) {
	
	function toArray(strg){
		strg = strg.replace(/left|top/g,'0px');
		strg = strg.replace(/right|bottom/g,'100%');
		strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
		var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
		return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
	}
	
	$.fx.step. backgroundPosition = function(fx) {
		if (!fx.bgPosReady) {
			
			var start = $.curCSS(fx.elem,'backgroundPosition');
			if(!start){//FF2 no inline-style fallback
				start = '0px 0px';
			}
			
			start = toArray(start);
			fx.start = [start[0],start[2]];
			
			var end = toArray(fx.options.curAnim.backgroundPosition);
			fx.end = [end[0],end[2]];
			
			fx.unit = [end[1],end[3]];
			fx.bgPosReady = true;
		}
		
		var nowPosX = [];
		nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
		nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
		fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

	};
})(jQuery);


// -- Easing Plugin ------------------------------------------------------------
// http://gsgd.co.uk/sandbox/jquery/easing/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	}
});

// -- Utilities ----------------------------------------------------------------
field = {
	info: function(msg) {
		if(typeof console != "undefined")
			console.info(msg)
	},
	
	preload: function() {
		for(var i = 0; i<arguments.length; i++) {
	    jQuery("<img>").attr("src", arguments[i]);
	  }
	},
	
	hoverImage: function(url) {
		var over = url.substring( 0, url.search(/(\.[a-z]+)$/) ) + '_o' + url.match(/(\.[a-z]+)$/)[0]
		field.preload(over)
		return over
	},
	
	isFontFaceSupported: function() {
		var version = parseFloat($.browser.version)
		return ($.browser.safari && version >= 3.1) ||
					 ($.browser.mozilla && version >= 3.5) ||
	 				 ($.browser.chrome && version >= 3)
	},
	
	templateURL: function() {
		var template_url = null
		$("head").children("link").each(function(i) {
			if($(this).attr('rel') == 'stylesheet' && template_url == null) {
				var url = $(this).attr('href')
				template_url = url.substring(0, url.lastIndexOf('/')+1)
			}
		})
		return template_url
	},
	
	loadCSS: function(url) {
		field.info("loading "+ url)
		
		var head = document.getElementsByTagName('head')[0]; 
		$(document.createElement('link')).attr({
			type: 'text/css', 
			href: url, 
			rel: 'stylesheet',
			media: 'screen'
		}).appendTo(head);
	}
}

// -- Grid ---------------------------------------------------------------------
field.grid = {
	init: function() {
		field.grid.cells.init()
		field.grid.initLogo()
		this.viewer = new field.grid.viewer();
		
		var template_dir = '/wp-content/themes/glahn2009/'
		
		$(document).keypress(function(e) {
			switch(e.which) {
				// 'g' - toggles grid
				case 103:
					if($('body').css('backgroundImage') == 'none') {
						$('body').css('backgroundImage', 'url(../'+template_dir+'images/grid39x49.png)')
					} else {
						$('body').css('backgroundImage', 'none')
					}
					break
			}
		})
	},
	
	initLogo: function() {
		var logo = $("#logo h1 a img")
		var normal = $(logo).attr('src')
		var hover = field.hoverImage(normal)				
		$(logo).hover( 
			function() { $(logo).attr('src', hover) },
			function() { $(logo).attr('src', normal) })
	}
}

// -- Cells --------------------------------------------------------------------
field.grid.cells = {
	init: function() {
		this.initCategories()
		this.initListItems()
		this.initImages()
		this.initMaps()
	},
	
	initCategories: function() {
		$(".categoryCell").each(function(i) {
			$(this).hover(
				function() {
					$(this).css('opacity', 0.5)
					$(this).stop().fadeTo(250, 1.0)
				},
				function() {})

			$(this).click(function() {
				document.location.href = $(this).find('a').attr('href')
			})				
		})
	},
	
	initListItems: function() {
		$(".listCell").each(function(i) {
			var img = $(this).find("img")
			var url = img.attr('src')
			$(img).remove()
			
			$(this).hover(
				function() { 
					$(this).css('backgroundImage', 'url('+url+')') 
					$(this).css('opacity', 0.5)
					$(this).stop().fadeTo(250, 1.0)
					$(this).find("div.innerCell").css('opacity', 0.0)
				},
				function() { 
					$(this).css('backgroundImage', 'none') 
					$(this).find("div.innerCell").css('opacity', 0.5)
					$(this).find("div.innerCell").stop().fadeTo(250, 1.0)
			})

			$(this).click(function() {
				document.location.href = $(this).find('a').attr('href')
			})
		})
	},
	
	initImages: function() {
		$(".imageCell").each(function(i) {
			var img = $(this).children()
			var normal = img.attr('src')
			var hover = field.hoverImage(normal)
			var large = normal.substring( 0, normal.search(/(\.[a-z]+)$/) - 2 ) + normal.match(/(\.[a-z]+)$/)[0]

			if(!$.browser.msie) {
				field.preload(large)
			}

			$(this).css('backgroundImage', 'url('+ normal +')');
			$(img).remove()

			$(this).hover( 
				function() { 
					$(this).css('backgroundImage', 'url('+ hover +')')
					$(this).css('backgroundColor', '#140e08')
					$(this).css('opacity', 0.5)
					$(this).stop().fadeTo(250, 1.0)
				}, function() { 
					$(this).css('backgroundImage', 'url('+ normal +')')
					$(this).css('backgroundColor', 'transparent')
					// $(this).stop().fadeTo(250, 1.0)
			})

			$(this).click(function() {
				field.grid.viewer.open('image',large)
			})
		})
	},
	
	initMaps: function() {
		$(".mapCell").each(function(i) {
			var img = $(this).children()
			var normal = img.attr('src')
			var address = img.attr('alt')
			var hover = field.hoverImage(normal)

			$(this).css('backgroundImage', 'url('+ normal +')');
			$(img).remove()
			
			$(this).hover( 
				function() { 
					$(this).css('backgroundImage', 'url('+ hover +')')
					$(this).css('backgroundColor', '#140e08')
					$(this).css('opacity', 0.5)
					$(this).stop().fadeTo(250, 1.0)
				}, function() { 
					$(this).css('backgroundImage', 'url('+ normal +')')
					$(this).css('backgroundColor', 'transparent')
					// $(this).stop().fadeTo(250, 1.0)
			})

			$(this).click(function() {
				field.grid.viewer.open('map', address)
			})
		})
	}
}

// -- Viewer -------------------------------------------------------------------
field.grid.viewer = function() {
	// fields
	var x = 0
	var y = 0
	var width = 0
	var height = 0
	var alignRight = false
	
	// init
	var cell = $(".viewerCell")
	var mapcontainer = undefined
	
	this.init = function() {
		field.info('viewer: init')
	
		var default_img = $(cell).children().get(0)
		var default_img_src = $(default_img).attr('src')
		alignRight = $(default_img).attr('align') == 'right'
		
		// get dimensions of the default image
		width = $(default_img).width()
		height = $(default_img).height()
		$(default_img).remove()
		
		// get default position
		x = $(cell).position().left
		y = $(cell).position().top
		
		// init styling
		$(cell).css({
			'left': x + width/2 +'px',
			'top': y + height/2 +'px',
	 		'width': '0px',
	 		'height': '0px',
			'opacity': 0.0,
			'backgroundPosition': (-width/2) +'px '+ (-height/2) +'px',
			'backgroundRepeat': 'no-repeat'
		})
		
		// add map div
		$(cell).html('<div id="map" style="margin:2px"></div>')
		mapcontainer = $("#map")
		
		// load default image
		this.open('image', default_img_src)
	}
		
	this.open = function(type, arg) {
		field.info('viewer: open '+ type +' '+ arg)
		
		if(type == 'image') {
			this.openImage(arg)
			
		} else if(type == 'map') {
			this.openMap(arg)
		}
	}
	
	this.openImage = function(url) {
		var img = new Image()
		img.src = url
		img.onload = function() {
			field.info('viewer: openImage: '+ url +' size: '+ img.width +'x'+ img.height)

			$(cell).css('backgroundImage', 'url('+ url +')')
			$(cell).css('opacity', 0.5)

			$(mapcontainer).fadeOut(250)
			
			var alignX = (alignRight) ? width - img.width: 0
			
			$(cell).stop().animate({
				'left': (x + alignX) +'px',
				'top': y + 'px',
				'width': img.width +'px',
				'height': img.height +'px',
				'opacity': 1.0,
				'backgroundPosition': '(0px 0px)'
			}, 500, 'easeInOutQuart')
		}
	}
	
	this.openMap = function(address) {
		field.info('viewer: openMap: '+ address)
				
		var width = 572
		var height = 355
		
		$(cell).css('backgroundImage', 'none')
		$(cell).css('opacity', 0.5)

		$(cell).stop().animate({
				'left': x +'px',
				'top': y + 'px',
				'width': width +'px',
				'height': height +'px',
				'opacity': 1.0
			}, 500);
			
		$(mapcontainer).fadeIn(250, function() {
			$(this).css({
				'width': width+'px',
				'height': height+'px',
				'padding': 0,
				'margin': 0
			})
			
			// init map
			var map = new GMap2( document.getElementById("map") )
			map.addControl(new GSmallMapControl())
			
			// get address and center on it
			var geo = new GClientGeocoder()
			geo.getLocations(address, function(response) {
				if (response.Status.code == G_GEO_SUCCESS) {
					var place = response.Placemark[0];
					var point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
					marker = new GMarker(point);
					map.addOverlay(marker);

					// marker.openInfoWindowHtml(
					// 	'<b>orig latlng:</b>' + response.name + '<br/>' + 
					// 	'<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
					// 	'<b>Status Code:</b>' + response.Status.code + '<br>' +
					// 	'<b>Status Request:</b>' + response.Status.request + '<br>' +
					// 	'<b>Address:</b>' + place.address + '<br>' +
					// 	'<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
					// 	'<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode);
					// 						  }

					map.setCenter(point, 14)
					field.info("viewer map center: "+ point)
				}
			})
		})
	}
	
	// initialize viewer
	if($(cell).length > 0) this.init()
}

// -- Init ---------------------------------------------------------------------
if(field.isFontFaceSupported())
	field.loadCSS(field.templateURL() + "style_custom_font.css")

$(document).ready(function() {
	if(jQuery.browser.safari && document.readyState != "complete"){
		field.info('safari init delay...')
		setTimeout(arguments.callee, 20)
		return
	}
	
	field.info('ready...')	
	field.info('Browser: '+ $.browser.name +' Version: '+ $.browser.version)

		
	field.grid.init()
})
