var sliders = false;
var living_room = false;
var move_fx = false;
var tray_open = false;
var scientist = false;
var video = false;

var slider_open = false;

window.addEvent('domready', function() {
	$('intro').addEvent('click', intro_open);
	$('main').addEvent('click', intro_close);
	$$('.item').addEvent('click', function(event){
		 event.stopPropagation();
		 event.preventDefault();
	});
	$$('.new_connect li').addEvent('click', function(){
		var the_link = $$(this.getElementsByTagName('a'));
		
		if (!the_link[0].onclick || (the_link[0].onclick()!=false))
		 location=the_link[0].href; 
	});
	
	scientist			= new Scientist();
	video 				= new Video(8599559);
	
	move_fx 			= new Fx.Tween('mover', { duration: 800, transition: Fx.Transitions.Quad.easeInOut, onComplete: on_intro_closed });
	sliders 			= new Sliders();
	living_room 		= new LivingRoom($('living_room'));
	
	new Poll('txt_username', username_check);
	
	draw();
});

window.addEvent('resize', draw);

function draw() 
{
	update_viewport();
}

function update_viewport()
{
	var wh = window.getHeight();
	
	if (tray_open) {
		$('viewport').setHeight(wh < 540 ? 540 : wh);
	} 
	else {
		var h = $('main').getHeight() + 100;
		h = h < wh ? wh : h;
		$('viewport').setHeight(h);
	}
	
	try {
		scientist.draw();
	}
	catch (ex) { }
}

function download_boxee(url)
{
	if (url == 'appletv') 
		location.href = '/download/' + url;
	else
		location.href = '/signup/?download=' + url;
}

var disable_resgister = false;
function register_user(e)
{
	e = new Event(e);
	e.stop();

	$('register_btn').disabled = true;
	$('register_btn').value = 'Submitting ...';
	
	var fields = ['fname','lname','email','username','password','password_check'];
	for (var i = 0; i < fields.length; i++) {
		$('txt_' + fields[i]).className = 'field';
	}
	
	// Passwords dont match
	if ($('txt_password').value != $('txt_password_check').value) 
	{	
		$('txt_password_check').className = $('txt_password').className = 'field_error';
		$('register_error_msg').innerHTML = 'Passwords do not match.';
		$('register_btn').value = 'Submit';
		$('register_btn').disabled = false;
		return false;
	}
	
	// Post request
	var r = new Request({
		url: '/accountapi/register',
		method: 'post',
		data:  'fname=' 	+ encodeURIComponent($('txt_fname').value) + 
			  '&lname=' 	+ encodeURIComponent($('txt_lname').value) +
			  '&email=' 	+ encodeURIComponent($('txt_email').value) +
			  '&username=' 	+ encodeURIComponent($('txt_username').value) +
			  '&password=' 	+ encodeURIComponent($('txt_password').value) +
			  '&boxeemail=' + encodeURIComponent($('chk_boxeemail').checked ? 1 : 0) +
			  '&format=json&disable_captcha=1&eula=true',
			
		onComplete: function(json) {
			json = JSON.decode(json);
			
			$('register_error_msg').innerHTML = '';
			
			if (!json.success) 
			{
				var i = 0;
				for (field in json.errors) 
				{
					if (i == 0) // Display error message
					{
						if (json.errors[field] == 'Too short.')
							$('register_error_msg').innerHTML = field + ' is too short.';
						else
							$('register_error_msg').innerHTML = json.errors[field];
					}
					
					$('txt_' + field).className = 'field_error';
					i++;
				}
				
				$('register_btn').disabled = false;
				$('register_btn').value = 'Submit';
			}
			else  // Auto fill out the login form and submit
			{
				$('register_btn').value = 'All set! Logging you in ...';
				window.location = '/signup/friends';
			}
		}
	});
	
	r.send();
}

var username_check_request = false;
function username_check(e)
{
	if (!/^[a-zA-Z0-9_.]+$/.test($('txt_username').value))
		return false;
		
	if (username_check_request) 
		username_check_request.cancel();
		
	$('username_response').innerHTML = 'Searching ...';
	
	username_check_request = new Request({
		url: '/api/checkid',
		method: 'post',
		data: 'userid=' + $('txt_username').value + '&format=json',
		onComplete: function(json) {
			var j = JSON.decode(json);
			
			disable_register = j.exists;
			
			$('username_response').className = '';
			$('username_response').addClass(!j.exists ? 'response_success' : 'response_fail');
			$('username_response').innerHTML = "'" + $('txt_username').value + "' is " + (j.exists ? 'unavailable' : 'available');
		}
	});
	username_check_request.send();
}

