var jf,
	Tracking;

function interpolate(amount, begin, end) {
	return begin + (end - begin) * amount;
}

function onYouTubePlayerReady(id) {
	jf.onYouTubeInit(id);
}

function onSerenadePlayerReady() {
	jf.onSerenadePlayerInit();
}

function onVideoSelected(id) {
	jf.setPage('/serenades/' + id);
}

var Tween = new Class({
	Extends: Fx,
	initialize: function (begin, end, duration, ease) {
		this.parent({
			duration: duration,
			transition: ease
		});
		
		this.begin = begin;
		this.end   = end;
	},
	set: function (now) {
		this.begin = now;
		
		this.fireEvent('update', this.begin);
		
		return now;
	},
	start: function (begin, end) {
		if (begin !== undefined && end !== undefined) {
			return this.parent(begin, end);
		}
		
		return this.parent(this.begin, this.end);
	},
	continueTo: function (end, duration) {
		this.cancel();
		
		this.options.duration = duration;
		this.end              = end;
		
		this.start();
		
		return this;
	}
});

var Scroller = new Class({
	initialize: function (content, scroller) {
		var that = this,
		    drag = scroller.getElement('.drag');
		
		this.content = content;
		this.value   = 0;
		
		this.content.addEvent('mousewheel', function (e) {
			e.stop();
			
			if (e.wheel < 0) {
				that.setScroll(that.value + 1);
			} else {
				that.setScroll(that.value - 1);
			}
		});
		
		this.slider = new Slider(scroller, drag, {
			mode: 'vertical',
			wheel: true,
			onChange: function (v) {
				that.value = v;
				that.onScrollUpdate();
			}
		});
	},
	setScroll: function (v) {
		this.slider.set(Math.min(100, Math.max(0, v)));
	},
	onScrollUpdate: function () {
		this.content.scrollTop = (this.content.scrollHeight - this.content.clientHeight) * (this.value / 100);
	}
});

var PageController = new Class({
	Implements: Events,
	initialize: function (sectChanger) {
		this.sectionChanger = sectChanger;
		
		if (!isFacebook) {
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, this.onSwfAddressChange.bind(this));
		}
	},
	setPage: function (id) {
		if (isFacebook) {
			this.sectionChanger.requestSection(id.slice(1));
		} else {
			SWFAddress.setValue(id);
		}
	},
	onSwfAddressChange: function () {
		this.sectionChanger.requestSection(SWFAddress.getValue().slice(1));
	}
});

var SectionChanger = new Class({
	Implements: Events,
	initialize: function () {
		this.clear();
	},
	requestSection: function (id) {
		if (id === this.queuedSection) {
			return;
		}
		
		if (id === this.getSection()) {
			this.queuedSection = null;
			return;
		}
		
		if (this.isChangingSections) {
			this.queuedSection = id;
		} else {
			this.startSectionChange(id);
		}
	},
	startSectionChange: function (id) {
		this.queuedSection      = null;
		this.section            = id;
		this.isChangingSections = true;
		
		this.fireEvent('request', this.section);
	},
	sectionChangeComplete: function () {
		if (!this.isChangingSections) {
			return;
		}
		
		this.isChangingSections = false;
		
		this.fireEvent('complete', this.section);
		
		if (this.queuedSection !== null) {
			this.startSectionChange(this.queuedSection);
		}
	},
	getSection: function () {
		return this.section;
	},
	getQueuedSection: function () {
		return this.queuedSection;
	},
	clear: function () {
		this.requestedSection   = null;
		this.queuedSection      = null;
		this.isChangingSections = false;
	}
});

var Banner = new Class({
	initialize: function () {
		var b = $('banner');
		
		this.content  = b.getElement('a');
		this.isOver   = false;
		this.tween    = new Tween(0, 1, 1, 'quad:out');
		this.interval = setInterval(this.toggle.bind(this), 4000);
		this.count    = 0;
		
		b.addEvents({
			mouseenter: this.over.bind(this),
			mouseleave: this.out.bind(this),
			click: function () {
				Tracking.banner();
			}
		});
		
		this.tween.addEvent('update', this.onTween.bind(this));
	},
	over: function () {
		clearInterval(this.interval);
		
		this.tween.continueTo(1, 400);
	},
	out: function () {
		clearInterval(this.interval);
		
		this.tween.continueTo(0, 400);
	},
	toggle: function () {
		this.isOver = !this.isOver;
		
		this.tween.continueTo(this.isOver ? 1 : 0, 400);
		
		if (++this.count >= 6) {
			clearInterval(this.interval);
		}
	},
	onTween: function (v) {
		var p = Math.round(v * 100);
		
		this.content.setStyles({
			filter: 'alpha(opacity=' + p + ')',
			opacity: v,
			'-ms-filter': '"progid:DXImageTransform.Microsoft.Alpha(opacity=' + p + ')"'
		});
	}
});

