var app = window.app = (function(app){
	app.fb_share = function (params){
		FB.ui(
			{
				method: 'feed',
				name: params.name,				
				link: params.link,
				picture: params.picture,
				source: params.source,
				type: params.type,
			},
			app.fb_ui_callback
		);
	};
	app.fb_send = function (params){
		FB.ui(
			{
				method: 'send',
				name: params.name,				
				link: params.link,
				// message: params.message,
				// picture: params.picture,
				// source: params.source,
				// type: params.type,
				// caption: params.caption,
				// description: params.description
			},
			app.fb_ui_callback
		);
	};
	app.fb_login = function (){
		FB.login(app.fb_ui_callback,{scope: 'email,publish_stream,publish_actions'});
	}
	app.fb_logout = function (){
		FB.logout();
	}
	app.fb_ui_callback = function (response) {
		if(window.console) console.log("fb_ui_callback",response);
		// if( response && response!==undefined && response.status === "unknown" ){
		// 	app.userView.idle();
		// }
	}
	app.fb_init = function (){
	  window.fbAsyncInit = function() {
			FB.init({
				appId  : fb_app_id,
				channelURL : 'http://voox.me/assets/js/channel.html', // channel.html file
				status     : true, // check login status
		    cookie     : true, // enable cookies to allow the server to access the session
		    oauth      : true, // enable OAuth 2.0
		    xfbml      : true  // parse XFBML
			});
			FB.Event.subscribe('auth.statusChange', function(response) {
				console.log("auth.statusChange",response);
				switch(response.status){
					case 'connected':
						FB.api("/me",function(me){
							if(me.id){
								$.post("/login", {user: me, auth: response.authResponse}, function(signedUser){
									if( signedUser!=null && signedUser.id ){
										app.user = new app.UserView({model:new Backbone.Model(signedUser)}).render();
									}else{
										// SHE IS NOT ALPHA USER
									}
									app.open();
								}, "json");
							}
						});
					break;
					case 'unknown':
						location.href="/logout";
					break;
				}
			});	
			FB.getLoginStatus(function(response) {
				console.log("getLoginStatus",response);
				if(response.authResponse===null){
					app.open();
				}
			});
			$("#btn_login").click(app.fb_login);
		};
	  // Load the SDK Asynchronously
	  (function(d){
	     var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
	     js = d.createElement('script'); js.id = id; js.async = true;
	     js.src = "//connect.facebook.net/en_US/all.js";
	     d.getElementsByTagName('head')[0].appendChild(js);
	   }(document));
	};
	app.soundManagerInit = function() {
		soundManager.useFlashBlock = true;
		soundManager.url = '../assets/swf/';
		soundManager.flashVersion = 9;
	};
	app.backboneInit = function() {
		
		var autoSyncId = app.autoSyncId = 0;
		var getVoxOrStreamById = app.getVoxOrStreamById = function( id ){
			var vox_or_stream = app.feed.collection.get(id);
			if( typeof vox_or_stream==="undefined" && typeof app.vox!=="undefined" && app.vox.id == id ){ vox_or_stream = app.vox; }
			if( typeof vox_or_stream==="undefined" && typeof app.stream!=="undefined" && app.stream.id == id ){ vox_or_stream = app.stream; }			
			return vox_or_stream;
		}
		
		app.PageView = Backbone.View.extend({

			slug: "",

			el: "#pages",

			initialize: function( slug ){
				this.slug = slug;
			},

			render: function() {
				if (this.slug) {
		    	$(this.el).html(_.template($('#page_' + this.slug + '_view').html()));
				}
		    return this;
		  },		

		});
		
		app.UserView = Backbone.View.extend({

			template: _.template($("#user_view").html()),

		  el: "#user",

			events: {
	      'click #btn_logout': 'logout',
	    },

			initialize: function(){
				$.ajaxPrefilter( function( options ) {
					options.url += (options.url.indexOf("?")>-1 ? "&" : "?") + "auth_token=" + app.user.model.get('auth_token');					
				});
			},

		  render: function() {
				$(this.el).html(this.template(this.model.toJSON()));
		    return this;
		  },

			logout: function() {
				app.fb_logout();
			},		

		});
		
		var Vox = app.Vox = Backbone.Model.extend({
			urlRoot: "/voxes",
		});
		
		var Voxes = app.Voxes = Backbone.Collection.extend({
			model: Vox,
			url: "/voxes",
			comparator : app.collComp
		});
		
		var VoxerView = app.VoxerView = Backbone.View.extend({

			template: _.template($("#voxer_view").html()),

			el: "#voxer",

			events: {
	      'click #publisher > #btn_publish_start': 'publishStart',
	      'click #publisher > #btn_publish_stop': 'publishStop',				
	      'click #recorder > #btn_record_start': 'recordStart',
	      'click #recorder > #btn_record_stop': 'recordStop',
	      'click #recorder > #btn_record_publish': 'recordPublish',
	      'click #recorder > #btn_record_listen': 'recordListen',
	      'click #recorder > #btn_record_delete': 'recordDelete',
	      'change #recorder > #record_settings > #record_effects': 'recordCompose',
	      'change #recorder > #record_settings > #record_backgrounds': 'recordCompose',
	    },

			initialize: function(params) {
				this.after_render = params.after_render;
				if (!app.isMobile) {

					if ( vc.isInited != true ){
						vc.init({
							debug:false,
							mic_feed:true,
							user_id:app.user.model.id,
							auth_token:app.user.model.get('auth_token'),
							autoConnect:true,
							onInit:this.onVc
						});
					}else{
						vc.args.user_id=app.user.model.id;
						vc.args.auth_token=app.user.model.get('auth_token');
					}

				}
			},

			render: function() {
				if( !app.isMobile ){
					$(this.el).html(this.template());
					this.busy();
				}
				if( window.vox.id!==undefined ){
					this.$("#publisher").remove();
				}
				this.after_render();
		    return this;
		  },

			onVc: function() {

				vc.addEventListener("All",function(e){
					if(e.type!=="Api.Mic.Activity"){
						app.voxer.onChangeStatus();	
					}
				});
				
				vc.addEventListener("Api.Mic.Activity",function(e){
									if(vc.args.status=="recording") {
				
										$("#btn_record_stop").css({
											"-moz-transform":"scale("+(1+Number(e.data/100))+")",
											"-webkit-transform":"scale("+(1+Number(e.data/100))+")",							
											"transform":"scale("+(1+Number(e.data/100))+")",							
										});
									}else{
										$("#btn_publish_stop").css({
											"-moz-transform":"scale("+(1+Number(e.data/100))+")",
											"-webkit-transform":"scale("+(1+Number(e.data/100))+")",							
											"transform":"scale("+(1+Number(e.data/100))+")",							
										});
									}
								});
				
				app.voxer.render();

			},

			onChangeStatus: function() {
				console.log(vc.args.status)
				switch( vc.args.status ){
					case "stand_by":
						this.$("#btn_publish_stop").hide();					
						this.$("#btn_record_start").show();
						this.$("#btn_record_stop").hide();
						this.$("#btn_record_publish").hide();
						this.$("#btn_record_listen").hide();
						this.$("#btn_record_delete").hide();
						this.$("#record_settings").hide();				
					break;
					case "connected": 
					case "deleted":
						this.$("#publisher").show();
						this.$("#btn_record_start").show();
						this.$("#btn_record_stop").hide();
						this.$("#btn_record_publish").hide();
						this.$("#btn_record_listen").hide();
						this.$("#btn_record_delete").hide();
						this.$("#record_settings").hide();
						if ( vc.args.parent_id != null){
							var m = app.getVoxOrStreamById(vc.args.parent_id);
							//TODO MAKE MORE OOP TOOLTIP WITH CLOSE BUTTON
							this.$("#tooltip").show().text("Click to record button for revoxing (replying) " + m.attributes.user.name + "'s " + m.attributes.name );
						}else{
							this.$("#tooltip").hide();
						}				
					break;
					case "recording":
						this.$("#publisher").hide();
						this.$("#btn_record_start").hide();
						this.$("#btn_record_stop").show();
						this.$("#btn_record_publish").hide();
						this.$("#btn_record_listen").hide();
						this.$("#btn_record_delete").hide();
						this.$("#record_settings").hide();
					break;
					case "converted":
						this.$("#publisher").hide();					
						this.$("#btn_record_start").hide();
						this.$("#btn_record_stop").hide();
						this.$("#btn_record_publish").show();
						this.$("#btn_record_listen").show();
						this.$("#btn_record_delete").show();
						this.$("#record_settings").show();
					break;
					case "publishing":
						this.$("#btn_publish_start").hide();
						this.$("#btn_publish_stop").show();
					break;
					case "published":
						this.$("#publish_settings").show();
						this.$("#btn_publish_start").show();
						this.$("#btn_publish_stop").hide();
					break;
					case "publish_saved":
						this.$("#publish_settings").hide();
						var published_stream = app.feed.streams.get(vc.args.live_stream);
						if(published_stream===undefined){
							published_stream = app.feed.streams.create({
								id: vc.args.live_stream,
								public: this.$("#publish_public").is(":checked") ? 1 : 0,								
								user: {id:app.user.model.id, name: app.user.model.get('name')},
								fresh: true,
							},{at: 0});
						}else{
							published_stream.save({
								id: vc.args.live_stream,
								public: this.$("#publish_public").is(":checked") ? 1 : 0
							});
						}
					break;
				}
				
				$("#btn_record_stop").css({
					"-moz-transform":"scale(1)",
					"-webkit-transform":"scale(1)",							
					"transform":"scale(1)",							
				});
						
				// if( app.vox!==undefined){
				// 					app.vox.fetch({success:function(model){
				// 						model.view.render();
				// 					}});
				// 				}
				this.idle();							
			},

			publishStart: function() {
				this.$("#recorder").hide();
				vc.api.publish();
			},

			publishStop: function() {
				this.$("#recorder").show();
				var published_stream = app.feed.streams.get(vc.args.live_stream);
				app.feed.streams.remove(published_stream);
				vc.api.stop(true);
			},
			
			recordStart: function() {
				this.busy();
				vc.api.record();
			},

			recordStop: function() {
				this.busy();			
				vc.api.stop();	
			},

			recordCompose: function() {
				this.busy();			
				vc.api.compose( this.$('#record_effects').val(), this.$('#record_backgrounds').val() );
			},

			recordPublish: function() {
				this.$("#tooltip").hide();				
				var edited_vox = app.feed.voxes.get(vc.args.current_vox.id);
				if(edited_vox===undefined){
					app.feed.voxes.create({
						id: vc.args.current_vox.id,
						active: 1,
						public: this.$("#record_public").is(":checked") ? 1 : 0,
						user: {id:app.user.model.id, name: app.user.model.get('name')},
						fresh: true,
					},{at: 0});
				}else{
					edited_vox.save({
						id: vc.args.current_vox.id,
						active: 1,
						public: this.$("#record_public").is(":checked") ? 1 : 0
					});
				}
				
				vc.args.current_vox = null;
				vc.args.stream = null;						
				vc.args.status = "connected";
				this.onChangeStatus();
			},	

			recordListen: function() {
				this.createSound(true);
			},

			recordDelete: function() {
				this.busy();			
				vc.api.delete();
			},

			recordRevox: function( id ) {
				vc.args.parent_id = vc.args.parent_id == id ? null : id;
				this.onChangeStatus();
			},

			recordEdit: function( model ){
				this.$("#tooltip").show().text("editing " + model.attributes.name + " #" + model.id );
				vc.api.set_current_vox( model.toJSON() );
				vc.args.status = "converted";
				this.onChangeStatus();
			},

			createSound: function( autoPlay ) {
				this.destroySound();
				vc.args.sound = soundManager.createSound({
					id:'vcSound',
					url:vc.args.storage + "/audio/users" + vc.args.current_vox.path + "/" + ( vc.args.current_vox.vox || vc.args.current_vox.voice ),
				});
				if(autoPlay===true) {
					vc.args.sound.play();				
				}
			},	

			destroySound: function() {
				if( typeof vc.args.sound !== 'undefined' ) { vc.args.sound.destruct(); }
			},
			
			busy: function(){
				this.$(".busy").show();
			},

			idle: function(){
				this.$(".busy").hide();
			}

		});
		
		var FeedView = app.FeedView = Backbone.View.extend({

			el: "#feed",

			events: {
	      "click .load_more": "more",
	    },

			initialize: function( type, user_id ){
				this.type = type;
				this.user_id = user_id;
				this.voxes = new Voxes();
				this.streams = new Streams();
				this.collection = type=="voxes" ? this.voxes : this.streams;
				var feed = this.collection;
				feed.bind("reset", this.render, this);
				feed.bind("add", this.render, this);				
				// feed.bind("add", this.addItem, this);			
				feed.bind("remove", this.removeItem, this);			
				feed.bind("change", this.updateItem, this);	

				var data = this.buildQuery( {user_id:user_id,parent_id:window.vox.id} );
				feed.fetch({data:data});

				this.start();
				this.$(".load_more").show();
			},

			buildQuery: function( params ){
				var data = {"conditions":{}};

				if ( typeof params.user_id !=="undefined" ){
					data["conditions"]["user_id eq ?"] = params.user_id;
				}
				if ( typeof params.since !=="undefined" ){
					data["conditions"]["created_at > '?'"] = params.since;
				}			
				if ( typeof params.from !=="undefined" ){
					data["conditions"]["created_at < '?'"] = params.from;
				}			
				if( this.type === "voxes") {
					
					if ( typeof params.parent_id !=="undefined" ){
						data["conditions"]["parent_id eq ?"] = params.parent_id;
					}
				}
				data["include"] = "user";
				return data;
			},

			render: function() {
				var self = this;
				this.$("#"+this.type).html(this.collection.map(function(vox_or_stream){
					vox_or_stream.view = self.type==="voxes" ? new VoxView({model: vox_or_stream}).render() : new StreamView({model: vox_or_stream}).render();
					return vox_or_stream.view.el;
				}));


				this.$("section").hide();
				this.$("#"+this.type).show();
				this.$(".load_more").show();

				return this;
			},

			// addItem: function(model){
			// 	model.view = this.type==="voxes" ? new VoxView({model: model}).render() : new StreamView({model: model}).render();
			// 	if ( model.get('fresh')===true ){
			// 		model.set({'fresh':null});
			// 		this.$("#"+this.type).prepend(model.view.el);
			// 	}else{
			// 		this.$("#"+this.type).append(model.view.el);
			// 	}
			// 
			// },
			
			removeItem: function(model){
				if(model.view!==undefined){
					model.view.remove();
				}
				model.destroy();
			},

			updateItem: function(model){
				if(model.view!==undefined){
					model.view.render();
				}
			},

			start: function(){
				clearInterval(app.autoSyncId);
				var self = this;
				app.autoSyncId = setInterval(function(){
					self.load();
				},10000);
			},

			stop: function(){
				clearInterval(this.autoSyncId);
			},

			load: function(){
				var feed = this.collection;
				var user_id = this.user_id;
				var type = this.type;
				var since = feed.first() ? feed.first().attributes.created_at : null;
				var data = this.buildQuery({user_id: user_id, parent_id: window.vox.id, since: since});
				feed.fetch({data: data, add: true});
			},

			more: function(){
				var feed = this.collection;
				var from = feed.last()!==undefined ? feed.last().attributes.created_at : null;
				var data = this.buildQuery({user_id:this.user_id,parent_id:window.vox.id,from:from});
				feed.fetch({data: data, add:true, success:function(model,collection){
					if (collection.length==0){
						this.$(".load_more").hide();
					}
				}} );
			}

		});
		
		
		
		var Stream = app.Stream = Backbone.Model.extend({
			urlRoot: "/streams",
		});
		
		var Streams = app.Streams = Backbone.Collection.extend({
			model: Stream,
			url: "/streams",
			comparator : app.collComp
		});
		
		var StreamView = app.StreamView = Backbone.View.extend({

			template: _.template($("#stream_view").html()),

			tagName: "article",
			
			className: "feed_item",

			events: {
	      "click .play": "play",
	      "click .share": "fb_share",
	      "click .send": "fb_send",
	      "click .private": "private",
	      "click .public": "public",
	      "click .delete": "delete",	
	    },


			initialize: function(){
			},

			render: function() {
				$(this.el).html(this.template(this.model.toJSON()));
				return this;
			},

			play: function() {

				app.feed.stop();

				var sound;

				if( typeof this.model.get('sound')!=="undefined" ){
					sound = this.model.get('sound');
					sound.togglePause();
				}else{
					try{
					sound = soundManager.createSound({
						id: this.model.id,
						serverURL: vc.args.rtmp + "/" + this.model.get('user').id,
					  url: this.model.id,
						onconnect: this.onConnect,
						onplay:this.onPlay,
						onstop:this.onStop,
						onpause:this.onPause,
						onresume:this.onResume,
						onfinish:this.onFinish
					});
					this.model.set({'sound':sound});				
					sound.play();				
					}catch(e){
						console.log(e)
					}
				}

				if( typeof app.lastSound!=="undefined" && app.lastSound!==this ){
					app.lastSound.stop();
				}

				app.lastSound = this;
				
				return false;
			},

			stop: function() {
				soundManager.stop(this.model.id);
		    if (!app.isMobile) { // iOS 4.2+ security blocks onfinish() -> playNext() if we set a .src in-between(?)
		      soundManager.unload(this.model.id);
		    }
			},

			onConnect: function(){
				
			},
			
			onPlay: function(){
				// var m = app.getVoxOrStreamById(this.sID);				
				// var v = m.view;
				// if ( m === app.vox || m === app.stream){
				// 	$(".master article").addClass('playing').find(".play").text("5");
				// }else{
				// 	v.$('.play').text("5");
				// 	$(v.el).addClass('playing');
				// }
				var v = app.getVoxOrStreamById(this.sID).view;				
				v.$('.play').text("5");
				$(v.el).addClass('playing');
			},

			onStop: function(){
				var v = app.getVoxOrStreamById(this.sID).view;
				v.$('.play').text("4");			
				$(v.el).removeClass('playing');				
				app.feed.start();
			},

			onPause: function(){
				app.getVoxOrStreamById(this.sID).view.$('.play').text("4");			
			},

			onResume: function(){
				app.getVoxOrStreamById(this.sID).view.$('.play').text("5");			
			},

			onFinish: function(){
				var v = app.getVoxOrStreamById(this.sID).view;				
				v.$('.play').text("4");			
				$(v.el).removeClass('playing');								
				app.feed.start();
			},
			
			fb_share: function(){
				app.fb_share({
					name: this.model.attributes.name + " by " + this.model.attributes.user.name,
					link: "http://voox.me/play/"+this.model.id,
					picture: "http://voox.me/assets/img/logo-64.png",
					source: "http://voox.me/assets/swf/player_mp3.swf?mp3="+this.model.attributes.href,
					type: "video"
				});
			},

			fb_send: function(){
				app.fb_send({
					name: this.model.attributes.name + " by " + this.model.attributes.user.name,
					link: "http://voox.me/play/"+this.model.id
				});
			},

			private: function(){
				this.model.save({public:0});
			},

			public: function(){
				this.model.save({public:1});			
			},

			delete: function(){
				var answer = confirm("Are you sure to stop publishing?");
				if(answer){
					vc.api.stop(true);
					if(this.model!==app.vox){
						app.feed.collection.remove(this.model);
					}else{
						this.model.destroy();
					}
				}
			},
		});
		
		var VoxView = app.VoxView = StreamView.extend({

			template: _.template($("#vox_view").html()),

			events: {
	      "dblclick .name": "rename",			
	      "click .play": "play",
	      "click .share": "fb_share",
	      "click .send": "fb_send",
	      "click .revox": "revox",
	      "click .private": "private",
	      "click .public": "public",
	      "click .edit": "edit",
	      "click .delete": "delete",
	    },

			play: function() {
				app.feed.stop();

				var sound;

				if( typeof this.model.get('sound')!=="undefined" ){
					sound = this.model.get('sound');
					sound.togglePause();
				}else{
					sound = soundManager.createSound({
						id: this.model.id,
						url: this.model.get('href'),
						onplay:this.onPlay,
						onstop:this.onStop,
						onpause:this.onPause,
						onresume:this.onResume,
						onfinish:this.onFinish
					});
					this.model.set({'sound':sound});				
					sound.play();				
				}

				if( typeof app.lastSound!=="undefined" && app.lastSound!==this ){
					app.lastSound.stop();
				}

				app.lastSound = this;

				return false;
			},

			revox: function(e){
				$(".revoxing").removeClass("revoxing");
				$(e.currentTarget).parent().parent("article").toggleClass("revoxing");
				app.voxer.recordRevox(this.model.id);
			},

			rename: function() {
				app.feed.stop();
				if(this.model.attributes.user.id==app.user.model.id){
					var self = this;
					this.$("strong").hide();
					this.$("input").val(self.$("strong").text());					
					this.$("input").show().unbind().blur(function(){
						if($(this).val()!==""){
							self.model.save({name: $(this).val()});
						}
						app.feed.start();
						$(this).hide();
						self.$("strong").show();
					});
				}
			},

			edit: function(){
				if( app.voxer && vc && vc.isInited ){
					app.voxer.recordEdit( this.model );
				}
			},	
			
			delete: function(){
				var answer = confirm("Are you sure to delete "+this.model.get("name")+"?");
				if(answer){
					if(this.model!==app.vox){
						app.feed.collection.remove(this.model);
					}else{
						this.model.destroy();
					}
				}
			},

		});
		
		window.router = new Router();
		Backbone.history.start();
		
		if( typeof window.vox.id !== "undefined") { 
			$("#logo").click(function(){
				location.href = "/";
				return false;
			});
		}
	};
	app.init = function() {

		app.isMobile = navigator.userAgent.match(/ipad|ipad|iphone/i);

		app.soundManagerInit();

		app.backboneInit();

		app.fb_init();
	};
	app.open = function() {
		if(app.user!==undefined){
			app.voxer = new app.VoxerView({after_render:function() {$("#container").show();}});
		}

		if(app.feed===undefined) { 
			app.feed = new app.FeedView( "voxes" ); 
		}else{
			app.feed.render();
		}
		
		if( typeof window.vox.id!== "undefined" && typeof app.vox === "undefined") {
			var vox = app.vox = new app.Vox(window.vox);
			vox.view = new app.VoxView({model: vox}).render();
			vox.bind('change',function(model){
				model.view.render().$(".revox, .go").remove();
			}).bind('destroy',function(){
				location.href="/";
			});
			$("nav.main").wrap( $("<div class=\"master\"/>").html(vox.view.el) ).remove();
			vox.view.el = $(".master article")[0];
			vox.view.$(".revox, .go").remove();			
			app.voxer.recordRevox(vox.id);
		}
		
		if( typeof window.stream.id!== "undefined" && typeof app.stream === "undefined") {
			var stream = app.stream = new app.Stream(window.stream);
			stream.view = new app.StreamView({model: stream}).render();
			stream.bind('change',function(model){
				model.view.render().$(".go").remove();
			}).bind('destroy',function(){
				location.href="/";
			});
			$("nav.main").wrap( $("<div class=\"master\"/>").html(stream.view.el) ).remove();
			stream.view.el = $(".master article")[0];			
			stream.view.$(".go").remove();						
			$("#voxer, #streams, #voxes, .load_more").remove();
		}
		
		if(app.user===undefined){
			$("#container").show();
		}
		
	}
	app.now = function() {
		function printDate() {
		    var temp = new Date();
		    var dateStr = padStr(temp.getFullYear()) + "-" +
		                  padStr(1 + temp.getMonth()) + "-" +
		                  padStr(temp.getDate()) + " " +
		                  padStr(temp.getHours()) + ":" +
		                  padStr(temp.getMinutes()) + ":" +
		                  padStr(temp.getSeconds());
				return dateStr;
		}

		function padStr(i) {
		    return (i < 10) ? "0" + i : "" + i;
		}
		return printDate();
	}	
	app.collComp = function(s) {
		var n = new Date();
		var d = new Date(s.get('time'));
	  return (n-d);
	}
	return app;
})(app || {});

$(document).ready(app.init);
