var RecaptchaOptions = {
   theme : 'white'
};

var twit_checkWinOpen = null;
var twit_windowLogin = null;
function twit_checkForWinClosed() {
	if (!twit_windowLogin.closed) {
		checkWinOpen = setTimeout("twit_checkForWinClosed()", 1000);
		return false;
	}
	if (twit_checkWinOpen) {
		clearTimeout(twit_checkWinOpen);
		twit_checkWinOpen = null;
		twit_windowLogin = null;
	}
	$.get(main_site_uri() + 'rpcs/login.php?service=tw', function() {
		window.location.reload();
	});
	return true;
}
function login_twitter() {
	twit_windowLogin = window.open(main_site_uri() + 'rpcs/twitterLogin.php', '_blank', 'location=0,status=0,menubar=1,height=380,width=800,resizable=0');
	twit_checkWinOpen = setTimeout("twit_checkForWinClosed()", 1000);
}

function login_facebook(callback) {
	FB_RequireFeatures(["Connect"], function() {
		FB.Connect.requireSession(function(exception) {
			FB.Connect.showPermissionDialog('publish_stream,read_stream,email', function() {
				$.get(main_site_uri() + 'rpcs/login.php?service=fb', function() {
					if (callback) {
						callback();
					}
				});
			});
		});
	});
}