var MusicVideos = new Class({
	initialize: function () {
		var subContent = $('sub-content'),
		    vids       = $('music-videos'),
		    i          = 0,
		    that       = this,
		    share;
		
		this.videos         = subContent.getElements('ul.videos li div');
		this.touts          = subContent.getElements('ul.touts li');
		this.featuredVid    = this.videos[0];
		this.defaultVid     = this.featuredVid;
		this.title          = vids.getElement('div.bar div.title');
		this.vidContainer   = vids.getElement('div.video');
		this.musicTab       = $('header').getElement('li.music a');
		this.videoSlide     = new Tween(0, 1, 500, 'quad:out');
		this.sectionChanger = new SectionChanger();
		this.switchingLi    = null;
		this.requestedVid   = null;
		this.player         = null;
		this.queuedVid      = null;
		this.like           = vids.getElement('iframe.like');
		this.likeSrc        = this.like.get('src');

		this.videos.each(function (vid) {
			var a  = vid.getElement('a'),
			    h2 = vid.getElement('h2');
			
			vid.store('title', h2.get('text'));
			vid.store('yt', a.get('id'));
			vid.store('id', a.get('href').slice(2));
			
			h2.destroy();
		});
		
		this.like.set('src', this.likeSrc.split('*****').join(escape(this.featuredVid.retrieve('id'))));
		
		share = vids.getElements('div.bar');
		
		share.getElement('a.email').addEvent('click', function (e) {
			e.stop();
			Tracking.shareEmail();
			
			var vid = that.getMusicVideoDataById(that.featuredVid.retrieve('id'));
			
			if (vid !== false) {
				document.location = 'mailto:?subject=' + vid.subject + '&body=' + vid.message;
			}
		});
		
		share.getElement('a.twitter').addEvent('click', function (e) {
			e.stop();
			
			Tracking.shareTW();
			
			var vid = that.getMusicVideoDataById(that.featuredVid.retrieve('id'));
			
			if (vid !== false) {
				window.open('http://twitter.com/home?status=' + vid.twitter);
			}
		});
		
		share.getElement('a.facebook').addEvent('click', function (e) {
			e.stop();
			
			Tracking.shareFB();
			
			window.open(this.get('href').split('*****').join(escape(that.featuredVid.retrieve('id'))), 'fb', 'width=660,height=310,location=0,menubar=0,scrollbars=1,status=1,toolbar=0,resizable=1');
		});
		
		this.title.grab(new Element('h2', {text: this.defaultVid.retrieve('title')}));
		
		this.videoSlide.addEvent('update', this.onVideoSlide.bind(this));
		this.videoSlide.addEvent('complete', this.onVideoSlideComplete.bind(this));
		
		while (++i < this.videos.length) {
			this.touts[i - 1].grab(this.videos[i]);
		}
		
		this.createVideo(this.defaultVid.retrieve('yt'));
		
		this.sectionChanger.requestSection(this.featuredVid.retrieve('id'));
		this.sectionChanger.sectionChangeComplete();
		this.sectionChanger.addEvent('request', this.onVideoRequest.bind(this));
	},
	getMusicVideoDataById: function (id) {
		var i = -1;
		
		while (++i < musicVideos.length) {
			if (musicVideos[i].videoId === id) {
				return musicVideos[i];
			}
		}
		
		return false;
	},
	createVideo: function (id) {
		return//EVB
		var flashId = 'music-video';
		
		this.vidContainer.empty();
		this.vidContainer.adopt(new Element('div', {id: flashId}));
	
		if (!isiPad) {
			swfobject.embedSWF('http://www.youtube.com/e/' + id + '?enablejsapi=1&version=3&fs=1&hd=1&showsearch=0showinfo=0&rel=0', flashId, '760', '458', '8', null, null, {wmode: 'opaque', allowScriptAccess: 'always', allowfullscreen: 'true'}, {id: 'ytplayer'});
		}
	},
	createiPadVideo: function (id) {
		if (this.player !== null) {
			this.player.destroy();
		}
		
		if (id === null) {
			id = this.defaultVid.retrieve('yt');
		}
		
		this.player = new Element('embed', {
			src: 'http://www.youtube.com/v/' + id,
			width: 760,
			height: 458,
			type: 'application/x-shockwave-flash'
		});
		
		var video = $('music-video');
		
		video.empty();
		video.grab(this.player);
	},
	switchVideo: function (id) {
		if (isiPad) {
			this.createiPadVideo(id);
			return;
		}
		
		if (this.player === null) {
			this.queuedVid = id;
			return;
		}
		
		this.player.cueVideoById(id);
	},
	getVideoById: function (id) {
		var i = -1,
		    vid;
		
		while (++i < this.videos.length) {
			vid = this.videos[i];
			
			if (vid.retrieve('id') === id) {
				return vid;
			}
		}
		
		return null;
	},
	pauseVideo: function () {
		if (isiPad && this.player !== null) {
			this.player.destroy();
			this.player = null;
		} else if (this.player !== null && this.player.getPlayerState() === 1) {
			this.player.cueVideoById(this.featuredVid.retrieve('yt'), this.player.getCurrentTime());
		}
	},
	showVideo: function (id) {
		if (id === null) {
			id = this.defaultVid.retrieve('id');
		}
		
		if (isiPad && this.player === null && id === this.sectionChanger.getSection()) {
			this.createiPadVideo(this.getVideoById(id).retrieve('yt'));
			return;
		}
		
		this.sectionChanger.requestSection(id);
	},
	onVideoRequest: function (id) {
		this.requestedVid = this.getVideoById(id);
		
		if (this.requestedVid !== this.featuredVid) {
			this.switchingLi = this.requestedVid.getParent('li');
			
			this.switchingLi.grab(this.featuredVid);
		}
		
		this.title.grab(new Element('h2', {text: this.requestedVid.retrieve('title')}));
		
		this.switchVideo(this.requestedVid.retrieve('yt'));
		
		this.videoSlide.start(0, 1);
	},
	onVideoSlide: function (v) {
		this.switchingLi.scrollTop = interpolate(v, 0, 95);
		this.title.scrollTop       = interpolate(v, 0, 47);
	},
	onVideoSlideComplete: function () {
		this.featuredVid = this.requestedVid.dispose();
		
		var id = this.featuredVid.retrieve('id');
		
		this.title.getElement('h2').destroy();
		
		this.switchingLi.scrollTop = 0;
		this.title.scrollTop       = 0;
		this.switchingLi           = null;
		
		this.like.set('src', this.likeSrc.split('*****').join(escape(id)));
		
		this.musicTab.set('href', '#/' + id);
		
		this.sectionChanger.sectionChangeComplete();
	},
	onYouTubeInit: function (id) {
		this.player = $('ytplayer');
		
		if (this.queuedVid !== null) {
			this.switchVideo(this.queuedVid);
			this.queuedVid = null;
		}
	}
});

