(function(){
	var supportCanvas = 'getContext' in document.createElement('canvas');
	var galleries = {};

	var Photo = Backbone.Model.extend({});
	var Gallery = Backbone.Collection.extend({
		model: Photo,
		initialize: function(models, options) {
			this.name = options.name;
		},

		url: function() {
			return "/galleries/" + this.name + "/";
		}
	});

	var PhotoView = Backbone.View.extend({
		className: "photo",

		template: _.template($("#photo-template").html()),
		
		initialize: function(photo, gallery) {
			var self = this;
			this.gallery = gallery;
			this.photo = photo;
			this.img = new Image();
			this.img.onload = function(){ self.trigger('loaded'); };
			this.img.onerror = function(){ self.trigger('error'); };
			this.img.src = photo.get('image');
		},

		render: function() {
			$(this.el).html(this.template({
				index: this.gallery.indexOf(this.photo) + 1,
				total: this.gallery.length,
				photo: this.photo,
				shareUrl: escape("http://www.inzajeano.com/gallery/" + this.photo.get("gallery") + "/" + this.photo.get("id"))
			}));
		}
	});

	var GalleryView = Backbone.View.extend({
		el: $("#main"),
		
		events: {
			"click .first": "first",
			"click .last": "last",
			"click .next": "next",
			"click .previous": "previous"
		},

		setGallery: function(gallery, photo) {
			var i;
			this.gallery = gallery;
			if(photo) {
				this.setPhoto(photo);
			} else {
				this.setIndex(0);
			}
		},

		next: function(){
			this.setIndex(this.gallery.currentIndex+1);
		},

		previous: function(){
			this.setIndex(this.gallery.currentIndex-1);
		},

		first: function(){
			this.setIndex(0);
		},

		last: function(){
			this.setIndex(this.gallery.length-1);
		},

		setPhoto: function(photo) {
			var self = this, view = new PhotoView(photo, this.gallery);
			self.$(".loading").fadeIn(100);
			view.bind('loaded', function(){
				view.render();
				self.$(".loading").fadeOut(100);
				self.$(".gallery")
					.fadeOut(100, function(){
						self.$(".gallery").html(view.el).fadeIn(100);
						self.gallery.currentIndex = self.gallery.indexOf(photo);
						console.log(self.$(".previous, .next"));
						self.$(".previous, .next, .first, .last").removeClass("disabled");
						if(self.gallery.currentIndex === 0) {
							self.$(".previous, .first").addClass("disabled");
						}
						if(self.gallery.currentIndex === self.gallery.length-1) {
							self.$(".next, .last").addClass("disabled");
						}
					});
			});
			view.bind('error', function(){
				//self.setIndex(0);
			});
			
		},

		setIndex: function(index) {
			if(index < 0 || index >= this.gallery.length) {
				return;
			}
			var photo = this.gallery.at(index);
			app_router.navigate("/gallery/" + this.gallery.name + "/" + photo.get("id"), true);
		}
	});

	var Router = Backbone.Router.extend({
		routes: {
			"/contact": "contact",
			"/about": "about",
			"/gallery/:name": "gallery",
			"/gallery/:name/:photo": "gallery"
		},

		contact: function(){
			$("nav .active").removeClass("active");
			$("nav li a[href='/contact']").closest("li").addClass("active");
			$("#contact, #about, #main").filter(":visible").fadeOut(100, function(){
				window._gaq.push(['_trackPageview', '/'+Backbone.history.getFragment()]);
				document.title = "Inzajeano Latif - Contact";
				$("#contact").hide().fadeIn(100);
			});
		},

		about: function(){
			$("nav .active").removeClass("active");
			$("nav li a[href='/about']").closest("li").addClass("active");
			$("#contact, #about, #main").filter(":visible").fadeOut(100, function(){
				window._gaq.push(['_trackPageview', '/'+Backbone.history.getFragment()]);
				document.title = "Inzajeano Latif - About";
				$("#about").hide().fadeIn(100);
			});
		},

		gallery: function(name, photo){
			var gallery = galleries[name];
			var navigate = function(){
				$("nav .active").removeClass("active");
				$("nav li a[href='/gallery/"+name+"/']").closest("li").addClass("active");
				photo = photo ? gallery.get(photo) : gallery.at(gallery.currentIndex || 0);
				app_router.navigate("/gallery/" + name + "/" + photo.get("id"));
				document.title = "Inzajeano Latif - " + photo.get("title");
				window._gaq.push(['_trackPageview', '/'+Backbone.history.getFragment()]);
				gallery_view.setGallery(gallery, photo);
				if(!$("#main").is(":visible")) {
					$("#contact, #about").filter(":visible").fadeOut(50, function(){
						$("#main").fadeIn(100);
					});
				}
			};
			if(gallery) {
				navigate();
			} else {
				gallery = galleries[name] = new Gallery([], {name: name});
				gallery.bind('all', navigate);
				gallery.fetch();
			}
		}
	});

	var gallery_view = new GalleryView();
	var app_router = new Router();
	Backbone.history.start({pushState: true});
	// Backbone.history.start();
	var fragment = Backbone.history.getFragment();
	if(fragment === '') {
		fragment = '/gallery/people';
	} else {
		fragment = "/" + fragment;
	}
	Backbone.history.navigate(fragment, true);
	$("nav a[href|='"+fragment+"']").closest("li").addClass("active");

	// Add listeners to nav links to ensure the page doesn't reload
	$("nav a").click(function(){
		if(!($(this).attr("href").indexOf("http://")===0)) {
			Backbone.history.navigate($(this).attr("href"), true);
			return false;
		}
	});

	// add left/right arrow key functionality
	$(document).keydown(function(event){
		if(!$(gallery_view.el).is(":visible")) {
			return;
		}
		if(event.keyCode === 39) {
			gallery_view.next();
		} else if(event.keyCode == 37) {
			gallery_view.previous();
		}
	});

	$(document).delegate(".share a","click", function(){
		var href = $(this).attr("href"),
			dimensions = $(this).data("share") || {},
			width = dimensions.width || 450,
			height = dimensions.height || 300;
		_gaq.push(["_trackSocial", $(this).attr("class").substring(6), "share", href]);
		if(href.indexOf("mailto:") !== 0) {
			window.open(href, 'inzshare', 
				'width='+width+',height='+height+
				',left='+((screen.availWidth-width)/2)+',top='+((screen.availHeight-height)/2));
			return false;
		}
	});

	$("#contactForm").submit(function(){
		var data = $("#contactForm").serialize();
		$("#contactForm").find("input, textarea").attr("disabled", true);
		$.post("/contact", data, function(response){
			$("#contactForm").find("input, textarea").attr("disabled", false);
			// TODO: some kind of feedback popup here
		});
		return false;
	});

})();