var prev_username_txt = '';
function username_char_check(e)
{
	if (/^[a-zA-Z0-9_.]*$/.test(e.currentTarget.value)) {
		prev_username_txt = e.currentTarget.value;
	}
	else {
		e.currentTarget.value = prev_username_txt;
	}
}

function intro_click()
{	
	if (!tray_open) {
		intro_open();
	}
	else {
		intro_close();
	}
}

function intro_open()
{
	if (!tray_open) {
		scientist.guyFrame(1);
		scientist.hideText();
		video.play();
	
		sliders.closeMenus();
		sliders.disable();
		living_room.hidePoints();
	
		scientist.slideUp();

		move_fx.start('margin-top', -420, 0);
		tray_open = true;
	}
	
	update_viewport();
	draw();
}

function intro_close()
{
	if (tray_open) {
		scientist.guyFrame(1);
		scientist.hideText();
		scientist.slideDown();
		move_fx.start('margin-top', 0, -420);
		tray_open = false;
	
		video.pause();
	}
	
	update_viewport();
	draw();
}

function on_intro_closed()
{
	draw();
	
	if (!tray_open) {
		scientist.guyFrame(0);
		scientist.setText(scientist.closed_txt);
		living_room.showPoints();
		living_room.draw();
		sliders.enable();
	}
	else {
		scientist.guyFrame(2);
		scientist.setText(scientist.open_txt);
	}
}

function menu_click(i)
{
	if (browser_iphone) 
	{
		switch (i)
		{
			case 0:
				location.href = '/signup';
				break;
				
			case 3:
				location.href = '/auth';
				break;
		}
		
	}
}

function menu_hover(el, e) 
{
	if (e.type == 'mouseover') 
		el.addClass('selected');
	else 
		el.removeClass('selected');
}

var LivingRoom = new Class({
	
	source: false, // the element to place the dots onto
	points: [],
	point_img: '/htdocs/images/logged_out/dot.png',
	hit_radius: 15,
	current: false,
	
	initialize: function(src)
	{
		this.source = src;
		
		window.addEvent('resize', this.draw.bind(this));
		
		this.draw();
	},
	
	add: function(content_id, x, y)
	{
		var p = new Element('div', { 
			'html': '&nbsp;',
			'styles': {
				'background': "url('" + this.point_img + "') no-repeat",
				'background-position': (this.hit_radius - 5) + 'px ' + (this.hit_radius - 5) + 'px',
				'overflow': 'hidden',
				'position': 'absolute',
				'display': 'none',
				'width': (this.hit_radius * 2) + 'px',
				'height': (this.hit_radius * 2) + 'px',
				'top': '0',
				'left': '0'
			},
			'events': {
				'mouseover': this.showTip.bind(this, this.points.length)
			}
		});
		
		$(document.body).adopt(p);
		
		var tip = $(content_id);
		tip.setStyle('position', 'absolute');
		tip.setStyle('z-index', '200');
		tip.setStyle('display', 'none');
		tip.setPosition(0, 0);
		tip.addEvent('mouseleave', this.hideAll.bind(this))
		
		this.points.push({
			tip: tip,
			x: x,
			y: y,
			point: p
		});
		
		this.draw();
	},
	
	find: function(id)
	{
		for (var i = 0; i < this.points.length; i++) {
			if (this.points[i].id == id)
				return i;
		}
		
		return false;
	},
	
	onPointOver: function(i)
	{
		this.showTip(i);
	},
	
	showTip: function(i)
	{
		this.current = i;
		if (!this.points[i].tip.isShowing()) {
			
			this.points[i].tip.show();
			this.points[i].tip.setPosition(this.points[i].x + this.source.getX() - 15, 
										   this.points[i].y + this.source.getY() - this.points[i].tip.getHeight() + 14);
		}
	},
	
	hideAll: function()
	{
		for (var i = 0; i < this.points.length; i++) {
			this.points[i].tip.hide();
		}
	},
	
	hidePoints: function()
	{
		this.hideAll();
		for (var i = 0; i < this.points.length; i++) {
			this.points[i].point.setStyle('visibility', 'hidden');
		}
	},
	
	showPoints: function()
	{
		for (var i = 0; i < this.points.length; i++) {
			this.points[i].point.setStyle('visibility', 'visible');
		}
	},
	
	draw: function()
	{
		for (var i = 0; i < this.points.length; i++) {
			this.points[i].point.show();
			this.points[i].point.setPosition(
				this.points[i].x + this.source.getX() - this.hit_radius,
				this.points[i].y + this.source.getY() - this.hit_radius
			);
		}
	}
});