var SocialSender = new Class({
	initialize: function (container) {
		var that = this,
		    props = {
				property: 'opacity',
				transition: 'quad:out',
				duration: 500
			};
		
		this.container         = container;
		this.fade              = new Fx.Tween(this.container, props);
		this.overlay           = this.container.getElement('div.container-overlay');
		this.successMessage    = this.container.getElement('div.successMessage');
		this.socialOptions     = this.overlay.getElement('dl');
		this.message           = this.overlay.getElement('p');
		this.wasFacebookSend   = false;
		this.onFacebookSuccess = function () {
			that.onFacebookAuthed();
		};
		this.onTwitterSuccess = function () {
			that.onTwitterAuthed();
		};
		this.onSendSuccess = function () {
			that.onSendComplete();
		};
		
		this.overlay.getElement('li.facebook a').addEvent('click', function (e) {
			e.stop();
			that.authFacebook();
		});
		this.overlay.getElement('li.twitter a').addEvent('click', function (e) {
			e.stop();
			
			that.authTwitter();
		});
	},
	show: function () {
		this.container.addClass('show');
		this.fade.set(0);
		this.fade.start(0, 1);
		
		if (SocialConnect.facebook.isLoggedIn) {
			this.onFacebookAuthed();
		} else if (SocialConnect.twitter.isLoggedIn) {
			this.onTwitterAuthed();
		} else {
			this.overlay.addClass('show');
			this.socialOptions.addClass('show');
			
			if (isFacebook) {
				this.authFacebook();
			}
		}
	},
	close: function () {
		this.container.removeClass('show');
		this.overlay.removeClass('show');
		this.fade.cancel();
		
		SocialConnect.facebook.removeEvent('loggedIn', this.onFacebookSuccess);
		SocialConnect.twitter.removeEvent('loggedIn', this.onTwitterSuccess);
		
		SocialConnect.facebook.removeEvent('sendComplete', this.onSendSuccess);
		SocialConnect.twitter.removeEvent('sendComplete', this.onSendSuccess);
	},
	authTwitter: function () {
		if (SocialConnect.twitter.isLoggedIn) {
			this.onTwitterAuthed();
		} else if (!SocialConnect.twitter.isRequestingLogIn) {
			SocialConnect.twitter.addEvent('loggedIn', this.onTwitterSuccess);
			SocialConnect.twitter.login();
		}
	},
	onTwitterAuthed: function () {
		SocialConnect.twitter.removeEvent('loggedIn', this.onTwitterSuccess);
		
		this.onAuthed();
	},
	authFacebook: function () {
		if (SocialConnect.facebook.retrievedFriends) {
			this.onFacebookAuthed();
		} else if (!SocialConnect.facebook.isRequestingLogIn) {
			SocialConnect.facebook.addEvent('loggedIn', this.onFacebookSuccess);
			SocialConnect.facebook.login();
		}else {
		}
	},
	onFacebookAuthed: function () {
		SocialConnect.facebook.removeEvent('loggedIn', this.onFacebookSuccess);
		
		this.onAuthed();
	},
	onAuthed: function () {
		this.overlay.removeClass('show');
		this.socialOptions.removeClass('show');
	},
	sendFacebook: function (list) {
		this.showMessage('Sending...');
		
		this.wasFacebookSend = true;
		
		SocialConnect.facebook.addEvent('sendComplete', this.onSendSuccess);
		SocialConnect.facebook.sendRecipientList(list);
	},
	sendTwitter: function (list) {
		this.showMessage('Sending...');
		
		this.wasFacebookSend = false;
		
		SocialConnect.twitter.addEvent('sendComplete', this.onSendSuccess);
		SocialConnect.twitter.sendRecipientList(list);
	},
	onSendComplete: function () {
		if(this.successMessage) {
			this.successMessage.setStyle("opacity", 1.0);
			this.successMessage.setStyle("display", "block");
			setTimeout('this.successMessage.fade(\'out\');', 1000);
		}else {
			if (this.wasFacebookSend) {
				this.showMessage(SocialConnect.facebook.getSendStatusMessage());
			} else {
				this.showMessage(SocialConnect.twitter.getSendStatusMessage());
			}
		}
	},
	showMessage: function (copy) {
		this.overlay.addClass('show');
		
		this.message.set('text', copy);
	}
});

