/*
 * App Stuff
 */
$(document).ready(function() {

var App = {
	Data: {},
	Controller: {},
	Model: {},
	Collection: {},
	View: {},
	Routes: {},
	Type: {},
	initialize: function() {
		$.ajax({
			url: "json/photos.json",
			dataType: "json",
			success: function(json) {
				App.Data.Main = json;
				new App.Controller.Main;
				Backbone.history.start();
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				console.log(errorThrown);
			}
		});
	}
}
App.initialize();


/*
 * Controllers
 */
App.Controller.Main = Backbone.Router.extend({
    routes: {
        "": "index",
				"/categoria/:category/foto/:file": "foto",
				"/categoria/:category/foto/:file/": "foto",
				"/categoria/:name": "category",
				"/categoria/:name/": "category",
				"/contato": "contato",
				"/contato/": "contato"
    },

		initialize: function() {
			App.Routes.INDEX = 'index';
			App.Routes.CATEGORY = 'category';
			App.Routes.FOTO = 'FOTO';
			App.Routes.CONTATO = 'CONTATO';
			
			_.extend(this, Backbone.Events);
			_.bindAll(this, 'onMainViewNavigate', 'loadSection', 'onMainViewResize');
			
			this.mainModel = new App.Model.Main({categories: new App.Collection.Categories(App.Data.Main.portfolio)});
			this.mainView = new App.View.Main({model: this.mainModel});
			
			this.mainView.bind("mainViewNavigate", this.onMainViewNavigate);
			this.mainView.bind("mainViewResize", this.onMainViewResize);
		},
		
		onMainViewResize: function() {
			this.mainView.render();
			this.sectionView.render();
		},
		
		onMainViewNavigate: function() {
			if (this.mainModel.get('currentSection') === App.Routes.CONTATO) {
				window.history.back();
			} else {
				this.navigate('#/contato/', true);
			}
		},
		
		index: function() {
			this.loadSection(App.Routes.INDEX);
    },

		category: function(name) {
			this.loadSection(App.Routes.CATEGORY, {'name':name});
		},
		
		contato: function() {
			this.loadSection(App.Routes.CONTATO);
		},
		
		foto: function(category, file) {
			this.loadSection(App.Routes.FOTO, {'category':category, 'file': file});
		},
		
		loadSection: function(section, params) {
			this.clearSection();
			
			switch(section) {
				case App.Routes.INDEX:
					this.sectionView = new App.View.Categories({"collection": this.mainModel.get("categories")});
					break;
				case App.Routes.CATEGORY:
					this.sectionView = new App.View.Category({"model": this.mainModel.get("categories").detect(function(cat) { return cat.get("name") === params.name})});
					break;
				case App.Routes.FOTO:
					var categoryObj = this.mainModel.get("categories").detect(function(cat) { return cat.get("name") === params.category });
					var photo = categoryObj.photos.detect(function(photo) { return photo.get("filename") === params.file });
					this.sectionView = new App.View.Foto({model:photo, 'category':params.category});
					break;
				case App.Routes.CONTATO:
					this.sectionView = new App.View.Contato();
					break;
			}
			
			$(this.mainView.el).append(this.sectionView.render().el);
			this.mainModel.set({currentSection:section});
		},
		
		clearSection: function() {
			if (this.sectionView !== undefined) this.sectionView.remove();
		}
});


/*
 * Main Model
 */
App.Model.Main = Backbone.Model.extend({
	url: 'json/photos.json',
	initialize: function() {
	},
	parse: function(response) {
		return {categories: new App.Collection.Categories(response.portfolio)};
	}
});


/*
 * Views
 */
App.View.Main = Backbone.View.extend({
	el: "#container",
	
	initialize: function() {
		_.bindAll(this, 'render', 'onResize');
		
		App.Type.DESKTOP = $(window).width() > 768;
		
		this.model.bind('change', this.render);
		
		window.onresize = this.onResize;
	},
	
	onResize: function(event) {
		console.log($(this.el).width());
		App.Type.DESKTOP = $(window).width() > 768;
		this.trigger("mainViewResize");
	},
	
	events: {
		"click a.contato-btn": "onContatoClick"
	},
	
	onContatoClick: function(event) {
		event.preventDefault();
		this.trigger("mainViewNavigate");
	},
	
	render: function() {
		if (this.model.get('currentSection') === App.Routes.CONTATO) {
			this.$("a.contato-btn").html('fotos');
		} else {
			this.$("a.contato-btn").html('contato');
		}
		
		return this;
	}
});

App.View.Categories = Backbone.View.extend({
	tagName: "section",
	
	id: "categories",
	
	template: _.template($("#categories-template").html()),
	
	initialize: function() {
		_.bindAll(this, 'render', 'resize');
		this.categories = this.collection.models;
	},
	
	resize: function(event) {
		/*var containerWidth = $(this.el).parent().width();
		var itemWidth = this.$('li').width() + 10;
		var rowCount = Math.floor(containerWidth/itemWidth);
		this.$('ul').css('width', (itemWidth * rowCount) + 'px');*/
	},
	
	render: function() {
		var extension = (App.Type.DESKTOP)? '-large.jpg' : '.jpg';
		$(this.el).html(this.template({'extension': extension, categories: this.collection.models}));
		/*_.each(this.$('ul').children(), function(item) {
			var randomDeg = getRandomInt(-4, 4);
			$(item).css({
				'-webkit-transform': 'rotate(' + randomDeg + 'deg)',
				'-moz-transform': 'rotate(' + randomDeg + 'deg)',
			});
		});*/
		return this;
	}
});

App.View.Category = Backbone.View.extend({
	tagName: "section",
	
	id: "category",
	
	template: _.template($("#category-template").html()),
	
	initialize: function() {
		_.bindAll(this, 'render');
	},
	
	render: function() {
		$(this.el).html(this.template(this.model.toJSON()));
		return this;
	}
});

App.View.Contato = Backbone.View.extend({
	tagName: "section",
	
	id: "contato",
	
	template: _.template($("#contato-template").html()),
	
	events: {
		"click #peter": "onPeterClick"
	},
	
	onPeterClick: function(event) {
		event.preventDefault();
		this.$('img').attr('src', 'images/peter.jpg');
	},
	
	initialize: function() {
		_.bindAll(this, 'render', 'onPeterClick');
	},
	
	render: function() {
		$(this.el).html(this.template());
		return this;
	}
});

App.View.Foto = Backbone.View.extend({
	tagName: "section",
	
	id: "foto",
	
	template: _.template($("#foto-template").html()),
	
	initialize: function(options) {
		_.bindAll(this, 'render');
		this.category = options.category;
	},
	
	render: function() {
		$(this.el).html(this.template({category: this.category, filename:this.model.get("filename")}));
		return this;
	}
});


/*
 * Model/Collections
 */
App.Model.Category = Backbone.Model.extend({
	initialize: function() {
		this.photos = new App.Collection.Photos(this.get("photos"));
	}
});
App.Collection.Categories = Backbone.Collection.extend({
  model: App.Model.Category,
	initialize: function() {
	}
});

App.Model.Photo = Backbone.Model.extend({
	initialize: function() {
		//console.log(this.get("filename"));
	}
});
App.Collection.Photos = Backbone.Collection.extend({
  model: App.Model.Photo,
	initialize: function() {
	}
});

});