var Sliders = new Class({	
	//Implement: Options,
	sliders: [],
	menus: [],
	fx: [],
	rollover_check: false,
	disabled: false,
	
	initialize: function() {
		this.menus = $$('.menu .item');
		
		// Bootup
		for (var i = 0; i < this.menus.length; i++) {
			var id = this.menus[i].id.split('_')[0];
			 this.menus[i].addEvent('mouseenter', this.openMenu.bind(this, i));
			
			if (i == 3) 
				this.menus[i].addEvent('click', this.onSliderOpen.bind(this, i));
			
			if (i == 1 || i == 2) 
				this.menus[i].addEvent('mouseleave', this.delayCloseMenu.bind(this, i));
			
			this.sliders.push($(id + '_slider'));
			
			var wrapper_fx_el = this.sliders[i].getFirst();
			var fx_el = wrapper_fx_el.getFirst();
			fx_el.store('wrapper', wrapper_fx_el);
			
			//this.sliders[i].store('box', fx_el.getFirst());
			this.sliders[i].setStyle('z-index', 2000);
			this.sliders[i].addEvent('mouseenter', this.sliderMouseEnter.bind(this, i));
			
			if (i == 1 || i == 2)
				this.sliders[i].addEvent('mouseleave', this.closeMenu.bind(this, i));
			
			this.sliders[i].show();
			
			// Calc height of box for right shadow
			var box_els = fx_el.getChildren();
			box_els[1].setHeight(box_els[0].getHeight()); // set shadow height
			fx_el.setWidth(this.menus[i].getWidth() - 0);
			box_els[0].setWidth(this.menus[i].getWidth() - 35); // set width (minus all the padding and borders)
			
			if (!Browser.Engine.trident) 
			{
				this.fx.push(new Fx.Slide(fx_el, { duration: 200, transition: Fx.Transitions.Back.easeOut, customOffset: -20, onComplete: this.onSliderOpen.bind(this, i) }));
				this.fx[i].hide();
			}
			else 
			{
				this.sliders[i].setStyle('visibility', 'hidden');
			}
		}
		
		this.draw();
		
		$(document.body).addEvent('click', function(e) { 
			var is_slider = false;
			for (var i = 0; i < this.sliders.length; i++) {
				if (this.sliders[i].hasChild(e.target)) {
					is_slider = true;
					break;
				}
			}
 			
			if (!is_slider)
				this.closeMenus();
				
		}.bind(this));
		window.addEvent('resize', this.draw.bind(this));
	},
	
	disable: function() 
	{
		this.disabled = true;
	},
	
	enable: function()
	{
		this.disabled = false;
	},
	
	openMenu: function(i)
	{	
		if (!this.disabled) {
			this.closeMenus();
			this.drawSlider(i);
			
			if (!Browser.Engine.trident) {
				this.fx[i].cancel();
				this.fx[i].slideIn();
			}
			else {
				this.sliders[i].setStyle('visibility', 'visible');
			}
		}
	},
	
	closeMenu: function(i)
	{
		if (!this.disabled) {
			if (this.rollover_check === false || this.rollover_check != i || i == 3 || i == 0) {	
				if (!Browser.Engine.trident) {
					this.fx[i].cancel();
					this.fx[i].slideOut();
				}
				else {
					this.sliders[i].setStyle('visibility', 'hidden');
				}
			}
			else {
				this.rollover_check = false;
			}
		}
	},
	
	closeMenus: function()
	{
		
		for (var i = 0; i < this.menus.length; i++)
		{	
			this.closeMenu(i);
		}
	},
	
	toggleMenus: function(i)
	{
		if(this.menus[i] == 'open')
		{
			console.log(this.menus);
		}
		
	},
	
	onSliderOpen: function(i)
	{
		if (this.fx[i].element.getStyle('margin-top').toInt() > -30)
		{
			if (i == 0)
				$('txt_fname').focus();
			else if (i == 3)
				$('login_username').focus();
		}
	},
	
	delayCloseMenu: function(i)
	{
		this.closeMenu.delay(100, this, i);
	},
	
	sliderMouseEnter: function(i)
	{
		this.rollover_check = i;
	},
	
	drawSlider: function(i) 
	{
		var coord = this.menus[i].getCoordinates();
		this.sliders[i].setPosition(coord.left, coord.top + coord.height);
		
		var shadow = this.sliders[i].getFirst().getFirst().getChildren()[1];
		shadow.setHeight(this.sliders[i].getFirst().getFirst().getHeight() - 5);
	},
	
	draw: function() 
	{
		for (var i = 0; i < this.sliders.length; i++) {
			this.drawSlider(i);
		}
	}
});