var SendRandom = new Class({
	Extends: SocialSender,
	initialize: function () {
		this.content    = $('random');
		this.friend     = null;
		this.isFacebook = false;
		this.videoId    = null;
		
		this.parent(this.content);
		
		var that = this;
		
		this.content.getElement('a.random').addEvent('click', function (e) {
			e.stop();
			Tracking.reshuffleRandomizer();
			that.randomize();
		});
		this.content.getElement('a.send').addEvent('click', this.onSend.bind(this));
	},
	show : function () {
		this.parent();
		Tracking.showRandomizer();
	},
	randomize: function () {
		var rand = SocialConnect.getRandomSerenade();
		
		$('randomSlide').set('src', rand.slide);
		$('randomTitle').set('text', rand.title);
		
		$('randomUserImage').set('src', rand.recipient.friend.photoURL);
		$('randomUserName').set('text', rand.recipient.friend.userName);
		
		this.videoId    = rand.videoId;
		this.friend     = rand.recipient;
		this.isFacebook = rand.network === 'facebook';
		var input = this.content.getElement('dl.to input');
		input.set('value', input.retrieve('defaultText'));
		this.content.removeClass('sent');
	},
	onAuthed: function () {
		this.parent();
		
		this.randomize();
	},
	onSend: function (e) {
		e.stop();
		Tracking.sendRandomizer();
		
		var input = this.content.getElement('dl.to input');
		var currentMessage = input.get('value');
		var checksum = currentMessage.replace(/\s+/g,'');
		if(checksum === "") currentMessage = "";
		
		this.friend.message = (currentMessage === input.retrieve('defaultText')) ? "" : currentMessage;
		
		if (this.isFacebook) {
			this.sendFacebook([this.friend]);
		} else {
			this.sendTwitter([this.friend]);
		}
	}
});

