if( typeof( window.console ) === "undefined" ) {
	window.console = {log: $.noop}
}

var deUrlify = function(str) {
	return str.replace(/\/|\s/g, "");
};
var bestRatio = function( w1, h1, w2, h2, fill ) {
	if( fill ) return ( ( w1 / w2 ) > ( h1 / h2 ) ) ? ( w1 / w2 ) : ( h1 / h2 );
	else return ( ( w1 / w2 ) < ( h1 / h2 ) ) ? ( w1 / w2 ) : ( h1 / h2 );
}

$(function() {
	
	jQuery("time.timeago").timeago();
	//Enables state handling in address.
	$.address.state("/");

	$("header a, #breadcrumb a, header h1 a, footer .greeting a").address();
	if(!window.history.pushState) {
		$("header h1 a, #breadcrumb a:first, footer .greeting p a").live( "click", function(){
			$(this).attr("href", "/start");
			return false;
		});
	}
	
	var initialized = false,
		req;
	
	$(window).bind("resize.footer", function(){
		var h = $("body").height() + $("footer").outerHeight() + parseInt( $("footer").css("marginTop") );
		$("footer:visible").toggleClass("bottom", h < $(window).height() );
	});	
	
	$("#updates article").css({width: 0, paddingLeft: 0, paddingRight: 0, overflow: "hidden"}).hide();
	$("#updates .tabs a").click( function(){
		var f, w = 294;
		if( $(this).parent().is(".tweet") ) {
			f = "#tweets";
		} else if( $(this).parent().is(".favorite") ) {
			f = "#favorites";
		} else {
			return true;
		}
		var el = $("#updates article").filter(f);
		if( el.width() != w )
			if( $("#updates article:visible").length ) {
				$("#updates article:visible").trigger("out", [true]);
			} else {
				el.trigger("in");
			}
		else 
			el.trigger("out");
		return false;
	});
	
	$("#updates article").bind("in", function(){
		var w = 294;
		var el = $(this);
		el.animate({width: w, paddingLeft: 25, paddingRight: 10}, "fast").show();
	});
	
	$("#updates article").bind("out", function(e, showSibling){
		var el = $(this);
		el.animate({width: 1, paddingLeft: 0, paddingRight: 0}, {duration: "fast", complete: function(){ $(this).hide(); if(showSibling) { $(this).siblings().trigger("in") } }});
	});
	
	$("#updates article").bind("paging", function(){
		var el = $(this);
		var offset = $(this).data("length"),
		li = $("ul:not(.pagination) li", $(this));
		if( li.length > offset && offset > 0 ) {
			if( !$(".pagination", $(this)).length ) {
				var pagination = $("<div class='pagination group black'><ul class='pagination'></ul></div>");
				for( var i = 0; i < li.length / offset; i++) {
					var page = $("<li><a href='' title=''><span>Page " + i + "</span></a></li>");
					$("ul", pagination).append( page );
				}
				$(this).append(pagination);
				$("a", pagination).click( function( e ){
					$(this).parent().addClass("active").siblings().removeClass("active");
					el.trigger("paging");
					return false;
				}).first().parent().addClass("active");
			}
			var index = $(".pagination ul li.active", $(this)).prevAll().length;
			li.hide().slice( index*offset, (index +1)*offset ).show();
		}
	}).each( function(){
		$(this).trigger("paging");
	});
	
	$(document).click(function(e){
		if( !$(e.target).closest("#updates").length ) {
			$("#updates article").trigger("out");
		}
	});
	
	var asideHandling = function( show ){
		if(show){
			$("#updates").show();
			var url = "/feed/";
			var user = {slug: ""};
			if( $("#artist").length ) {
				user = {slug: $("#artist").data("path").split("/").pop() }
			}
			
			if( url != $("#updates").data("feed") || user.slug != $("#updates").data("slug") ) {
				$("#updates").data("feed", url);
				$("#updates").data("slug", user.slug || "" );
				$.get(url,user,function(data){
					if( data == "" ) return;
					$("#updates article#tweets ul.feed").html(data);
					$("#updates article#tweets").trigger("paging");
					jQuery("time.timeago").timeago();
				});
			}
		} else {
			$("#updates").hide();
		}
	}
	
	/***************************************
	*  START PAGE
	****************************************/
	var setupStartpage = function(){
		$("#main a").address();
	}
	if( $("#main").length ) { setupStartpage(); }
	
	/***************************************
	*  ARTIST OVERVIEW
	****************************************/
	var setupArtistOverview = function(){
		$("article.artist").mouseenter( function(){
		}).mousemove( function(e){
			var pos = (e.pageX - $(this).offset().left) / $(this).width(),
			index = Math.round( pos * ( $("li", $(this) ).length-1 ) ),
			li = $("li", $(this)).eq(index),
			img = $("img", li);
			if( !img.attr("src") ) img.attr("src", img.data("src"));
			if( li.is(":hidden") ) li.show(0);
			$("li", $(this)).not(":hidden, :eq("+index+")").hide(0);
		});
	
		$("article.artist").each( function(){
			$("li", $(this)).hide();
			$("li:first", $(this)).show(0);
			$("a", $(this)).address();
			
			if( Modernizr.touch ) {
				$(".buttons a").touchEvents();
				$("a", $(this)).unbind("touchStart").bind("touchStart", function(){
					$(this).click();
				});
			}
			
			$("img", $(this)).fadeTo( 0, 0).load( function(){
				$(this).fadeTo( "fast", 1 );
			});
		})
	}
	if( $("#artists-overview").length ) { setupArtistOverview(); }
	
	/***************************************
	*  SEARCH
	****************************************/
	$("#search ul.search-results").slideUp(0);
	(function(){
		var t, q = $("#s").val(),
		form = $("#search"),
		b = $("button", form),
		request;
		$("#s").placeholder().focus(function(){
			$(this).closest("fieldset").addClass("active");
			$(".search-results",form).stop(true, false).slideDown("fast");
		}).keyup(function(){
			clearTimeout(t);
			if( request ) request.abort();
			t = setTimeout(function(){
				var sb = $(".search-results li.all-results a",form);
				if( $("#s").val() != q ) {
					b.addClass("loading");
					request = $.ajax({
						url: form.attr("action") + "?qs=" + $("#s").val(),
						cache: !$.browser.msie,
						success: function(res){
							if( $.trim( res ) != "" ) {
								$(".search-results",form).remove();
								form.append(innerShiv(res, false));
								$(".search-results a",form).click( function(e){
									$("body").trigger("click");
									e.stopImmediatePropagation();
									$.address.value($(this).attr("href"));
									return false;
								});
								if( $(".search-results li", res).length < 2 ) {
									sb = $(".search-results a",form);
									sb.html(sb.data("empty"));
								}
							} else {
								if( $("#s").val() == "" ) {
									$(".search-results li:not(.all-results)",form).remove();
								}
								sb.html(sb.data("empty"));
							}
							b.removeClass("loading");
						}
						
					})
					q = $("#s").val()
				}
			}, 500)
		})
		$(document).click(function(e){
			if( !$(e.target).closest("#search").length )
				$(".search-results",form).slideUp("fast", function(){
					$("#s").closest("fieldset").removeClass("active");
				});
		})
		form.submit( function( e ){
			$.address.value(form.attr("action") + "?" + $(this).serialize());
			$("body").trigger("click");
			$("#s").blur();
			return false;
		})
	})()
	
	
	
	/***************************************
	*  SEARCH RESULT
	****************************************/	
	var setupSearchResult = function() {
		$("#search_results #more").unbind("click").bind("click", function() {
			var btn = $(this);
			$("body").addClass("loading");
			$.get( $(this).attr("href"), function(data){
				data = $(data);
				$("#search_results").append($("article.media, article.more", data));
				btn.closest("article").remove();
				setupSearchResult();
				$("body").trigger("loaded");
			})
			return false;
		})
		$("#search_results a:not(#more)").address();
		if( $("article.artist").length ) setupArtistOverview();
	}
	if( $("#search_results").length ) { setupSearchResult(); }
	
	
	
	/***************************************
	*  ARTIST 
	****************************************/
	var setupArtist = function(){
		$("article.collection li a, .case-study li a, article.contact a").address();
		var t, tCid;
		$("article.collection li a").mouseenter( function(){
			var li = $(this).closest("li"),
			cid = li.data("cid");
			if(cid) $("img", li.siblings("[data-cid="+cid+"]")).addClass("hover");
			$("img",$(this)).addClass("hover");
			$(".info",$(this)).fadeIn(0);
			if( cid == tCid )
				clearTimeout( t );
		}).mouseleave( function(){
			var li = $(this).closest("li"),
			cid = li.data("cid"),
			el = $(this);
			if( cid ) {
				t = setTimeout( function(){
			    	$("img", li.siblings("[data-cid="+cid+"]")).removeClass("hover");
				    $("img",el).removeClass("hover");
				}, 50);
				tCid = cid;
			} else {
				$("img",el).removeClass("hover");
			}
			$(".info",$(this)).fadeOut(0);
		}).mousemove( function( e ){
			var fc = $(".info", $(this)),
			l = Math.round(e.pageX - $(this).offset().left - (fc.width() * .5)),
			t = Math.round(e.pageY - $(this).offset().top) - fc.height() - 15;
			fc.css( { left: l, top: t });
		}).click( function(){
			$(this).trigger("mouseleave");
		}).each( function(){
			//HACK TO FORCE SET WIDTH TO AVOID CLIPPING
			$(".info",$(this)).css({position:"relative", width: 300});
			$(".info",$(this)).width( $(".info span",$(this)).width() + 2 );
			$(".info",$(this)).css("position", "absolute").hide();
		});
		
		$("#artist a.bio").click( function(){
			$("html, body").animate({scrollTop: $("#artist-info").offset().top}, 400);
			return false;
		});
		
	}
	
	if( $("section#artist").length ){ setupArtist(); }
	
	/***************************************
	*  OVERLAY
	****************************************/
	var media, x;
	var setupOverlay = function() {
		var overlay = $("#overlay").removeClass("infoview");
		$("body:visible").children(":not(#overlay)").hide();
		$("#overlay .thumbnails a:not([address=true]), #overlay a.arrow, #overlay a.close:not([address=true])").address();
		x = null;
		media = $(".media-entry", overlay);
		
		$(window).unbind("resize.img").bind("resize.img", function(){
			var w = $(window).width(), h = $(window).height(),
			m = $("img", media);
			if( !m.length ) return;
			if( (w > 800 || h > 800) && m.attr("src") != m.data("large") ) {
				m.attr("src", m.data("large"));
			} 
		}).trigger("resize.img");
		
		if( $("img", media).length ) {
			$(".media", overlay).addClass("preloader");
		
			$("img", media).load(function(){
				$(this).fadeTo("fast", 1);
				if( Modernizr.touch ) {
					x = media.position().left;
					media.css({position:"absolute", left: x, top: 0 });
				}
				media.data("w", $(this).width());
				$(".media", overlay).removeClass("preloader");
			});
		} else {
			media.data("w", $("*:first", media).width());
		}
		
		if( Modernizr.touch ) {
			if( $("#videoplayer").length ) {
				media.fadeTo("fast", 1);
				media.data("w", $("object", media).width());
				x = media.position().left;
				media.css({position:"absolute", left: x });
			}
			
			if( !media.data("touch") ) {
				media.data("touch", true );
				media.touchEvents({min_move_x:80});
				media.bind("touchMove", function(e, n, dx, dy){
					if( x != null ) media.filter(":not(:animated)").css("left", x-dx);
				});
				media.bind("touchEnd", function(e){
					var current = media.filter(":not(:animated)");
					if( current.length && current.position().left != x ) {
						current.stop(true, false).animate({left: x}, {duration:"fast"});
					} 
				});
			
				media.bind("touchSwipeLeft", function(e){
					var next = $("#overlay a.arrow.next");
					if( !next.length ) return false;
					media.stop(true, false).animate({left: -media.data("w") - 100}, {duration:"fast", 
						complete: function(){
							next.click();
							$(this).hide();
						}
					});
				});
			
				media.bind("touchSwipeRight", function(e){
					var prev = $("#overlay a.arrow.prev");
					if( !prev.length ) return false;
					media.stop(true, false).animate({left: $(window).width() + 100}, {duration:"fast", 
						complete: function(){
							prev.click();
							$(this).hide();
						}
					});
				});
			}	
		}
		
		overlay.unbind(".overlay").bind("mousemove.overlay", function(){
			var timer = overlay.data("timer");
			$("header, footer", overlay).filter(":not(:visible, :animated)").stop(true, false).fadeIn("fast");
			if(timer) clearTimeout(timer);
			timer = setTimeout(function(){
				$("header, footer", overlay.filter(":not(.infoview)")).filter(":visible").stop(true, false).fadeOut( "fast" );
			}, 3000);
			$("#overlay").data("timer", timer);
		});
		
		var ul = $("ul.thumbnails", overlay),
		last = ul.children("li:last"),
		m = parseInt( last.css("marginRight") ) + parseInt( last.css("marginLeft")),
		ulw = 0;
		
		$("li", ul).each( function(){
			$(this).data("x", ulw < 1 ? 3 : ulw );
			ulw += parseInt( $("img", $(this)).data("width") ) + m;
		})
		ul.width( ulw );
		
		$("a.current", ul).removeClass("current");
		var c = $("a[href="+overlay.data("path")+"]", ul).addClass("current").closest("li");
		
		var findThumbPosition = function() {
			var sw = ul.parent().width();
			if ( sw > ulw ) return;
			var l = -c.data("x") + (sw*.5);
			if( l > 10 ) l = 10;
			else if( l < -ulw+sw ) l = -ulw+sw;
			ul.css("left", l );			
		}
		
		var timer;
		var img = $("img", media);
		$(window).unbind("resize.overlay").bind("resize.overlay", function(){
			if( img.length) {
				img.removeClass("wide");
				if( img.width() > $(window).width() - 100 ) {
					img.addClass("wide");
				}
			}
			overlay.toggleClass("narrow", ($(window).height() < 480 || $(window).width() < 640) );
			if(timer) clearTimeout(timer);
			timer = setTimeout(function(){
				findThumbPosition();
			}, 400 );
		}).trigger("resize.overlay");
		
		$("#entry .info", overlay).unbind(".info").bind("show.info", function(){
			var reset = overlay.hasClass("infoview");
			var info = $(this),
			mediaItem = media.children().first();
			$(".contact a, .related a", info).address();
		
			if( !reset ) {
				overlay.addClass("infoview");
				var w = mediaItem.width(),
				h = mediaItem.height(),
				width = overlay.width() * .5 - 200,
				height = media.height() -100,
				ratio = bestRatio( width, height, w, h ),
				iw = info.width(),
				ih = info.height();

				info.css({position: "absolute", top: ( overlay.height() - ih )*.5 });
				var oh = overlay.height();
				var ow = overlay.width();
				mediaItem.css({ width: ratio*w, height: ratio*h, top: (media.height() - (ratio*h))*.5, position: "relative"});
			}
			
			media.unbind("reset").bind("reset", function(){
				overlay.removeClass("infoview");
				mediaItem.removeAttr("style");
			});
			
			mediaItem.unbind("click").bind("click", function(){
				media.trigger("reset");
			});
			
			
			if( reset )
				media.trigger("reset");
			
			$(window).unbind(".overlayinfo").bind("resize.overlayinfo", function(){	
				if( overlay.is(".infoview") ) $(".info", overlay).trigger("show");
			});
		});
		
		if( overlay.is(".infoview") ) $("#entry .info", overlay).trigger("show");
		
		if( Modernizr.touch ) $(".buttons a").touchEvents();
	
		$(".buttons a").unbind("click").unbind("touchStart").bind( "click touchStart", function( e ){
			var li = $(this).closest("li");
			if( li.hasClass("information") ) {
				$(".info", overlay).trigger("show.info");
			} else if( li.hasClass("favorite") ) {
				li.toggleClass("marked");
				$.get($(this).attr("href"),function(data) {
					$("#favorites ul").html(data);
				});
			} else if( li.hasClass("download") || li.closest("ul").hasClass("social") ) {
				window.open($(this).attr("href"));
			} else if( li.hasClass("mail") ) {
				window.location.href = $(this).attr("href");
			} else if( li.hasClass("share") ) {
				$(".social", overlay).slideToggle("fast");
				$(document).one("click", function(){
					$(".social", overlay).slideUp("fast");
				});
			}
			return false;
		});
		
		$(".social:visible", overlay).slideUp(0);
		
		$(".media img").click( function(){
			$(".hide a", overlay).click();
			return false;
		});
		
		$(document).unbind("keydown").bind("keydown", function( e ) {
			if( overlay.is(":visible") ) {
				switch( e.keyCode ) {
					case 37: //left
						$("#overlay a.prev").click();
						break;
					case 39: //right
						$("#overlay a.next").click();
						break;
					case 27: //esc
						$("#overlay a.close").click();
						return false;
						break;
				}
			}
		});
	}
	
	
	var setupNews = function(){
		var links = $("#news .pagination a, #news h1 a").address();
	}
	if( $("#news").length ){ setupNews(); }
	
	var setupContact = function(){
		if( $("#contact #staff .active").length ) {
			var darkener = $("<div class='darkener'></div>");
			$("#staff li:not(.active)").each( function(){
				$(this).append(darkener.clone());
			});
			$("#contact").click( function(){
				$("#staff li .darkener").fadeOut("fast", function(){
					$(this).remove();
				})
			});
		}
		
		$(window).bind("resize.contact", function(){
			var s = $("#contact");
			if( !s.length ) {
				$(this).unbind("resize.contact");
				return false;
			}
			if( $("#staff .container").length < 3 && $(this).width() > 1300 ) {
				var c = $("#staff .container:last");
				var el = c.clone();
				el.children().filter(":not(:last)").remove();
				$("#staff").append( el );
				c.children(":last").hide();
			} else if( $(this).width() < 1300 ){
				if( $("#staff .container").length >= 3 ) {
					$("#staff .container:last").remove();
					$("#staff .container:last").children().show();
				}
			}
		}).trigger("resize");
		
	}
	
	if( $("#contact").length ){ setupContact(); }
	
	/***************************************
	*  WORLD
	****************************************/
	var setupWorld = function() {
		var markers = {},
		activeMarkers = {},
		radius,
		maxZoom = 16,	
		gmap = new google.maps.Map( $("#map")[0],{
			zoom: 3,
			center: new google.maps.LatLng(60,-50),
			mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'grey'] },
			streetViewControl: true,
			navigationControl: true,
			scaleControl: true,
			mapTypeControl: false,
			scrollwheel: false,
		    navigationControl: true
		});

		var style = [
		  { featureType: "administrative", elementType: "all",
		    stylers: [ { saturation: -100 } ]
		  },{ featureType: "landscape", elementType: "all",
		    stylers: [ { saturation: -100 } ]
		  },{ featureType: "poi", elementType: "all",
		    stylers: [ { saturation: -100 } ]
		  },{ featureType: "road", elementType: "all",
		    stylers: [ { saturation: -100 } ]
		  },{ featureType: "transit", elementType: "all",
		    stylers: [ { saturation: -100 } ]
		  },{ featureType: "water", elementType: "all",
		    stylers: [ { saturation: -100 } ]
		  }
		];

		var styledMapOptions = { name: "grey map" },
		greyMap = new google.maps.StyledMapType(style, styledMapOptions);
		gmap.mapTypes.set('grey', greyMap);
		gmap.setMapTypeId('grey');
		
		function createMarker(person){
			var p = new google.maps.LatLng(person.lat,person.lng),
			ico  = ico = new google.maps.MarkerImage("/images/map-icons/"+person.type+".png",
		      new google.maps.Size(26, 32),
		      new google.maps.Point(0,0),
		      new google.maps.Point(15, 30)
			),
			m = new google.maps.Marker({
				map: gmap,
				position: p,
				title: person.name,
				icon: ico
			});
			google.maps.event.addListener(m,"click",function(){
				var pos = this.getPosition();
				this.getMap().setZoom(12);
				var latLng = new google.maps.LatLng( pos.lat(), pos.lng() - (-.1) );
				this.getMap().panTo( latLng );
				$("#world article").remove();
				var req = $.get("/world",person, function(data){
					data = $(innerShiv(data, false));
					$("h1 a", data).address();
					$("#world form").after(data);
					jQuery("time.timeago").timeago();
					$("a.close", data).click( function(){
						$(this).closest("article").remove();
						return false;
					});
				});
			});
			m.slug = person.slug;
			return m;
		}
		
		var persons = {};
		$("fieldset.people select option").each( function(i,person){
			person = $(person);
			var category = person.data("category");
			if( !category ) { return true; }
			if( !persons[category] ) {
				persons[category] = [];
			}
			var p = { lat: person.data("lat"), lng: person.data("lng"), type: person.data("category"), slug: person.val(), name: person.html() }
			if( p.lat == "0.0" || p.lng == "0.0" ) return true;
			var m = createMarker( p );
			persons[category].push( m );
			activeMarkers[p.slug] = markers[p.slug] = m;
		});
		
		$("fieldset.people select").change( function() {
			var val = $("fieldset.people select").val();
			if( val == "all" ) {
				var box = $("form.nav input[type=checkbox]").filter(":not(:checked)");
				box.click();
				if( !box.length ) $("form.nav input[type=checkbox]:first").change();
			} else {
				google.maps.event.trigger(markers[$("fieldset.people select").val()], "click");
			}
		});
		
		$("form.nav input[type=checkbox]").each( function(){
			var checkbox = $(this).hide(),
			span = $("<span class='checkbox " + $(this).attr("id") + "'></span>").insertAfter( checkbox );
			span.toggleClass("inactive",!$(this).is(":checked"));
			
			if( checkbox.is("#directors-of-photography") ) { span.css("marginLeft", 0); }
			
			span.click( function(){
				if( !checkbox.is(":checked") ) checkbox.attr("checked", "checked");
				else checkbox.removeAttr("checked");
				checkbox.change();
			});
			
		}).change( function(){
			$(this).next( ".checkbox:first" ).toggleClass("inactive", !$(this).is(":checked"));
			var box = $(this)
			$.each(persons[$(this).attr("id")], function(){
				if(box.is(":checked")) {
					this.setMap(gmap)
					activeMarkers[this.slug] = this;
				} else {
					this.setMap(null);
					delete activeMarkers[this.slug];
				}
			});
			
			var b = new google.maps.LatLngBounds();
			$.each(activeMarkers, function(){
				b.extend( this.getPosition() );
			});
			gmap.fitBounds( b );
			if( gmap.getZoom() > 14 ) gmap.setZoom(14);
			
		}).filter(":not(:checked)").each( function(){
			$(this).change();
		});
		
		var b = new google.maps.LatLngBounds();
		$.each(activeMarkers, function(){ b.extend( this.getPosition() ); });
		gmap.fitBounds( b );
		
		
		var filler = $("<div class='filler'></div>");
		$("#social .box").each( function(){
			var html = $(this).html();
			$(this).html( filler.clone().append( html ) );
		});
		
		function resizeBoxes() {
			var layout = 2,
			h = $("<div class='holder group'></div>"),
			boxes = $("#social .box"),
			holder;
			if( $(window).width() > 1600 ) layout = 3;
			if( $("#social .holder:first .box").length != layout  ) {
				$("#social .box").clone(true).each( function( i ){
					if( i % layout == 0 ) holder = h.clone(true);
					holder.append($(this));
					$("#social").append(holder);
					$("h3, h4", $(this)).hide().show();
				});
				if( boxes.parent().is(".holder") ) {
					boxes.parent().remove();
				} else {
					boxes.remove();
				}
			}
			
			$("#social .holder").each( function(){
				$(this).toggleClass("layout-2", layout==2);
				$(this).toggleClass("layout-3", layout==3);
			});
		}
		
		$("#social .box").bind("paging", function(){
			var offset = $(this).data("length"),
			li = $("div:not(.pagination) > ul li", $(this));
			if( li.length > offset && offset > 0 ) {
				if( !$(".pagination", $(this)).length ) {
					var pagination = $("<div class='pagination group'><ul></ul></div>");
					for( var i = 0; i < li.length / offset; i++) {
						var page = $("<li><a href='' title=''><span>Page " + i + "</span></a></li>");
						$("ul", pagination).append( page );
					}
					$(this).append(pagination);
					$("a", pagination).click( function( e ){
						$(this).parent().addClass("active").siblings().removeClass("active");
						$(this).closest(".box").trigger("paging");
						return false;
					}).first().parent().addClass("active");
				}
				var index = $(".pagination ul li.active", $(this)).prevAll().length;
				li.hide().slice( index*offset, (index +1)*offset ).show();
			}
		}).each( function(){
			$(this).trigger("paging");
		})
		
		$("#newsletter form input[type=checkbox]").each(function(){
			$(this).change(function(){
				var str = "";
				$("#newsletter form input[type=checkbox]:checked").each(function(){
					str += $(this).val() + ","
				})
				$("#newsletter form input[name=FormValue_ListID]").val( str );
			})
		})

		$("#social .box .videos a").live("click", function( e ){
			e.preventDefault();
			var r = $(".current", $("#social .box.video"));
			var v = r.clone();
			$("param[name=video]", v).attr("value", $(this).attr("href"));
			$("object",v).attr("data", $(this).attr("href"));
			r.replaceWith( v );
			return false;
		})
		
		var timer;
		$(window).resize( function(){
			if(timer) clearTimeout(timer);
			else { 
				resizeBoxes(); 
			}
			timer = setTimeout(function(){
				$("#map-container").width( $(this).width() );
				$("#map-container").height( $(this).height() );
				resizeBoxes();
			}, 300 );
		}).resize();
	}
	if( $("#map").length ) { setupWorld(); }
	
	/***************************************
	*  ROUTES
	****************************************/
	// Must be defined first to get priority before the routes (so we can skip them when needed...)
	$.address.change(function(e, params){
		if( window.history.pushState && window.location.hash.length > 1 && window.location.hash.indexOf("newsletter") < 0 ) 
			window.location.href = window.location.hash.replace(/\#/g, "");
		
		if( req ) req.abort();
		if( !initialized ) {
			$("body").bind("loaded", function(){
				if( $(window).data("font-loaded") && $("section.content, #overlay").length ) {
					jQuery("time.timeago").timeago();
					req = null;
					$(this).removeClass("preloader").removeClass("loading");
					asideHandling(!$("#world, #overlay").length);
					
					if( $("section").length ) {
						var title = $("section").data("title");
						if( title ) $.address.title(title);
					}
					
					// console.log("LOADED");
					if( $.browser.msie ) {
						$("html a[href*="+window.location.host+"]").each( function(){
							var h = $(this).attr("href");
							$(this).attr("href", h.split(window.location.host).pop());
						});
					}
				}
				$(window).trigger("resize");
			}).trigger("loaded");
			if( e.path != "/" && !window.history.pushState ) {
				initialized = true;			
			}
		} else if( e.path == "/" && !window.history.pushState ) {
			$("body").trigger("loaded");
		}
	});
	
	//HOME, WORLD, CONTACT,NEWS AND CATEGORY
	$.route(["/","/:category/?","/news/:entry/?","/contact/:contact/?"],function(params,href){
		// console.log("in route", href);
		if( !initialized ) {
			initialized = true;
			if( window.history.pushState ) $("body").trigger("loaded");
			return false;
		}

		if( href == "/start" ) href = "/";
		else if( href.indexOf("/contact") > -1 ) href= "/contact";
		
		if( $.address.value().indexOf("?") > -1 ) href = $.address.value();
		var content = $("section.content");
		if( content.data("path") && deUrlify(href) == deUrlify(content.data("path")) ){
			$("body").trigger("loaded");
			$(window).resize();
			return false;
		}
		$("body").addClass("loading");
		req = $.ajax({
			url: href,
			data: {xhr:"true"},
			cache: !$.browser.msie,
			success: function(data){
				$("section.content, section#overlay, #breadcrumb").remove();
				data = $(innerShiv(data, false));

				//Show menu and footer elements if they are set to hidden
				$("body:not(.preloader)").children(":not(#overlay, script):hidden").show();
				$("body.preloader").children(":not(#overlay, script):hidden").css("display", "block");
				
				$("header").after(data);
				
				//Startpage
				if($("#main",data) || data.is("#main")) setupStartpage();
			
				//ARTISTS
				if($("#artists-overview",data).length || data.is("#artists-overview")) setupArtistOverview();
			
				//NEWS
				if($("#news",data).length || data.is("#news")) setupNews();
			
				//SEARCH
				if($("#search_results",data).length || data.is("#search_results")) setupSearchResult();
				
				//CONTACT
				if($("#contact",data).length || data.is("#contact")) {
					$("#contact li[data-slug="+params["contact"]+"]:first").addClass("active");
					setupContact();
				}
				
				//WORLD
				if($("#world",data).length || data.is("#world")) {
					setupWorld();
				}
				
				$("body").trigger("loaded");
			},
			error: function( e ){
				window.location.href = href;
			}
		});
	});
	
	//USER
	$.route(["/:category/:user/?"],function(params,href){
		//Load user if not exists
		if( !$("#artist").length || href.replace(/\/|\s/g, "") != $("#artist").data("path").replace(/\/|\s/g, "")) {
			$("body").addClass("loading");
			$("#preloader").css("display", "block");
			req = $.ajax({
				url: href,
				data: {xhr:"true"},
				cache: !$.browser.msie,
				success: function(data){
					$("section, #breadcrumb").remove();
					data = $(innerShiv(data, false));
					$("header").after(data);
					setupArtist();
					
					$("body").trigger("loaded");
					$("body").children(":visible, :not(#overlay, script)").show();
					$(window).resize();
				},
				error: function(){
					window.location.href = href;
				}
			});
		} else {
			if( $("#overlay").length ) {
				$("#overlay").remove();
			};
			if( $("#case-study").length ) {
				$("#case-study").remove();
				$("#breadcrumb").children().last().remove();
			}
			$("body:not(.preloader)").children(":visible, :not(#overlay, script)").show();
		}
	})
	
	//OVERLAY AND SHOWCASE ROUTE 
	$.route(["/:category/:user/:collection/?", "/:category/:user/:collection/:id/?"],function(params,href){
		var match = false,
		opts = {xhr:"true"};
		if( $("#overlay").length ) match = href.replace(/\/|\s/g, "") == $("#overlay").data("path").replace(/\/|\s/g, "");
		
		if( $("#overlay").length && match ) {
			if( !$("#overlay footer").length ) {
				$.ajax({
					url: "/"+params["category"]+"/"+params["user"]+"/"+params["collection"],
					cache: !$.browser.msie,
					data: $.extend(opts, {thumbnails: true}),
					success: function(thumbs){
						$("#overlay").append(thumbs);
						$("body").trigger("loaded");
						setupOverlay();
					}
				})
			} else {
				$("body").trigger("loaded");
				setupOverlay();
			}
			return false;
		} else if( $("#overlay").length && $("#overlay").data("collection") != params["collection"] ) {
			$("#overlay").remove();
		}
		
		//Hack to force load artist if not exists when visiting a showcase
		
		if( !$("#artist").length ) { $.extend(opts, {artist:true}); }
		
		$("body").addClass("loading");
		req = $.ajax({
			url: href,
			cache: !$.browser.msie,
			data: opts,
			success: function(data){
				$("section.content:not(#artist)").remove();
			
				data = $(innerShiv(data, false));
			
				//Handles artist hack above, places template in correct element
				if( data.is("#case-study") ) {
					$("#case-study, #overlay").remove();
					$("#artist .case-study").before(data.filter("#case-study"));
					$("#breadcrumb").replaceWith(data.filter("#breadcrumb"));
					$("body").trigger("loaded");
					$("html, body").animate({scrollTop: 0}, "fast");
					return false;
				} else if( data.is("#artist") ) {
					$("#case-study, #overlay").remove();
					$("header").after(data);
					setupArtist();
					$("body").trigger("loaded");
					return false;
				}
			
				$("html, body").animate({scrollTop: 0}, "fast");
				
				var media = $(".media .media-entry", data);
				$("img", media).fadeTo(0,0);
				if( !$("#overlay").length ) {
					req = $.ajax({
						url: "/"+params["category"]+"/"+params["user"]+"/"+params["collection"],
						cache: !$.browser.msie,
						data: $.extend(opts, {thumbnails: true}),
						success: function(thumbs){
							data.append(thumbs);
							$("header").after(data);
							setupOverlay();
							$("body").trigger("loaded");
						}
					})
					return false;
				}
				
				$("#overlay").data("path", data.data("path"));
				if( $("header",$("#overlay")).is(":hidden") ) {
					$(".social", data).css("display","none").slideUp(0);
					$("header", data).hide();
				}
				$("header",$("#overlay")).replaceWith($("header", data));
				$("#entry",$("#overlay")).replaceWith($("#entry", data));
				setupOverlay();
			
				$("body").trigger("loaded");
			},
			error: function(){
				window.location.href = href;
			}	
		});
	})
	
	if( $("#overlay").length ){
		$("#overlay .media-entry img").fadeTo(0, 0);
		// setupOverlay();
		$.route.request( window.location.pathname )
	};
})
