var DiS =  {
	init: function() {
		DiS.TopicMarker.markers = DiS.TopicMarker.getAll();
		DiS.TopicMarker.offset = 1244000000 // shorten cookies
		DiS.ReleaseRatings = $H();
		DiS.Preferences.prefs = $H();
		
		Event.observe(window, 'load', function() {
			DiS.UserTooltip.init();
			DiS.Timestamp.init();
			DiS.Ticker.init();
			DiS.ReleaseRating.init();
		});
	},
	Ticker:  {
		init: function() {
			if($('tickers').childElements()[1].down('a')) {
				if(DiS.Preferences.get('enable_ticker')==false) {
					$('tickers').hide();
					return false;
				}
				$('tickers').observe('mouseover', DiS.Ticker.stop)
				$('tickers').observe('mouseout', DiS.Ticker.start)
				this.moveToTop();
				this.start();	
			}
		},
		
		moveToTop: function() {
			$('ticker').style.top='0px';
			$('ticker_title').style.top='0px';
			$('ticker').childElements()[1].down('a').hide();
		},
		
		next: function() {
			titles = $('ticker_title').childElements()
			if(titles[0].childElements()[0].innerHTML != titles[1].childElements()[0].innerHTML) {
				new Effect.Parallel([
					new Effect.Move('ticker',{x:0, y:-20, mode:'absolute'}),
					new Effect.Move('ticker_title',{x:0, y:-20, mode:'absolute'})
				], { 
					duration: 1.5,
					afterFinish:this.bump
				});
			} else {
				new Effect.Move('ticker',{ x:0, y:-20, mode:'absolute',afterFinish:this.bump });
			}
		},

		bump: function() {			
			Element.insert('ticker', {bottom: Element.remove($('ticker').childElements().first())})
			Element.insert('ticker_title', {bottom: Element.remove($('ticker_title').childElements().first())})
			DiS.Ticker.moveToTop();
			DiS.Ticker.effect = new Effect.BlindRight($('ticker'), {afterSetup:DiS.Ticker.reset, duration:2, transition:Effect.Transitions.linear});
		},

		reset: function() {			
			$('ticker').down('li a').show();
		},
		
		start: function() {
			DiS.Ticker.interval = setInterval('DiS.Ticker.next()', 4000);
		},
		
		stop: function() {
			clearInterval(DiS.Ticker.interval)
		}
	},
	
	TopicMarker: {
		set: function(topic_id, timestamp) {
			this.markers.set(topic_id, (timestamp - DiS.TopicMarker.offset))
			Cookie.set('topics', this.markers.toJSON());
		},
		getAll: function() {
			t = Cookie.get('topics');
			return t ? $H(t.evalJSON()) : $H() ;
		},
		get: function(topic_id) {
			result = this.markers.get(topic_id)
			return result ? (result + DiS.TopicMarker.offset) : false
		},
		unset: function(topic_id) {
			this.markers.unset(topic_id)
			Cookie.set('topics', this.markers.toJSON());
		},
		prune: function(before) {
			before = before - DiS.TopicMarker.offset
			this.markers.each(function(marker) {
				if(marker[1] <= before)
					DiS.TopicMarker.unset(marker[0]);
			});
		}
	},
	
	Topic: {
		read: function(topic_id, timestamp) {
			DiS.TopicMarker.set(topic_id, timestamp);
		},
		
		has_read: function(topic_id, timestamp) {
			t = DiS.TopicMarker.get(topic_id)
			return (t && t >= timestamp)
		},
		
		ignore: function(topic_id) {
			if(DiS.TopicMarker.get(topic_id))
				DiS.TopicMarker.unset(topic_id)
		},
		
		indicator: function(topic_id, timestamp) {
			if(DiS.Topic.has_read(topic_id, timestamp)) {
				$('read_topic_'+topic_id).addClassName('read')
			} else {
				DiS.Topic.ignore(topic_id);
				$('read_topic_'+topic_id).addClassName('unread')
			}
		},
		
		tag: function(field, element) {
			artist_id = element.down('.value').innerHTML
			field.value = '';
			DiS.TopicTagging.create(topic_id, artist_id);
		}
	},
	
	Comment: function(comment_id) {
		this.comment_id = comment_id
		this.destroy= function() {
			$('r'+this.comment_id).setOpacity(0.5);
			new Ajax.Request('/comments/'+comment_id, {asynchronous:true, evalScripts:true, method:'delete'});
		}
	},
	
	Reply: function(commentable_id, commentable_type, form_holder, form_element) {
		this.commentable_id = commentable_id
		this.commentable_type = commentable_type
		this.form_element = form_element
		this.form_holder = form_holder
		
		this.open = function() {
			new Effect.BlindDown(this.form_holder)
		}
		
		this.close = function() {
			new Effect.BlindUp(this.form_holder);
		}
		
		this.disable = function() {
			form_element.disable();
		}

		this.enable = function() {
			form_element.enable();
		}

		this.clear =  function() {
			this.enable();
			this.form_element.reset();
		}

		this.to =  function(content_id) {
			$('parent_id').value = content_id;
			this.open()
			if($('r'+content_id)) Element.insert('r'+content_id, this.form_holder);
		}

		this.added = function() {
			this.clear();
			this.close();
		}
		
		this.abandon = function() {
			this.added();
		}
		
		/*
		this.move = function(id, parent_id) {
			c = $(id)
			if($('t'+parent_id)) {
				// we have a thread (ul). Attach at bottom
				Element.insert('t'+parent_id, {after: c });
			} else if($('r'+parent_id)) {
				// we have a leaf to make into a branch.
				x = document.createElement("ul")
				x.id = 't'+parent_id
				Element.insert('r'+parent_id, {bottom: x });
				move_comment(id, parent_id)
			}
		}
		*/
		
	},
	Tab: {
		show: function(group, n) {
			x = $(group).up('.t_holder').down('.tabs').childElements();
			h = $(group).up('.t_header')
			h = (h.down('ul')) ? h.down('ul').childElements() : h.childElements();
			
			x.each(function(t) { t.hide(); });
			h.each(function(t) { t.removeClassName('selected'); });
			h[n].addClassName('selected');
			x[n].show();
		}
	},
	ArtistTagging: {
		update: function(id, params) {
			new Ajax.Request('/artist_taggings/'+id, {
				method: 'put',
				parameters: params,
				onCreate: function() {
					$('updating_'+id).show();
				},
				onSuccess: function(transport) {
					$('updating_'+id).hide();
				}
			});
		},
		setPrimary: function(id) {
			this.update(id, { primary:true });
		},
		destroy: function(id) {
			$('at_'+id).setOpacity(0.5);
			new Ajax.Request('/artist_taggings/'+id, {asynchronous:true, evalScripts:true, method:'delete'});
		},
		create: function(field,element) {
			params = element.down('.value').innerHTML
			params = params.replace(/\&amp;/g,'&');
			DiS.ArtistTagging.clear(field, element);
			new Ajax.Updater('artist_taggings', '/artist_taggings/new?'+params, {insertion:Insertion.Bottom, asynchronous:true, evalScripts:true});
		},
		clear: function(field, element) {
			field.value = '';
		}
	},

	TopicTagging: {
		destroy: function(id) {
			$('at_'+id).setOpacity(0.5);
			new Ajax.Request('/community/tags/'+id, {asynchronous:true, evalScripts:true, method:'delete'});
		},
		create: function(topic_id, artist_id) {
			new Ajax.Updater('artist_tokens', '/community/topics/'+ topic_id +'/tags', {insertion:Insertion.Bottom, asynchronous:true, evalScripts:true, parameters:{artist_id:artist_id}});
			$('no_artists').hide()
		}
	},
	UserTooltip: {
		init: function() {
			if(is_ie)
				return
			var tt_id = 0;
			$$('.comment_author').each(function(x) {
				u = x.rel
				z = "usertooltip"+(tt_id++)
				s = Element.identify(x);
        	
        	
				t = new Tooltip(z, {
				    source:s,
				    content:DiS.UserTooltip.html(u),
				    shadowWidth:0,
					position:"bottom-right",
					positionRatio:0.0,
					offsetTop:0,
					offsetLeft:0,
					events: {
			            onShowEvent: function() {  DiS.UserTooltip.load(this.user, this.id); addActive(this.trigger); },
						onHideEvent: function() {  removeActive(this.trigger) }
        	
			        }
				});
				t.trigger = s
				t.id = z
				t.user = u
			});
		},
		html: function(u) {
			return '<div class="loader user-loader">Loading</div> \
			<ul class="tooltip-list"> \
				<li class="first"><a href="/users/'+u+'">View profile</a></li> \
				<li><a href="/notes/new/to/'+u+'">Send a note</a></li> \
				<li class="moderator"><a href="/users/'+u+'/ban">Ban</a></li> \
			</ul>'
		},
		load: function(user, e) {
			if($(e) && user) {
				if(l = $(e).down('.loader')) {
					l.removeClassName('loader');
					new Ajax.Updater(l, '/users/'+user+'/mini.html', { method:'get' });
				}
			}
		}
	},
	Timestamp: {
		init: function() {
			if(DiS.Preferences.get('enable_relative_time')==false)
				return
			
			$$('.timestamp').each(function(e) {
				if(e.hasClassName('datestamp')) {
					t = DiS.Timestamp.relative_date(e.title)
				} else {
					t = DiS.Timestamp.time_ago_in_words(e.title) 
				}
				if (t) {
					e.update(t.gsub(" ", "&nbsp;"))
					f = new Date();
					f.setTime(e.title * 1000);
					e.title = f
				}
				t = null
			})
		},
		relative_date: function(from) {
			f = new Date();
			f.setTime(from * 1000);
		  	return this.distance_of_time_in_days(new Date(), f)	
		},
		
		time_ago_in_words: function(from) {
			f = new Date();
			f.setTime(from * 1000);
		  	return this.distance_of_time_in_words(new Date(), f)
		},

		distance_of_time_in_words: function(to, from) {
			abbr = false
		  seconds_ago = ((to  - from) / 1000);
		  minutes_ago = Math.floor(seconds_ago / 60);
		  if(minutes_ago <= 0) { return abbr ? ">1m" : "less than a minute ago"; }
		  if(minutes_ago == 1) { return abbr ? "1m" : "a minute ago"; }
		  if(minutes_ago < 45) { return minutes_ago + (abbr ? "m" : " minutes ago"); }
		  if(minutes_ago < 90) { return abbr ? "1h" : "an hour ago"; }
		  hours_ago  = Math.round(minutes_ago / 60);
		  if(minutes_ago < 1440) { return hours_ago + " hours ago"; }
		  if(minutes_ago < 2880) { return "Yesterday at " + from.getHours() + ":" + from.getMinutes(); }
		return false
		},
		distance_of_time_in_days: function(to, from) {
			seconds_ago = ((to  - from) / 1000);
			minutes_ago = Math.floor(seconds_ago / 60);
			days  = Math.round(minutes_ago / 1440);
			if(days == -1) { return "Yesterday"}
		  	
		  	if(days <= 1) { return "Tonight" }
		  	if(days == 2) { return "Tomorrow"}
			return false
		},
		full_distance_of_time_in_words: function(to, from) {
		  days_ago  = Math.round(minutes_ago / 1440);
		  if(minutes_ago < 43200) { return days_ago + " days"; }
		  if(minutes_ago < 86400) { return "1 month"; }
		  months_ago  = Math.round(minutes_ago / 43200);
		  if(minutes_ago < 525960) { return months_ago + " months"; }
		  if(minutes_ago < 1051920) { return "1 year"; }
		  years_ago  = Math.round(minutes_ago / 525960);
		  return "over " + years_ago + " years" 
		}
	},
	Preferences: {
		get: function(p) {
			return DiS.Preferences.prefs.get(p)
		},
		set: function(p) {
			DiS.Preferences.prefs = $H(p)
		}
	},
	Tracker: {
	},
	ReleaseRating: {
		register: function(id, value) {
			DiS.ReleaseRatings.set(id,value)
		},
		init: function() {
			if(DiS.ReleaseRatings.size() > 0) {
				if(logged_in) {
					new Ajax.Request('/release_ratings', { asynchronous:true, evalScripts:true,  parameters:{release_ids: DiS.ReleaseRatings.keys().join("-") }, method:'get'});
				} else {
					DiS.ReleaseRatings.keys().each(function(x) {
						DiS.ReleaseRating.update(x, null)
					})
				
				}
			}
		},
		rate: function(release_id, e) {
			new Ajax.Request('/release_ratings', { asynchronous:true, evalScripts:true,  parameters:{release_id:release_id, rating: e.value }});
		},
		set: function(ratings) {
			
			ratings = $H(ratings)
			ratings.each(function(r) {
				DiS.ReleaseRating.update(r[0], r[1])
			})
		},
		reset: function(e) {
			rated = Element.up(e, '.rated')
			x = Element.up(e, '.release_rating')
			unrated = Element.down(x, '.unrated')
			Element.hide(rated);
			Element.show(unrated);
			},
		update: function(release_id, rating) {
			$$('.release_rating_'+release_id).each(function(e) {
				Element.down(e, '.rating_loading').hide()
				Element.down(e, '.unrated').hide()
				
				if(rating==null) {
					Element.down(e, '.unrated').show()
				} else {
					Element.down(e,'.rated').show()
					Element.down(e,'.rating_holder').update(rating)
					Element.down(e,'.rating_select').selectedIndex = 11-rating
				}
			})
		}
	},
	drown: function() {
		new Effect.Parallel([
			new Effect.Move('drowning_man',{x:0, y:50, mode:'relative'}),
			new Effect.Fade("drowning_man"),
			new Effect.Move('oh_hai_img',{x:0, y:50, mode:'relative'}),
			new Effect.Fade("oh_hai_img")
		], { 
			duration: 1.5
		});
	},
	oh_hai: function() {
		new Effect.Parallel([
			new Effect.Move('oh_hai_img',{x:0, y:-20, mode:'relative'}),
			new Effect.Appear("oh_hai_img"),
		], { 
			duration: 1.0
		});
		$('drowning_man').onclick =function() { DiS.drown(); }
	}
};



DiS.init();