var SendSerenade = new Class({
	Extends: SocialSender,
	initialize: function () {
		this.content = $('send');
		
		this.parent(this.content);
		
		var list       = this.content.getElement('div.list'),
		    to         = this.content.getElements('div.to ul'),
		    socialTabs = this.content.getElement('div.friends ul.connect'),
		    that       = this;
		
		this.friendList  = list.getElement('ul');
		this.scrollDrag  = list.getElement('div');
		this.toList      = this.content.getElements('div.to ul li');
		this.facebookTab = socialTabs.getElement('li.facebook');
		this.twitterTab  = socialTabs.getElement('li.twitter');
		this.toUsers     = [];
		this.videoId     = null;
		this.isFacebook  = false;
		this.search      = $('search');
		
		this.search.addEvent('keyup', function (e) {
			that.onSearch(this.get('value'));
		});
		
		this.container.getElements('a.email').addEvent('click', function (e) {
			e.stop();
			Tracking.sendEmail();
			document.location = this.get('href').split('*****').join(escape(that.videoId));
		});
		
		this.facebookTab.getElement('a').addEvent('click', function (e) {
			e.stop();
			
			that.authFacebook();
		});
		
		this.twitterTab.getElement('a').addEvent('click', function (e) {
			e.stop();
			
			that.authTwitter();
		});
		
		to.getElements('a.closeButton').each(function (a) {
			a.addEvent('click', function (e) {
				e.stop();
				
				that.removeFriend(this.getParent('li').retrieve('user'));
			});
		});
		
		to.getElements('a.miniSend').each(function (a) {
			a.addEvent('click', function (e) {
				e.stop();
				
				var messages = [];
				var message = "";
				var element = this.getParent('li');

				var input = this.getParent('li').getElement('input');
				
				message = (input.get('value') === input.retrieve('defaultText')) ? "" : input.get('value');

				messages.push(new Recipient(element.retrieve('user'), that.videoId, message));
				that.removeFriend(element.retrieve('user'));
				if (that.isFacebook) {
					that.wasFacebookSend = true;
					SocialConnect.facebook.addEvent('sendComplete', that.onSendSuccess);
					SocialConnect.facebook.sendRecipientList(messages);
				} else {
					that.wasFacebookSend = false;
					SocialConnect.twitter.addEvent('sendComplete', this.onSendSuccess);
					SocialConnect.twitter.sendRecipientList(messages);
				}
			});
		});
		
		this.content.getElement('a.send').addEvent('click', this.onSend.bind(this));
		
		this.scroll = new Scroller(this.friendList, this.scrollDrag);
		
		this.clear();
	},
	show : function () {
		this.parent();
		Tracking.sendSerenade();
	},
	setVideoId: function (id) {
		this.videoId = id;
		this.content.getElement('h3 span').set('text', $(id).get('text'));
	},
	onSearch: function (query) {
		if (query === '') {
			this.clearSearch();
		}
		
		var found = 0;
		
		this.friendList.getElements('li').each(function (li) {
			if (li.retrieve('user').userName.toLowerCase().indexOf(query.toLowerCase()) > -1) {
				found++;
				li.removeClass('hide');
			} else {
				li.addClass('hide');
			}
		});
		
		this.scroll.setScroll(0);
		
		if (found < 10) {
			this.scrollDrag.addClass('hide');
		} else {
			this.scrollDrag.removeClass('hide');
		}
	},
	clearSearch: function () {
		var friends = this.friendList.getElements('li');
		
		friends.removeClass('hide');
		
		this.scroll.setScroll(0);
		
		if (friends.length < 10) {
			this.scrollDrag.addClass('hide');
		} else {
			this.scrollDrag.removeClass('hide');
		}
	},
	onTwitterAuthed: function () {
		this.parent();
		
		this.clear();
		
		this.isFacebook = false;
		
		this.clearSearch();
		
		this.facebookTab.removeClass('active');
		this.twitterTab.addClass('active');
		
		this.showFriends(SocialConnect.twitter.friends);
	},
	onFacebookAuthed: function () {
		this.parent();
		
		this.clear();
		
		this.isFacebook = true;
		
		this.clearSearch();
		
		this.facebookTab.addClass('active');
		this.twitterTab.removeClass('active');
		
		this.showFriends(SocialConnect.facebook.friends);
	},
	showFriends: function (friends) {
		var that = this;
		
		this.clear();
		
		friends.each(function (friend) {
			var li = new Element('li', {
				id: friend.userId,
				html: '<a href="#">' + friend.userName + '</a>'
			});
			li.store('user', friend);
			
			that.friendList.grab(li);
		});
		
		this.scroll.setScroll(0);
		
		if (friends.length < 10) {
			this.scrollDrag.addClass('hide');
		} else {
			this.scrollDrag.removeClass('hide');
		}
		
		this.friendList.getElements('a').each(function (a) {
			a.addEvent('click', function (e) {
				e.stop();
				
				if (this.hasClass('active')) {
					return;
				}
				
				that.sendToFriend(this.getParent('li').retrieve('user'));
			});
		});
	},
	sendToFriend: function (friend) {
		if (this.toUsers.length === 5) {
			return;
		}
		
		$(friend.userId).getElement('a').addClass('active');
		
		var targetLi = this.toList[this.toUsers.length],
		    message = targetLi.getElement('input'),
		    profile = new Element('img', {
				src: friend.photoURL,
				width: 48,
				height: 48
			});
		
		targetLi.getElement('h4').set('text', friend.userName);
		targetLi.getElement('span.thumb').grab(profile);
		targetLi.getElement('span.thumb').grab(profile);
		message.set('value', message.retrieve('defaultText'));
		targetLi.store('user', friend);
		targetLi.removeClass('empty');
		
		this.toUsers.push(friend);
		
		return targetLi;
	},
	removeFriend: function (friend) {
		$(friend.userId).getElement('a').removeClass('active');
		
		var cloneUsers = [],
		    that       = this;
		
		this.toList.each(function (li) {
			if (!li.hasClass('empty')) {
				cloneUsers.push({data: li.retrieve('user'), message: li.getElement('input').get('value')});
			}
		});
		
		this.clearToList();
		
		cloneUsers.each(function (f) {
			if (f.data.userId !== friend.userId) {
				that.sendToFriend(f.data).getElement('input').set('value', f.message);
			}
		});
	},
	clearToList: function () {
		this.toList.each(function (li) {
			this.eliminate('user');
			
			var img = li.getElement('img');
			
			if (img !== null) {
				img.destroy();
			}
			
			li.addClass('empty');
		});
		this.toUsers = [];
	},
	clear: function () {
		this.scroll.setScroll(0);
		this.friendList.empty();
		
		this.clearToList();
		
		this.content.removeClass('sent');
	},
	onSend: function (e) {
		e.stop();
		
		if (this.toUsers.length > 0) {
			var messages = [],
			    that     = this;
			
			this.toList.each(function (li) {
				if (!li.hasClass('empty')) {
					var input   = li.getElement('input'),
					    message = (input.get('value') === input.retrieve('defaultText')) ? null : input.get('value');
					
					messages.push(new Recipient(li.retrieve('user'), that.videoId, message));
				}
			});
			
			this.friendList.getElements('a').removeClass('active');
			this.clearToList();
			
			if (this.isFacebook) {
				this.sendFacebook(messages);
			} else {
				this.sendTwitter(messages);
			}
		}
	}
});