function init_light() {
	// hack - for some reason ie7 breaks top bar somehow...
	if ($.browser.msie && $.browser.version < 8) {
		$('#top_bar').css({ marginTop: -18 });
	}

	$('form.login .login_button').click(function() {
		$.getJSON(main_site_uri() + 'rpcs/login.php?email=' + $('form.login .email').attr('value') + '&pass=' + SHA1($('form.login .pass').attr('value')), function(data) {
			if (data.status == 'ok') {
				window.location.reload();
			} else {
				alert(data.message);
			}
		});
		return false;
	});

	function handleUrls() {
		if ($.address.parameter('video_id')) {
			document.location = '?v=' + $.address.parameter('video_id');
		} else if ($.address.parameter('fcast_id')) {
			document.location = '?f=' + $.address.parameter('fcast_id');
		} else if ($.address.parameter('extern_id')) {
			document.location = '?e=' + $.address.parameter('extern_id');
		} else if ($.address.parameter('topic_id')) {
			document.location = '?t=' + $.address.paramater('topic_id');
		} else if ($.address.path() == '/about') {
			if ($.address.parameter('p') == 'contact') {
				document.location = '?about=contact';
			} else if ($.address.parameter('p') == 'privacy') {
				document.location = '?about=privacy-policy';
			} else if ($.address.parameter('p') == 'terms') {
				document.location = '?about=terms-of-use';
			} else if ($.address.parameter('p') == 'team') {
				document.location = '?about=team-rippol';
			} else if ($.address.parameter('p') == 'technology') {
				document.location = '?about=how-it-works';
			} else {
				document.location = '?about=about-rippol';
			}
		}
	}
	handleUrls();
	$.address.change(function() {
		handleUrls();
	});
	
	function wrap_video_thumb_small(thumb_img) {
		var outer = $('<div></div>').addClass('video_thumb_wrapper_small');
		$('<div></div>').addClass('video_thumb_wrapper_small_overlay').appendTo(outer);
		var inner = $('<div></div>').addClass('video_thumb_wrapper_small_inner');
		$('<img />').attr({ src: thumb_img }).appendTo(inner);
		inner.appendTo(outer);
		return outer;
	}

	var showtypes = {
		episode: 'TV Shows',
		movie: 'Movies',
		sports: 'Sports',
		news: 'News',
		lecture: 'Lectures',
		clip: 'Clips',
		live: 'Live',
		political: 'Political',
		tutorials: 'Tutorials',
		trailers: 'Trailers',
		music: 'Music Videos',
		buzzy: 'Buzzy'
	};
	$('#discover_box').attr({ autocomplete: 'off' });
	$('#discover_box').attr({ value: 'What would you like to watch?' });

	$('#discover_box').keyup(function() {
		var q = $(this).attr('value');			
		if (q == '') {
			$.doTimeout('search');
			$('#search_results_wrapper').hide();
		} else {
			$.doTimeout('search', 500, function() {
				var tbl = $('#search_results');
				tbl.empty();
				$.getJSON(main_site_uri() + 'rpcs/search.php?s_vid=1&q=' + q + '&l=6', function(data) {
					$('#search_results_wrapper').show();
					$.each(data.videos, function(i, item) {
						var thumb = wrap_video_thumb_small(item.thumb);
						thumb.css({ float: 'left' });
						var row = $('<tr></tr>');
						var cell = $('<td></td>');
						thumb.appendTo(cell);
						var title = eval('showtypes.' + item.showType) + ' &raquo; ' + item.genre_text + ' &raquo; ';
						if (item.topic_text) {
							title += item.topic_text + ' &raquo; ';
						}
						title += item.title;
						$('<div></div>').html(title).appendTo(cell);
						var desc_area = $('<div></div>').css({ fontSize: 12 });
						if (item.desc) {
							desc_area.html(item.desc);
						} else if (item.description) {
							desc_area.html(item.description);
						}
						desc_area.appendTo(cell);

						cell.click(function() {
							var g = item.genre_text.toLowerCase();
							var showtype_in_url = item.showType;
							if (item.showType == 'lecture') {
								showtype_in_url = 'lectures';
							} else if (item.showType == 'episode') {
								showtype_in_url = 'tv-shows';
							} else if (item.showType == 'music') {
								showtype_in_url = 'music-videos';
							}

							var p = '/watch/' + showtype_in_url + '/' + g + '/';
							if (item.topic_text) {
								p += item.topic_text.toLowerCase() + '/';
							}
							p += item.title.toLowerCase();

							var params = 'g=' + item.genre_id;
							if (item.type == 'topic') {
								params += '&t=' + item.topic_id;
							} else if (item.type == 'video') {
								if (item.topic_id) {
									params += '&t=' + item.topic_id;
								}
								params += '&v=' + item.video_id;
							}
							var uri = '?p=' + p + '&' + params;
							if (main_site_uri().indexOf('http://rippol.com' == 0)) {
								uri = p + '?' + params;
							}
							window.location = uri;
						});
						cell.appendTo(row);
						row.appendTo(tbl);
					});
				});
			});
		}
		return false;
	});
	$('body').click(function() {
		$('#search_results_wrapper').hide();
		$('#register_results_wrapper').hide();
	});
	
	$('.reg_like').keyup(function() {
		var q = $(this).attr('value');			
		if (q == '') {
			$.doTimeout('search');
			$('#register_results_wrapper').hide();
		} else {
			$.doTimeout('search', 500, function() {
				var tbl = $('#register_results');
				tbl.empty();
				$.getJSON(main_site_uri() + 'rpcs/search.php?s_vid=1&q=' + q + '&l=6', function(data) {
					$('#register_results_wrapper').show();
					$.each(data.videos, function(i, item) {
						var thumb = wrap_video_thumb_small(item.thumb);
						thumb.css({ float: 'left' });
						var row = $('<tr></tr>');
						var cell = $('<td></td>');
						thumb.appendTo(cell);
						var title = eval('showtypes.' + item.showType) + ' &raquo; ' + item.genre_text + ' &raquo; ';
						if (item.topic_text) {
							title += item.topic_text + ' &raquo; ';
						}
						title += item.title;
						$('<div></div>').html(title).appendTo(cell);
						cell.click(function() {
							var c = row.clone(false);
							c.click(function() { c.remove(); });
							c.appendTo($('#register_results_final'));
							return false;
						});
						cell.appendTo(row);
						row.appendTo(tbl);
					});
				});
			});
		}
		return false;
	});

	
	var uploadify_settings = {
		uploader: 'scripts/lib/uploadify/uploadify.swf',
		script: 'scripts/lib/uploadify/uploadify.php',
		folder: 'uploads',
		cancelImg: 'scripts/lib/uploadify/cancel.png',
		buttonText: 'Choose video file',
		buttonImg: 'style/white/tweet_video_choose_button.png',
		queueID: 'fileQueue',
		width: 126,
		height: 32,
		rollover: true,
		auto: true,
		onOpen: function(event, queueID, fileObj) {
			//$('#uploadifyUploader').hide();
		},
		onComplete: function(event, queueID, fileObj, response, data) {
			$('.lite_upload_box input[name=file_path]').attr({ value: response });
			$('#fileQueue').html('Upload completed!').css({ fontSize: 14, color: 'green', fontWeight: 'bold' });
			$('#uploadifyUploader').hide();
		},
		onError: function(event, queueID, fileObj, errorObj) {
			alert('Error: ' + errorObj.info);
		}
	};
	if ($('#uploadify').length) {
		setTimeout(function() {
			$('#uploadify').uploadify(uploadify_settings);
		}, 100);
	}
	
	$('.tweet_video_button').click(function() {
		var f = $('.lite_upload_box');
		var video_title = f.find('[name=video_title]').attr('value');
		var video_desc = f.find('[name=video_desc]').attr('value');
		if (video_title == '' || video_title == 'Video Title') { 
			alert('Please specify a title for your video');
			return;
		}
		if (video_desc == '' || video_desc == 'Video Description') {
			alert('Please specify a description for your video.');
			return;
		}
		var twitter_user = f.find('[name=twitter_user]').attr('value');
		var twitter_pass = f.find('[name=twitter_pass]').attr('value');
		var file_path = f.find('[name=file_path]').attr('value');
		if (file_path == '') {
			alert('Please wait until uploading has finished.');
		} else {
			var params = 'video_title=' + video_title + '&video_desc=' + video_desc + '&twitter_user=' + twitter_user + '&twitter_pass=' + twitter_pass + '&file_path=' + file_path;
			$.post(main_site_uri() + 'rpcs/heywatch/uploadAndTweet.php', params, function(data) {
				if (data.status == 'ok') {
					alert('Tweeted! Now login using Twitter to manage your uploaded files.');
					f.find('[name=video_title]').attr({ value: 'Video Title' });
					f.find('[name=video_desc]').attr({ value: 'Video Description' });
					$('#uploadify').empty().uploadify(uploadify_settings);
				} else {
					alert('Error: ' + data.message);
				}
			}, 'json');
		}
	});
}

function prompt_login() {
	var c = $('<div></div>').addClass('login_prompt');
	$('<p></p>').html('You need to log in to use this function.').appendTo(c);
	$('#top_nav_inner .login_facebook').clone(true).appendTo(c);
	$('#top_nav_inner .login_twitter').clone(true).appendTo(c);
	c.show().appendTo('body');
}