var Scientist = new Class({
	
	fx: false,
	guy: false,
	bubble: false,
	text: false,

	closed_txt: 'Click here to see an introduction to Boxee!',
	open_txt: 'Click here to return to the home page!',
	
	initialize: function()
	{
			
		window.addEvent('resize', this.draw.bind(this));
		
		this.guy = new Element('div', {
			'id': 'scientist',
			'styles': {
				'background': 'url(/htdocs/images/logged_out/scientist-sprite.png) no-repeat',
				'display': 'none',
				'width': '179px',
				'height': '167px',
				'overflow': 'hidden',
				'visibility': browser_iphone ? 'hidden' : 'visible'
			},
			'events': {
				'click': this.click.bind(this)
			}
		});
		this.guyFrame(0);
		
		this.bubble = new Element('img', {
			'id': 'speechbubble',
			'display': 'none',
			'src': '/htdocs/images/logged_out/speech-bubble.png',
			'styles': {
				'visibility': browser_iphone ? 'hidden' : 'visible'
			},
			'events': {
				'click': this.click.bind(this)
			}
		});
		
		this.text = new Element('div', {
			'id': 'speechtext',
			'display': 'none',
			'html': 'safdasfsd',
			'styles': {
				'visibility': browser_iphone ? 'hidden' : 'visible'
			},
			'events': {
				'click': this.click.bind(this)
			}
		})
		
		$(document.body).adopt(this.guy);
		$(document.body).adopt(this.bubble);
		$(document.body).adopt(this.text);
	
		this.fx = new Fx.Tween('scientist', { duration: 800, transition: Fx.Transitions.Quad.easeInOut });
	
		this.draw();
		
		this.setText(this.closed_txt);
	},
	
	guyFrame: function(frame)
	{
		this.guy.setStyle('background-position', '0px ' + (frame * -167) + 'px');
	},
	
	click: function()
	{
		intro_click();
	},
	
	draw: function()
	{
		var pos = $('login_menu').getCoordinates();
		this.guy.show();
		this.guy.setPosition(pos.left + 70, pos.top - 130);
		this.bubble.setPosition(pos.left - 20, pos.top - 85);
		this.text.setPosition(pos.left - 10, pos.top - 75);
	},
	
	hideText: function()
	{
		this.bubble.hide();
		this.text.hide();
	},
	
	showText: function()
	{
		this.bubble.show();
		this.text.show();
		this.draw();
	},
	
	setText: function(txt) 
	{
		this.text.innerHTML = txt;
		this.showText();
	},
	
	slideUp: function()
	{
		this.fx.start('top', this.guy.getY(), this.guy.getY() + 420);
	},
	
	slideDown: function()
	{
		this.fx.start('top', this.guy.getY(), this.guy.getY() - 420);
	}
});

// Vimeo player interaction
var Video = new Class({
	
	swf_obj: false,
	container: 'video',
	swf_id: 'vimeo',
	loaded: false,
	
	initialize: function(id)
	{
		scientist.hideText();
		
		if (Browser.Plugins.Flash.version.toInt() < 8) {
			$(this.container).innerHTML = 'Flash is required in order to play this vidoe. <a href="http://get.adobe.com/flashplayer/">Click here to download the latest Flash Player</a>';
			return false;
		}

		var moogaloop = new Swiff('http://vimeo.com/moogaloop.swf', {
		    id: this.swf_id,
			container: this.container,	
		    width: 640,
		    height: 424,
		    vars: {
		        clip_id: id,
		        show_portrait: 1,
		        show_byline: 1,
		        show_title: 1,
				js_api: 1, // required in order to use the Javascript API
				js_onLoad: 'video.onLoad', // moogaloop will call this JS function when it's done loading (optional)
				js_swf_id: this.swf_id
		    }
		});
		
		this.swf_obj = document.getElementById(this.swf_id);
	},
	
	onPlay: function()
	{
		if (!tray_open)
			intro_click();
	},
	
	onLoad: function() 
	{
		scientist.showText();
		Swiff.remote(this.swf_obj, 'api_addEventListener', 'onPlay', 'video.onPlay');
		this.loaded = true;
	},
	
	load: function()
	{
		this.play();
		this.pause();
	},
	
	play: function() 
	{
		try {
			Swiff.remote(this.swf_obj, 'api_play');
		} catch(e) { }
	},
	
	pause: function()
	{
		try {
			Swiff.remote(this.swf_obj, 'api_pause');
		} catch(e) { }
	}
});

function checkEmail(val) { 
	if (/^\w+([\.\+-]?\w*)*@\w+([\.-]?\w+)*(\.\w{2,5})+$/.test(val) && val != '')
		return true;
	
	return false;
}