var Serenades = new Class({
	initialize: function () {
		var that  = this,
		    flashvars = {
				locid: 'site', //'fb'
				videoid: '',
				nameid: '',
				videoband: 'high',
				videopath: ''
			},
		    params = {
				bgcolor: '000000',
				scale: 'noscale',
				salign: 'tl',
				menu: 'false',
				quality: 'high',
				wmode: 'opaque',
				allowScriptAccess: 'always',
				allowfullscreen: 'true'
			},
		    attributes = {
				id: 'serenade-player',
				name: 'serenade-player'
			};
		
		if (!isiPad) {
			swfobject.embedSWF('media/swf/UnicornVideoPlayer.swf', 'selector', '760', '427', '9', 'media/swf/express_install.swf', flashvars, params, attributes);
			$('serenade-selector').getElements('ul').addClass('hide');
		}
		
		this.sectionChanger = new SectionChanger();
		this.content        = $('serenades');
		this.barContent     = this.content.getElement('div.bar');
		this.tween          = new Tween(0, 1, 1, 'quad:out');
		this.player         = null;
		this.queuedVid      = null;
		this.sendSerenade   = new SendSerenade();
		this.sendRandom     = new SendRandom();
		this.like           = this.content.getElement('iframe.like');
		this.likeSrc        = this.like.get('src');
		
		this.barContent.getElement('a.all').addEvent('click', function (e) {
			e.stop();
			Tracking.viewAll();
			
			jf.setPage('/serenades');
		});
		//here is the button to click to share mini serenades
		this.content.getElement('div.bar a.send').addEvent('click', this.onSendClick.bind(this));
		$('send').getElement('a.container-close').addEvent('click', function (e) {
			e.stop();
			
			that.closeSend();
		});
		
		$('sub-content').getElement('a.random').addEvent('click', this.onRandomClick.bind(this));
		$('random').getElement('a.container-close').addEvent('click', function (e) {
			e.stop();
			
			that.closeRandom();
		});
		
		this.tween.addEvent('update', this.onTweenUpdate.bind(this));
		this.tween.addEvent('complete', this.onTweenComplete.bind(this));
		
		this.sectionChanger.requestSection('/');
		this.sectionChanger.sectionChangeComplete();
		this.sectionChanger.addEvent('request', this.onSerenadeRequest.bind(this));
	},
	requestSerenade: function (id) {
		this.closeSend();
		this.closeRandom();
		
		this.sectionChanger.requestSection(id);
	},
	onSerenadeRequest: function (id) {
		if (isiPad) {
			this.onTweenUpdate((id === '/') ? 0 : 1);
			this.onTweenComplete();
		} else {
			this.tween.continueTo((id === '/') ? 0 : 1, 500);
		}
		
		if (id === '/') {
			this.hideVideo();
		} else {
			this.showVideo(id);
		}
	},
	onTweenUpdate: function (v) {
		this.barContent.scrollLeft = interpolate(v, 0, 760);
	},
	onTweenComplete: function () {
		this.sectionChanger.sectionChangeComplete();
	},
	onSendClick: function (e) {
		e.stop();
		
		//if (!isiPad && this.player !== null && this.player.isPlaying() === true) {
		if (isiPad) {
			this.hideVideo();
		} else if (this.player) {
			this.player.pauseVideo();
		} else if (this.queuedVid !== null) {
			this.queuedVid = null;
		}
		
		this.sendSerenade.show();
	},
	closeSend: function (e) {
		if (isiPad) {
			var id = this.sectionChanger.getSection();
			
			if (id !== '/') {
				this.showVideo(id);
			}
		}
		
		this.sendSerenade.close();
	},
	onRandomClick: function (e) {
		e.stop();
		
		if (!$('random').hasClass('show')) {
			this.closeSend();
			
			if (!isiPad && this.player !== null) { // && this.player.isPlaying() === true) {
				this.player.pauseVideo();
			} else if (this.queuedVid !== null) {
				this.queuedVid = null;
			}
			
			if (isiPad) {
				this.hideVideo();
			}
			
			this.sendRandom.show();
		}
	},
	closeRandom: function (e) {
		if (isiPad) {
			var id = this.sectionChanger.getSection();
			
			if (id !== '/') {
				this.showVideo(id);
			}
		}
		
		this.sendRandom.close();
	},
	showVideo: function (id) {
		this.like.set('src', this.likeSrc.split('*****').join(escape(id)));
		
		if (isiPad) {
			if (this.player !== null) {
				this.hideVideo();
			}
			
			$('selector').addClass('hide');
			$('serenade-selector').addClass('video');
			
			var i = -1,
			    path;
			
			while (++i < serenadesData.length) {
				if (serenadesData[i].videoId === id) {
					path = serenadesData[i].video;
					break;
				}
			}
			
			this.player = new Element('video', {
				src: path,
				width: 760,
				height: 427,
				controls: ''
			});
			
			$('serenade-selector').grab(this.player);
			
			this.sendSerenade.setVideoId(id);
			return;
		}
		
		if (this.player !== null) {
			this.barContent.getElement('h2').set('text', $(id).get('text'));
			
			this.sendSerenade.setVideoId(id);
			this.player.loadVideoById(id);
		} else {
			this.queuedVid = id;
		}
	},
	hideVideo: function () {
		if (this.player !== null) {
			if (isiPad) {
				$('selector').removeClass('hide');
				$('serenade-selector').removeClass('video');
				
				this.player.destroy();
				this.player = null;
			} else {
				this.player.showMenu();
			}
		}
	},
	onSerenadePlayerInit: function () {
		this.player = $('serenade-player');
		
		if (this.queuedVid !== null) {
			this.showVideo(this.queuedVid);
			this.queuedVid = null;
		} else {
			this.player.showMenu(false);
		}
	}
});

