$(document).ready(function() {
	//facebox stuff
	$('a[rel*=facebox]').facebox();
	
	// hide stuff
	$('#record, #record form, #upload, #upload-complete, #import, #import-complete, #loggedout, #signup, #profile, #main .fm-embed-code, .fm-embed-ok, .hidden').hide();

	avSwitches = new Array($("#adda"), $("#addb"), $("#addc"));
	//var avSections = new Array($("#record"), $("#upload"));
	avSections = new Array($("#loggedout"), $("#loggedout"), $("#loggedout"));
	
	loSwitches = new Array($('#loa'), $('#lob'));
	loSections = new Array($('#login'), $('#signup'));
	
	// Record with web cam
	$('#adda').click(function(e) {
		e.preventDefault();
		
			// If logged in, show recorder
			if (checkLogin()) {
				
				var username = get_cookie('sxswusername');
				var password = get_cookie('sxswpassword');
				
				getSessionID(username,password,true);
				
				changeStatus(true);
				sectionSwitch($('#adda'), avSwitches, avSections);
			
			} else {
				// Show login form
				sectionSwitch($('#adda'), avSwitches, avSections);
			
			}
	});
	
	
	// Uploading a file
	$('#addb').click(function(e) {
		e.preventDefault();
		
		// If logged in, show recorder
			if (checkLogin()) {
				
				changeStatus(true);
				// Show login form
				sectionSwitch($('#addb'), avSwitches, avSections);
			
			} else {
				// Show login form
				sectionSwitch($('#addb'), avSwitches, avSections);
			
			}

	});
	
	// Import a file or URL
	$('#addc').click(function(e) {
		e.preventDefault();
		
		// If logged in, show recorder
			if (checkLogin()) {
				
				changeStatus(true);
				sectionSwitch($('#addc'), avSwitches, avSections);
			
			} else {
				// Show login form
				sectionSwitch($('#addc'), avSwitches, avSections);
			
			}
	})
	
	$('#loa').click(function(e) {
		e.preventDefault();
		sectionSwitch($('#loa'), loSwitches, loSections);
	});
	
	$('#lob').click(function(e) {
		e.preventDefault();
		sectionSwitch($('#lob'), loSwitches, loSections);
	});
	
	$('#upload input.fm-submit').click(function(e) {
		e.preventDefault();
		
		var title = $("#upload-title").val();
		var tags = 'sxsw,'+$("#upload-tags").val()+',sxsw'+$('#upload-cat').val();
		var description = '<p>This video was recorded on <a href="http://sxswvideos.com/">SXSWVideos.com</a>.</p>';
		var username = get_cookie('sxswusername');
		var password = get_cookie('sxswpassword');
		// Get a new session (just in case)
		getSessionID(username,password);
		var sessionid = get_cookie('sxswsessionid');
		
		$("#uploadinggif")
		.ajaxStart(function(){
			$(this).show();
		})
		.ajaxComplete(function(){
			$(this).hide();
		});
		
		// Asynchronous uploading
		$.ajaxFileUpload
		(
			{
			url:'php/gateway.php?a=upload&sessionid='+sessionid+'&title='+title+'&tags='+tags, 
			secureuri:false,
			fileElementId:'upload-file',
			dataType: 'json',
			success: function (data, status)
			{
				if(typeof(data.error) != 'undefined')
				{
					if(data.error != '')
					{
						//alert(data.error);
						$('#upload .fm-error').html('The file was not uploaded successfully. '+data.error+' Sorry.');
					}else
					{
						$('#upload').hide();
						$('#upload-complete').show();
						nextSet('sxsw',1,10);
					}
				}
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		}
		);
		
		$('#upload input.fm-submit').attr({src:'images/bt-cancel.gif'});
	});
	
	
	// Importing!
	$('#import input.fm-submit').click(function(e) {
		e.preventDefault();
		
		var title = $("#import-title").val();
		var url = $('#import-url').val();
		var tags = 'sxsw,'+$("#import-tags").val()+',sxsw'+$('#import-cat').val();
		var description = '<p>This video was imported on <a href="http://sxswvideos.com/">SXSWVideos.com</a>.</p>';
		var username = get_cookie('sxswusername');
		var password = get_cookie('sxswpassword');		
		
		var gw = 'php/gateway.php';
		
		$.ajax({
			url: gw,
			type: 'GET',
			data: 'a=import&username='+username+'&password='+password+'&title='+title+'&url='+url+'&description='+description+'&tags='+tags,
			dataType: 'text',
			timeout: 2500,
			error: function(){
				$('.inner').prepend('<p>Could not add to the import queue..</p>');
				theresponse = 'error';
			},
			success: function(message){
				if (message != 'error') {
					
					$('#import').slideUp('slow', function() {
						$('#import-complete').slideDown('slow');
					});
								
				} else {
					// There was an error!
					$('#import .fm-error').val('Sorry, we couldn\'t add your video to the upload queue.');
				
				}
			}});

	});
	
	
	// Login!
	$('#login input.fm-submit').click(function(e) {
		e.preventDefault();
		
		var username = $('#login-user').val();
		var password = $('#login-pass').val();
		
		if ($('#upload').hasClass('on')) {
			getSessionID(username,password,false); // Logs in, and does upload
		} else {
			getSessionID(username,password,true);
		}
		
		// Clear the form
		// Just in case someone
		// else sits down at the computer
		//$('#login-user').val('');
		$('#login-pass').val('');
				
	});
	
	// Log out!	
	$('#profile a').click(function(e) {
		e.preventDefault();
		
		var username = get_cookie('sxswusername');
		var password = get_cookie('sxswpassword');
		var sessionid = get_cookie('sxswsessionid');
		
		// Expire cookies, cuz cookies are nummy nums.
		var cookiedate = new Date();
		var expdate = cookiedate.getTime();
		expdate -= 600*1000; //expires soon (milliseconds) 
		cookiedate.setTime(expdate);
		document.cookie = "sxswsessionid="+sessionid+";expires=" + cookiedate.toGMTString();
		document.cookie = "sxswusername="+username+";expires=" + cookiedate.toGMTString();
		document.cookie = "sxswpassword="+password+";expires=" + cookiedate.toGMTString();
		
		changeStatus(false);
	});
	
	$('#loggedout .fm-cancel').click(function(e) {
		e.preventDefault();
		$('#loggedout').slideUp('slow', function() {
			$('#add-video h3 a').removeClass('on');
			$('#signup').hide();
			$('#lob').removeClass('on');
			$('#login').show();
			$('#loa').removeClass('on');
			$('#loa').addClass('on');
		});
	});
	
	// Saving video information
	// After recording
	$('#record input.fm-submit').click(function(e) {
		e.preventDefault();
		var title = $('#record-title').val();
		var tags = $('#record-tags').val();
		var category = 'sxsw'+$('#record-cat').val();
		var vid = $('#record-vid').val();
		
		tags = tags+','+category;
		
		setVideoInfo(vid,title,'',tags);
		
		nextSet('sxsw',1,10);
		//refreshVideos();
	
	});
	
	$('#signup input.fm-submit').click(function(e) {
		e.preventDefault();
		registerUser();
	});
	
	// Assign classes to form elements (the attribute selector doesn't work in IE; thus the classes)
	
	$('input[type="text"], input[type="password"], input[type="file"]').addClass('fm-input-txt');
	$('input[type="button"], input[type="submit"]').addClass('fm-input-bt');
	$('input[type="checkbox"]').addClass('fm-input-cb');
	$('input[type="radio"]').addClass('fm-input-rd');
	
	// Rounded corners
	$('.inner').each(function(index, el) {
		$('<div class="inner-top"></div>').insertBefore(el);
		$('<div class="inner-bottom"></div>').insertAfter(el);
	});	
	
	// Categories	
	$('ul.category-list li a').click(function(e) {
		e.preventDefault();
		var target = $(e.target);
		if (! target.is('.on')) {
			$('ul.category-list li a').each(function(index, el) {
				$(el).removeClass('on');
			});
			target.addClass('on');
			
			var thetag = target.attr("title");
			
			if (!thetag) {
				thetag = 'sxsw';
			} else {
				thetag = 'sxsw'+thetag;
			}
			
			nextSet(thetag,1,10);
		}
	});
	
	// User profile images
	var vidThumbCounter = 0;
	$('.video-thumbnail').each(function(index, element) {
	if (vidThumbCounter == 4) {
	vidThumbCounter = 0;
	$(element).css({clear:'left'});
	}
	vidThumbCounter++;
	});

	// Preload (unneeded on live?)
	var image = new Image();
	image.src = 'images/simpleplayer.jpg'; // load image into browser
	
	// table stuff
	
	var testCounter = 0;
	$('td').each(function(index, element) {
		if ($(element).text().replace(/^\s*/, "").replace(/\s*$/, "").length > 0) {
			$(element).addClass('full');
		} else {
			$(element).addClass('empty');
		}
	});
	
	$('table tr:nth-child(2)').addClass('tr-second');
	$('table tr td:nth-child(2)').addClass('td-second');
	
	
	
	
	// a useful block of code I wrote in my spare time...
	
	$('ul.tablist li a:not([rel=notab])').click(tabSwitch);
	$('ul.tablist li:first-child').addClass('on');
	$('ul.tablist').each(function(index, element){
		var startingPoint = $(element).parent()
		var counter = 0;
		while(startingPoint.children('.tabsection').length == 0 && counter <= 3) {
			startingPoint = startingPoint.parent();
		}
		startingPoint.children('.tabsection:not(:first)').hide();
	});
	
	function tabSwitch(e) {
		// change the 'current' class
		e.preventDefault();
		var a = $(e.target);
		var li = a.parent();
		var container = li.parent().parent();
		var lastChosen = li.siblings('.on');
		li.siblings().removeClass('on');
		li.addClass('on');
		
		
		// find the tab sections.
		var sections = container.children('.tabsection');
		var counter = 0;
		var moved = false;
		while (container.children('.tabsection').length == 0 && counter <=3) {
			container = container.parent();
			counter++;
			moved = true;
		}
		sections = container.children('.tabsection');
		
		// which link did you click?
		var newIndex = 0;
		li.parent().children().each(function(index, child){
			if($(child).text() == li.text()) {
				newIndex = index;
			}
		});
		if (newIndex>=sections.length) {
			newIndex = -1;
			li.removeClass('on');
			lastChosen.addClass('on');
		}
		// if we found sections outside of our container, only switch the sections if you can't find another ul.tablist
		if (moved && container.children('.tablist').length == 0 || ! moved) {
			if (newIndex >=0) {
				sections.hide();
				sections.eq(newIndex).show();
			}
		}
	}
	
	
	// Check login
	if (loggedin = checkLogin()) {
		fillProfile();
		$('#profile').fadeIn('slow');
	}
	
	watchEvents();
});

function fillProfile() {
	var username = get_cookie('sxswusername');
	var password = get_cookie('sxswpassword');
	
	$('#profile b').html(username);
	
}

function nextSet(tag,p,pp) {
// Gateway
var gw = 'php/gateway.php';

var today = new Date();

$.ajax({
	url: gw,
	type: 'GET',
	data: 'a=videolist&tag='+tag+'&p='+p+'&pp='+pp,
	dataType: 'text',
	timeout: 2500,
	error: function(){
		$('#mastervideolist').html('List of videos currently unvailable. Whoopsie!');
	},
	success: function(response){
		if (response != 'no videos') {
			
			refreshVideos(response);
			
		} else {
			// ERROR!
			alert('No videos in that category yet. Please select another one.');
			//$('#mastervideolist').html('<p class="center">Zounds! Currently there\'s nothing in this category.<br />Why not add some videos to this category yourself? '+today+'</p>');
		}
	}});
}

function getSessionID(username,password,record) {
// Gateway
var gw = 'php/gateway.php';

$.ajax({
	url: gw,
	type: 'GET',
	data: 'a=session&username='+username+'&password='+password,
	dataType: 'text',
	timeout: 2500,
	error: function(){
		$('.inner').prepend('<p>There was an error logging you in.</p>');
		theresponse = 'error';
	},
	success: function(sessionid){
		if (sessionid != 'error') {
			
			// Create cookies, cuz cookies are nummy nums.
			var cookiedate = new Date();
			var expdate = cookiedate.getTime();
			expdate += 600*1000; //expires soon (milliseconds) 
			cookiedate.setTime(expdate);
			document.cookie = "sxswsessionid="+sessionid+";expires=" + cookiedate.toGMTString();
			document.cookie = "sxswusername="+username+";expires=" + cookiedate.toGMTString();
			document.cookie = "sxswpassword="+password+";expires=" + cookiedate.toGMTString();
			
			fillProfile();
			if (record) {
				getRecordToken();
			}
			changeStatus(true);
			
		} else {
			// There was an error!
			$('#login .fm-error').html('Username and/or password are incorrect.');
			
		
		}
	}});
return;
}

function getRecordToken() {
// Gateway
var gw = 'php/gateway.php';
var sessionid = get_cookie('sxswsessionid');

$.ajax({
	url: gw,
	type: 'GET',
	data: 'a=token&sessionid='+sessionid,
	dataType: 'text',
	timeout: 2500,
	error: function(){
		$('.inner').prepend('<p>Could not get a record token.</p>');
		theresponse = 'error';
	},
	success: function(token){
		if (token != 'error') {
			
			$('#therecorder').remove();
			
			$('#record').prepend('<div id="therecorder" class="flash-content"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="449" height="380" id="viddler_recorder" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="movie" value="http://cdn-ll-static.viddler.com/flash/recorder.swf" /><param name="quality" value="high" /><param name="scale" value="noScale"><param name="bgcolor" value="#000000" /><param name="flashvars" value="fake=1&recordToken='+token+'" /><embed src="http://cdn-ll-static.viddler.com/flash/recorder.swf" quality="high" scale="noScale" bgcolor="#000000" allowScriptAccess="always" allowNetworking="all" width="449" height="380" name="viddler_recorder" flashvars="fake=1&recordToken='+token+'" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object></div>');
						
		} else {
			// There was an error!
			//$('.fm-error').val('Username and/or password are incorrect.');
		
		}
	}});
	
return;
}

function getVideoEmed(vid,playertype,width,height) {

		width +='';
		height +='';
		
		if (width == '' || !width) {
			width = '320';
		}
		if (height == '' || !width) {
			height = '282';
		}
		
		if (playertype=='simple') {
			playerurl = 'http://cdn-ll-static.viddler.com/flash/simple_publisher.swf?key='+vid+'&autoplay=t';
		} else {
			playerurl = 'http://www.viddler.com/player/'+vid+'/';
		}
		
		html = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+width+'" height="'+height+'" id="viddler"><param name="wmode" value="opaque"><param name="bgcolor" value="#f3d19f" /><param name="movie" value="'+playerurl+'" /><param name="allowScriptAccess" value="always" />';
		// Auto play?
		if (playertype == 'player') {
			html += '<param name="flashvars" value="autoplay=t" />';
		}
		html += '<param name="allowFullScreen" value="true" /><embed src="'+playerurl+'" wmode="opaque" bgcolor="#f3d19f" width="'+width+'" height="'+height+'" type="application/x-shockwave-flash" allowScriptAccess="always" allowFullScreen="true"';
		// Auto play?
		if (playertype == 'player') {
			html += 'flashvars="autoplay=t"';
		}
		html += ' name="viddler"></embed></object>';
		
	return html;
	
	}
	
function setVideoInfo(vid,title,description,tags) {
	
	var sessionid = get_cookie('sxswsessionid');
	var gw = 'php/gateway.php';
	
	$.ajax({
		url: gw,
		type: 'GET',
		data: 'a=setDetails&sessionid='+sessionid+'&video_id='+vid+'&title='+title+'&description='+description+'&tags='+tags,
		dataType: 'text',
		timeout: 2500,
		error: function(){
			// Error
		},
		success: function(response){
			if (response == 'success') {
			  // Success
			  nextSet('sxsw',1,10);
			} else {
				// Error
			}
		}});
}
	
// Recording is done
function recordDone(u,uvn,vid) {
	// u = username uvn = uservideonumber vid = videoid
	
	// Throw in some default values
	setVideoInfo(vid,'SXSW 2008 video!','Needs a description.','sxsw');
	
	// Remove the recorder
	$('#record object').remove();
	
	// Prefill the form
	$('#record-title').val('SXSW 2008 video!');
	$('#record-vid').val(vid);
	
	$('#record form').show();
}

function registerUser() {

	var gw = 'php/gateway.php';

	var username = $('#signup-user').val();
	var password = $('#signup-pass').val();
	var password2 = $('#signup-confirm').val();
	var fname = $('#signup-fname').val();
	var lname = $('#signup-lname').val();
	var emaila = $('#signup-email').val();
	
	if (username == '' || password == '' || password2 == '' || fname == '' || lname == '' || emaila == '') {
		$('#signup .fm-error.general').html('All fields are required. Please fill in all fields.');
		return;
	}
	
	if (password != password2) {
		$('#signup .fm-error.signup-confirm').html('Your passwords do not match.');
		return;
	}
	
	var args = 'username='+username+'&password='+password+'&fname='+fname+'&lname='+lname+'&email='+emaila;
	
$.ajax({
    url: gw,
    type: 'GET',
    data: 'a=register&'+args,
    dataType: 'text',
    timeout: 2500,
    error: function(){
    	// User registration has failed.
    },
    success: function(userresponse){
    	if (userresponse != 'error' && userresponse != 'error username' && userresponse != 'error email') {
    		
    		$('#login-user').val(userresponse);
    		
    		// Show login form
			//sectionSwitch($('#adda'), avSwitches, avSections);
			sectionSwitch($('#loa'), loSwitches, loSections);
    		
		  } else {
		  	if (userresponse == 'error username') {
		  		errortext = 'This username is already is already in use.';
		  		$('#signup .fm-error.signup-user').html(errortext);
		  	}
		  	if (userresponse == 'error email') {
		  		errortext = 'This email address is already in use.';
		  		$('#signup .fm-error.signup-email').html(errortext);	  	
		  	}
		  	if (userresponse == 'error') {
		  		errortext = 'Error. Please ask for help.';
		  		$('#signup .fm-error.general').html(errortext);
		  	}
		  }
       
    }});
	
}

	
function refreshVideos(html) {
	$('.video-section').fadeOut('slow', function() {
		$('#main .fm-embed').show();
		$('#main .fm-embed-code').hide();
		$('#main .fm-embed-ok').hide();
		$('#mastervideolist').html(html);
		$('.video-section').fadeIn('slow',watchEvents());
	});
}
	
function sectionSwitch(target, switchArray, sectionArray, activeClass) {
	if (activeClass == undefined) { activeClass = 'on' }
	var fade = false;
	var chosenSection = false;
	var unwantedSection = false;
	for (var i = 0;i<switchArray.length;i++) {
		var t = switchArray[i];
		if (t.attr('id') == target.attr('id')) {
			t.not('.'+activeClass).addClass(activeClass);
			var chosenSection = i;
		} else {
			t.removeClass(activeClass);
			if (sectionArray) {
				if (sectionArray[i].is(':visible')) {
					var unwantedSection = i;
					var fade = true;
				}
			}
		}
	}
	if (sectionArray) {
		if (sectionArray == avSections && ($('#upload-complete').is(':visible') || $('#import-complete').is(':visible') )) {
			if ($('#upload-complete').is(':visible')) {
				$('#upload-complete').slideUp('slow', switcherLogic);
			} else if ($('#import-complete').is(':visible')) {
				$('#import-complete').slideUp('slow', switcherLogic);
			}
		} else {
			//switcherLogic(fade,section);
			if (!fade) {
				sectionArray[chosenSection].slideDown('slow');
			} else {
				sectionArray[unwantedSection].slideUp('slow', function() { sectionArray[chosenSection].slideDown('slow'); });
			}
		}
	}
}
	
// Load either recorder, or uploader, or importer
function changeStatus(status) {
	if (status) {
		avSections = new Array($("#record"), $("#upload"), $('#import'));
		$('#loggedout').slideUp('slow', function(){
			for (var i=0;i<avSwitches.length;i++) {
				var t = avSwitches[i];
				if (t.is('.on')) {
					avSections[i].slideDown('slow');
				}
			}
		});
		fillProfile(); // Fill in the username
		$('#profile').fadeIn('slow');
	} else {
		for (var i=0;i<avSwitches.length;i++) {
			var t = avSwitches[i];
			if (t.is('.on')) {
				avSections[i].slideUp('slow', function(){
					$('#add-video h3 a').removeClass('on');
				});
			}
		}
		avSections = new Array($("#loggedout"), $("#loggedout"), $('#loggedout'));
		
		$('#lob').removeClass('on');
		$('#loa').removeClass('on').addClass('on');
		$('#signup').hide();
		$('#login').show();
		$('#profile').fadeOut('slow');
	}
}

function watchEvents() {
	// Load the player	
	$('.vs-play').click(function(e) {
		e.preventDefault();
		var target = $(e.target);
		target.next('img').remove();
		target.parent().html(getVideoEmed(target.attr("title"),'player','291','257')); // Hack?
		target.hide();
	});
	
	$('.fm-embed').click(function(e) {
		var target = $(e.target);
		target.fadeOut('fast', function(){
			target.siblings('.fm-embed-code').fadeIn('fast');
			target.siblings('.fm-embed-ok').fadeIn('fast');
		});
	});
	
	$('.fm-embed-ok').click(function(e) {
		var target = $(e.target);
		target.siblings('.fm-embed-code').fadeOut('fast');
		target.fadeOut('fast', function() {
			target.siblings('.fm-embed').fadeIn('fast');
		});
	});
}

function checkLogin() {
	
	var sessionid = get_cookie('sxswsessionid');
	
	if (!sessionid || sessionid == '') {
		return false;
	}
	
	return true;
}

function get_cookie (cookie_name) {
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

//  Twitter!
function twitterCallback(obj) {
	twitdate = new Date(obj[0].created_at);
	var d=twitdate.getDay();
	var mm=twitdate.getMonth();
	var yy=twitdate.getFullYear();
	var h=twitdate.getHours();
	var m=twitdate.getMinutes();
	var s=twitdate.getSeconds();
	
	document.getElementById('twitter-when').innerHTML = '<a id="twitter-time" href="http://twitter.com/sxswvideos/statuses/'+obj[0].id+'/">'+d+'/'+mm+'/'+yy+' '+h+':'+m+'</a>';

}