var Unicorn = new Class({
	initialize: function () {
		var that    = this,
		    header  = $('header'),
		    body    = $(document.body),
		    i       = -1,
		    isMusic = false,
		    footer  = $('footer');
		
		this.sectionChanger = new SectionChanger();
		this.pageController = new PageController(this.sectionChanger);
		this.slide          = new Tween(0, 1, 1, 'quad:out');
		this.musicFade      = new Tween(0, 1, 1, 'quad:out');
		this.serenadeFade   = new Tween(0, 1, 1, 'quad:out');
		this.content        = $('content');
		this.subContent     = $('sub-content');
		this.isSend         = isFacebook;
		this.musicTab       = header.getElement('li.music a');
		this.serenadeTab    = header.getElement('li.serenade a');
		this.musicVideos    = new MusicVideos();
		this.serenades      = new Serenades();
		
		if (!isiPad) {
			this.banner = new Banner();
		} else {
			body.getElements('a').addEvents({
				touchstart: function () {
					this.addClass('touch');
				},
				touchend: function () {
					this.removeClass('touch');
				},
				touchcancel: function () {
					this.removeClass('touch');
				}
			});
		}
		
		if (!isiPad) {
			/*EVB
			this.musicTab.addEvents({
				mouseenter: function () {
					if (!this.hasClass('active')) {
						that.musicFade.continueTo(1, 500);
					}
				},
				mouseleave: function () {
					if (!this.hasClass('active')) {
						that.musicFade.continueTo(0, 500);
					}
				}
			});
			*/
			this.serenadeTab.addEvents({
				mouseenter: function () {
					if (!this.hasClass('active')) {
						that.serenadeFade.continueTo(1, 500);
					}
				},
				mouseleave: function () {
					if (!this.hasClass('active')) {
						that.serenadeFade.continueTo(0, 500);
					}
				}
			});
		}
		
		footer.getElement('a.facebook').addEvent('click', function () {
			Tracking.linkFB();
		});
		footer.getElement('a.youtube').addEvent('click', function () {
			Tracking.linkYT();
		});
		
		this.musicFade.addEvent('update', this.onMusicFade.bind(this));
		this.serenadeFade.addEvent('update', this.onSerenadeFade.bind(this));
		this.musicFade.set(isFacebook ? 0 : 1);
		this.serenadeFade.set(isFacebook ? 1 : 0);
		
		if (isFacebook) {
			this.serenadeTab.addClass('active');
		} else {
			//EVBthis.musicTab.addClass('active');
		}
		
		this.slide.addEvent('update', this.onSlide.bind(this));
		this.slide.addEvent('complete', this.onSlideComplete.bind(this));
		this.slide.set(isFacebook ? 1 : 0);
		
		this.content.getElements('input.guide').each(function (input) {
			if (input.get('value') !== '') {
				input.store('defaultText', input.get('value'));
				input.addEvent('focus', function () {
					if (this.get('value') === this.retrieve('defaultText')) {
						this.set('value', '');
						this.addClass('active');
					}
				});
				input.addEvent('blur', function () {
					if (this.get('value') === '' && this.retrieve('defaultText')) {
						this.set('value', this.retrieve('defaultText'));
						this.removeClass('active');
					}
				});
			}
		});
		
		body.addEvent('click', function (e) {
			var target = $(e.target),
			    a      = (target.get('tag') === 'a') ? target : target.getParent('a'),
			    rel,
			    href;
			
			if (a !== null) {
				rel  = a.get('rel');
				href = a.get('href');
				
				if (rel === 'external' || rel === 'nofollow') {
					e.stop();
					window.open(href);
				} else if (rel === 'internal') {
					e.stop();
					
					that.pageController.setPage(href.slice(1));
				}
			}
		});
		
		this.sectionChanger.addEvent('request', this.onSectionRequest.bind(this));
		
		if (deepLink !== null) {
			while (++i < musicVideos.length) {
				if (musicVideos[i].videoId === deepLink) {
					isMusic = true;
					break;
				}
			}
			
			this.setPage(isMusic ? '/' + deepLink : '/serenades/' + deepLink);
		}
	},
	onSectionRequest: function (id) {
		var isSend = false,
		    parts;
		
		if (id === '/' || id === '' || id === null || id === undefined) {
			id = null;

			Tracking.setPageType('videos');
			Tracking.setVideoId(this.musicVideos.defaultVid.retrieve('id'));
		}
		
		if (id !== null) {
			parts = id.split('/');
			
			switch (parts[0]) {
			case 'serenades':
				isSend = true;
				
				this.musicVideos.pauseVideo();
				
				Tracking.setPageType('serenades');
				
				if (parts.length > 1) {
					Tracking.setVideoId(parts[1]);
					this.serenades.requestSerenade(parts[1]);
				} else {
					this.serenades.requestSerenade('/');
				}
				break;
//			case 'whip-it':
//				id = 'keenan';
//			case 'keenan':
//			case 'gangsta':
//			case 'angel':
//				Tracking.setPageType('videos');
//				Tracking.setVideoId(id);
//		
//				this.serenades.requestSerenade('/');
//				this.musicVideos.showVideo(id);
//				break;
			default:
				id = null;
				this.serenades.requestSerenade('/');
				this.musicVideos.showVideo(id);
			}
		} else {
			this.serenades.requestSerenade('/');
		}
				
		if (isiPad && id === null) {
			this.musicVideos.createiPadVideo(id);
		}
		//EVB	
			isSend = true;
			this.musicTab.removeClass('active');
		//
		if (this.isSend !== isSend) {
			this.isSend = isSend;
			
			if (this.isSend) {
				this.musicTab.removeClass('active');
				this.serenadeTab.addClass('active');
			} else {
				//EVB	this.musicTab.addClass('active');
				this.serenadeTab.removeClass('active');
			}
			
			if (isiPad) {
				this.slide.set(this.isSend ? 1 : 0);
				this.musicFade.set(this.isSend ? 0 : 1, 500);
				this.serenadeFade.set(this.isSend ? 1 : 0, 500);
				this.onSlideComplete();
			} else {
				this.slide.continueTo(this.isSend ? 1 : 0, 500);
				this.musicFade.continueTo(this.isSend ? 0 : 1, 500);
				this.serenadeFade.continueTo(this.isSend ? 1 : 0, 500);
			}
		} else {
			this.sectionChanger.sectionChangeComplete();
		}
	},
	onSlide: function (v) {
		this.content.scrollLeft    = interpolate(v, 0, 760);
		this.subContent.scrollLeft = interpolate(v, 0, 708);
		this.content.setStyle('height', interpolate(v, 505, 477));
		this.subContent.setStyle('height', interpolate(v, 95, 58));
	},
	onMusicFade: function (v) {
		var p = Math.round(v * 100);
		
		this.musicTab.setStyles({
			filter: 'alpha(opacity=' + p + ')',
			opacity: v,
			'-ms-filter': '"progid:DXImageTransform.Microsoft.Alpha(opacity=' + p + ')"'
		});
	},
	onSerenadeFade: function (v) {
		var p = Math.round(v * 100);
		
		this.serenadeTab.setStyles({
			filter: 'alpha(opacity=' + p + ')',
			opacity: v,
			'-ms-filter': '"progid:DXImageTransform.Microsoft.Alpha(opacity=' + p + ')"'
		});
	},
	onSlideComplete: function () {
		this.sectionChanger.sectionChangeComplete();
	},
	onYouTubeInit: function (id) {
		this.musicVideos.onYouTubeInit(id);
	},
	setPage: function (id) {
		this.pageController.setPage(id);
	},
	onSerenadePlayerInit: function () {
		this.serenades.onSerenadePlayerInit();
	}
});

window.addEvent('domready', function () {
	SocialConnect.facebook.initAPI();
	
	Tracking = new TrackingClass();
	
	jf = new Unicorn();
});
